Android中的廣播使用小結
(1)實現一個動態廣播接收器
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
abortBroadcast();
}
}複製程式碼
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
myBroadcastReceiver = new MyBroadcastReceiver();
registerReceiver(myBroadcastReceiver, intentFilter);複製程式碼
(2)實現一個靜態廣播接收器
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>複製程式碼
(3)傳送廣播
Intent intent = new Intent("android.net.conn.CONNECTIVITY_CHANGE");
sendBroadcast(intent); // 傳送廣播複製程式碼
(4)登出廣播
unregisterReceiver(myBroadcastReceiver);
分析:從使用上來看,需要分析一下BroadcastReceiver和IntentFilter原始碼,需要分析函式ContextImpl.registerReceiver和ContextImpl.sendBroadcast以及ContextImpl.unregisterReceiver原始碼。
- A.BroadcastReceiver
- B.IntentFilter
- C.ContextImpl.registerReceiver
- D.ContextImpl.sendBroadcast
- E.ContextImpl.unregisterReceiver