Android開發之淺談廣播的運用

之前講過了activity,服務service和內容提供者,四大組件就還差廣播沒講,所以就順便講講吧。當然,這裏都是很基礎的講解,沒有深入,要是深入的話光一個activity就可以講很久。所以這裏只做基礎使用的講解了。

時間緊迫,直接上代碼吧。

首先,廣播有兩種註冊方式,一種在清單文件中註冊,註冊後程序一運行廣播就開始監聽。一種在代碼中註冊,根據需求註冊註銷廣播。

我們先看廣播的第一種註冊方式,首先定義一個廣播接受者

package com.batways.apopo.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * @ClassName: TestReciver
 * @author victor_freedom ([email protected])
 * @createddate 2015年2月28日 下午9:31:23
 * @Description: TODO
 * 
 */
public class TestReciver extends BroadcastReceiver {

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		// TODO Auto-generated method stub

	}

}
然後再清單文件中註冊

  <receiver android:name="com.batways.apopo.receiver.TestReciver" >
            <intent-filter>
                <action android:name="aaa.bbb.ccc" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
這樣,當程序啓動的時候,廣播就開始監聽動作爲“aaa.bbb.ccc”的意圖。


接下來再看在代碼中註冊廣播

首先在代碼中new一個廣播接受者

	private class UpdateCreditsBroadCast extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			
		}

	}
然後用代碼註冊:category可以填可以不填

mUpdateCreditsBroadCast = new UpdateCreditsBroadCast();
		IntentFilter filter = new IntentFilter("com.batways.apopo_core.service");
		//filter.addCategory(Intent.ACTION_DEFAULT);
		registerReceiver(mUpdateCreditsBroadCast, filter);

一般而言,在該註冊文件的生命週期函數中的起始函數註冊廣播,在結束函數中註銷廣播:

unregisterReceiver(mUpdateCreditsBroadCast);
		mUpdateCreditsBroadCast = null;

這樣,就完成了再代碼中廣播的註冊與註銷。

那麼,我們發送廣播的時候,該怎麼弄呢。這裏博主提供一個廣播工具類吧,一般的都能滿足使用了。這裏需要特別注意,如果廣播註冊的時候加了category,這裏就需要加,如果沒有,這裏就不需要加了。

public class BroadcastHelper {

	
	/**
	 * 發送String 類型的值的廣播
	 * @param context
	 * @param action
	 * @param key
	 * @param value
	 */
	public static void sendBroadCast(Context context,String action,String key,String value) {
		Intent intent = new Intent();
        intent.setAction(action);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra(key, value);
        context.sendBroadcast(intent);
	}
	
	public static void sendBroadCast(Context context,String action,String key,int value) {
		Intent intent = new Intent();
		intent.setAction(action);
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		intent.putExtra(key, value);
		context.sendBroadcast(intent);
	}
	

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章