Android9.0 BroadcastReceiver案例分析附源碼

Android BroadcastReceiver用於異步進程間通信,類似於發佈-訂閱的設計模式,不像Activity那樣有界面,它是一個Android組件,用於向系統或者應用程序廣播消息,這種廣播消息指的是事件或者intent(意圖)。具體例子像系統的電源容量低通知,下載通知等。
常用的系統intent有:
android.intent.action.BATTERY_CHANGED
android.intent.action.BATTERY_LOW
android.intent.action.POWER_CONNECTED
android.intent.action.POWER_DISCONNECTED
android.intent.action.BOOT_COMPLETED
android.intent.action.CALL
android.intent.action.DATE_CHANGED
android.intent.action.REBOOT
android.intent.action.CONNECTIVITY_CHANGE
android.intent.action.BUG_REPORT
android.intent.action.CALL_BUTTON

Android中大致有兩種廣播消息:
1.有序廣播
2.無序廣播

有序廣播是同步型廣播,按序發送廣播消息,序號按照android:priority 屬性排列。相同優先級的廣播消息將沒有先後之分。
無序廣播則是異步型廣播,隨機發送廣播消息,使用Context:sendBroadcast發送廣播消息。

要實現BroadcastReceiver,首先需要註冊這個receiver。
有兩種方式:
1.通過Context 註冊

<receiver android:name="DataReceiver" >
             <intent-filter>
                 <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
             </intent-filter>
</receiver>

2.通過Manifest註冊

IntentFilter filter = new IntentFilter();
intentFilter.addAction(getPackageName()+"android.net.conn.CONNECTIVITY_CHANGE");
MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);

注意:Android8以上需要在代碼中註冊receiver纔行。

具體細節請參考完整案例:
開發環境:Android Studio4.0
TestBroadcastReceiver.zip:

MyBroadcastReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter filter = new IntentFilter("com.funny.CUSTOM_INTENT");
        receiver = new MyBroadcastReceiver();
        registerReceiver(receiver, filter);
    }

在這裏插入圖片描述

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