Broadcast
廣播的分類
是否靜態 | 是否有序 |
---|---|
靜態 | 有序 |
動態 | 普通 |
各種廣播特點
靜態廣播
特點
- 在配置文件中 定義
- 在app未啓動時也可接收
在配置文件中定義
同配置Activity的結構相同,通過action與category來匹配
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.zhao.intentdemo.testbc"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
動態註冊廣播
特點
- 在代碼中對接收器進行註冊
- 在app退出前需要結束註冊
動態註冊
//註冊
registerReceiver(receiver, filter);
//解除註冊
unregisterReceiver(receiver);
無序廣播(普通)
特點
- 所有廣播會一起收到廣播
- 廣播不可以被截斷同時也不可以對傳輸的數據進行修改
發送序廣播
- 設置需要匹配的action 與 category
- 然後發送出去
Intent intent = new Intent("com.zhao.BroadcastDemo.MY_BROADCASTRECEIVER");
sendBroadcast(intent);
有序廣播
特點
- 廣播的傳遞方式是一個接一個的傳遞的
- 若被某個接收器截斷 後續接收器將無法再獲取
- 可以對傳輸的數據進行修改 然後再傳遞到下一個接收器
- 可以添加匹配權限(若無權限 將無法匹配成功)
- 爲每個監聽器設置優先級
發送有序廣播
Intent intent = new Intent("com.zhao.BroadcastDemo.MY_BROADCASTRECEIVER");
//發送有序廣播 第二參數爲添加的權限
sendOrderedBroadcast(intent,null);
截斷有序廣播(後續廣播無法接收)
public void onReceive(Context context, Intent intent) {
//截斷 不繼續傳遞廣播
abortBroadcast();
}
設置接收器的優先級
<receiver android:name=".BroadcastReceiver_3" >
<intent-filter android:priority="10">
<action android:name="com.zhao.BroadcastDemo.MY_BROADCASTRECEIVER"/>
</intent-filter>
</receiver>
android:priority=”10” 值越大 優先級越高
修改廣播中傳輸的數據(後續廣播將收到經過該接收器處理過的數據)
public void onReceive(Context context, Intent intent) {
Bundle bundle = new Bundle();
bundle.putString("msg","new data");
//用自己定義的Bundle 替換數據
setResultExtras(bundle);
}