特點:數據的發送方只負責發送數據,數據如何接收如何處理都有接收方決定。
在android中發生的就是是各種事件
簡述:一,先註冊廣播接收對象。
二,安卓操作系統產生一個事件時(如接到一個電話),或者自定義發送的廣播。(這些事件都是一個intent對象)
三,通知各Broadcast Receiver,Broadcast Receiver判斷該事件是否它要處理的事件,然後進行相應處理。
四,事件(intent對象)和filter對象都有action屬性,只有兩者對上了才能允許intent通過。
五,BroadcastReceiver的生命週期:onReceiver調用結束,生命週期結束。
ps:intent裏面的action和data的關係:比如洗衣服,洗臉。action是動作,data是對象。同一個動作不同對象處理方式也不一樣。
廣播發送方Intent intent=new Intent();
intent.setAction(Intent.ACTION_EDIT);
sendBroadcast(intent);
廣播接收器要extends BroadcastReceiver ,然後覆寫public void onReceive(Context context, Intent intent){ } 方法
BroadcastReceiver 註冊:
一,在清單文件中註冊:
<receiver android:name=".receiver">
<intent-filter >
<action android:name="android.intent.action.EDIT"/> //該接收器接收什麼事件就在這裏定義
</intent-filter>
</receiver>
//特點:無論程序開或關,該接收器都能接受相應的廣播
二,在應用程序代碼中註冊:
receiver=new BroadcastReceiver(); //生成一個接收器對象,另一個類
IntentFilter filter=new IntentFilter(); //生成一個過濾器對象
filter.addAction(android.provider.); //爲過濾器增添action
registerReceiver(receiver, filter)
//參數一是一個接收器,參數二是該接收器的過濾器
unregisterReceiver(receiver);
//特點:若寫在onCreat()中,在activity可見的時候註冊,在其不可見的時候取消註冊,節省了資源
Android內置的Broadcast Action (各種手機系統事件)
ACTION CAMERA BUTTON 按下照相機按鈕就會觸發
ACTION BARRERY LOW 電池電量低時觸發
……