一、 定義 當一個事件發生的時候,就會發送一個廣播,所有註冊了這個廣播的接收者都可以接收這個廣播,也就是說一個廣播可以被多個接收者接收二 、廣播的接收 1、資訊清單檔中註冊(永久註冊,除非卸載)
Receiver Bundle bundle= }
<receiver android:name="com.example.receiver.Receiver"> <intent-filter android:priority="1000"> <action android:name="android.intent.action.ACTION_SHUTDOWN"/> </intent-filter> </receiver>
2、代碼註冊臨時的廣播接收者 在activity啟動時註冊廣播接收者(onCreate()),在activity退出時登出廣播接收者(onDestroy())
receiver = IntentFilter filter= IntentFilter("com.broadcast.ORDER" filter.setPriority(1000 }三、發送廣播 a、普通廣播:接受者之間不能中斷(absort),不能互傳資料(result)
Intent intent= Intent("com.broadcast.NORMAL" sendBroadcast(intent,); b、有序廣播:接收者之間可以中斷,可以傳遞資料,
Intent intent= Intent("com.broadcast.ORDER" intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); sendOrderedBroadcast(intent,);四、發送廣播時傳遞資料 a、intent傳遞資料,該資料不可被修改(需要重新發布) 向intent中添加資料
intent.putExtra("data","添加資料");
擷取各自對應的資料
intent.getStringExtra("data");
b、ResultAPI傳遞資料,有序廣播可以使用ResultAPI傳遞資料
Bundle bundle= bundle.putString("name","張三" bundle.putInt("age",21 sendOrderedBroadcast(intent,,,,1,"MainActivity",bundle);
擷取各自的資料
code=getResultCode(); String data=getResultData(); Bundle bundle=getResultExtras();
修改結果資料 在有序廣播中,接收者是將資料一個給一個傳遞的,是個鏈式結構,後面的接收者可以接收前面修改後的數
bundle.putString("name","王族" bundle.putInt("age",25 setResult(6,"Paris",bundle);五、中斷廣播(有序廣播中可操作) abortBroadcast()可中斷廣播,後面就不會收到廣播,sendOrderedBroadcast()中若第三個參數賦值ResultReceiver, 還是會收到廣播,始終都是最後一個接收到六、廣播許可權 a、發送端要求接收端的許可權(要求接收者必須有許可權)
接收端必須持有發送端的許可權才可以接收這個廣播
<permission/>聲明許可權---在發送端聲明這個許可權
<uses-permission/>使用許可權---在接收端使用這個許可權才可以收到廣播
b、接收端要求發送端的許可權
在<receiver/>標籤中指定android:permission=""許可權,發送端必須有這個許可權,接收端才會接收它的廣播;若無許可權,接收端不接收廣播七、生命週期 從收到廣播的時候生命週期開始,到執行onReceive()方法執行結束,生命週期結束,進程中如果沒有其他組件,容易被殺死