Android-Broadcast Receiver(廣播接收器)

Override0330發表於2019-04-12

簡單記錄Broadcast Receiver(廣播接收器)的簡單實用

1. 廣播分類

1.1 Normal broadcasts 標準廣播

完全非同步的廣播,所有的廣播接收器幾乎同時受到廣播且無法截斷。

1.2 Ordered broadcast 有序廣播

顯然對比與標準廣播,有序廣播就是有序的,可以設定各個接收器的優先順序,可以被截斷。

2. 註冊全域性廣播接收器

全部廣播代表,整個Android系統中的所有廣播接收器都可以收到的廣播

2.1 動態註冊廣播接收器

接受系統廣播

主要步驟如下:

  1. 自定義廣播接收器繼承自BroadcastReceiver,並重寫onReceive方法
class NetWorkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            networkInfo = connectivityManager.getActiveNetworkInfo();//需要申請許可權
            if (networkInfo != null && networkInfo.isAvailable())
                Toast.makeText(context,"網路開啟了",Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(context,"網路關閉了",Toast.LENGTH_SHORT).show();
        }
    }
複製程式碼
  1. 在程式碼中新建一個自定義廣播接收器的例項,並在Activity中註冊,註冊時需要傳入該廣播接收器所接受的廣播型別。
public class MainActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private NetworkInfo networkInfo;
    private NetWorkReceiver netWorkReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intentFilter = new IntentFilter();
        netWorkReceiver = new NetWorkReceiver();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//設定廣播接收器接受的內容
        registerReceiver(netWorkReceiver,intentFilter);//註冊廣播接收器
    }
}
複製程式碼
  1. 在Activity的onDestroy方法中要取消註冊廣播接收器。
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkReceiver);
    }
複製程式碼

此時變設定好了一個接受系統廣播的廣播接收器,當資料網路開關出現變化時,會接受到相應的廣播併發出Toast資訊。

2.2 註冊靜態廣播接收器

靜態廣播接收器還有一個特性,那就是在系統沒有啟動的時候就能夠接受廣播並對他進行處理

2.2.1 接受系統廣播(開機啟動)
  1. 同樣自定義廣播接收器繼承自BroadcastReceiver,並重寫onReceive方法
public class BootCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"開機了!",Toast.LENGTH_LONG).show();
    }
}
複製程式碼
  1. 在AndroidManifest.xml檔案中註冊(如果使用as自動建立的則自動註冊)
<application
        >
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        //廣播接收器註冊
        <receiver android:name=".BootCompleteReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action
                    android:name="android.intent.action.BOOT_COMPLETED"></action>
            </intent-filter>
        </receiver>
    </application>
複製程式碼
2.3 傳送自定義廣播並接收

自定義的廣播使用靜態註冊

2.3.1 傳送標準廣播
  1. 廣播接收器註冊

步驟同靜態廣播接收器一致,不過在AndroidManifest.xml檔案中不僅僅註冊時,廣播接收器的標籤裡應該填寫自己自定義的廣播名

......
<intent-filter>
                <action
                    android:name="com.override0330.example"></action>
            </intent-filter>
......
複製程式碼
  1. 傳送廣播-使用Intent傳送:
......
Intent intent = new Intent("com.override0330.example");
sendBroadcast(intent);
......
複製程式碼
2.3.2 傳送有序廣播
  1. 廣播接收器註冊

步驟同傳送標準廣播一致,但是多加入一個優先順序的設定

......
<intent-filter android:priority="98">//設定優先順序為98,最高為100
                <action
                    android:name="com.override0330.example"></action>
            </intent-filter>
......
複製程式碼
  1. 傳送有序廣播
Intent intent = new Intent("com.override0330.example");
sendOrderBroadcast(intent, null);//null引數為一個與許可權相關的字串,一般情況傳入null
複製程式碼
  1. 截斷廣播

在想要截斷的廣播接收器的onReceive裡使用

abortBroadcast();//截斷該廣播
複製程式碼

3.使用本地廣播

本地廣播區別於全域性廣播,它只在本應用程式中傳遞,如果掌握了全域性廣播,那麼本地廣播的使用是非常簡單的。而且貌似本地廣播只能使用標準廣播。 將上圖中我們使用的註冊廣播接收器和傳送廣播的方法改為使用由LocalBroadcastManager的方法:

//獲取LocalBroadManage例項
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
//傳送本地廣播
localBroadcastManager.sendBroadcast(intent);
//註冊本地廣播接收器
localBroadcastManager.registerReceiver(localBroadReceiver,intentFilter);
複製程式碼

4. 總結

廣播的使用還是相當簡單的,但是它的底層實現還有待我的研究√

相關文章