-廣播是跨進程的通信方式,任何應用都可以收到不同程序發出的廣播。
接收廣播需要進行廣播注冊,才能接收到對應廣播。
動態注冊
- 必須程序啟動后才能接受廣播
- 動態注冊的廣播接收器都要取消注冊
//實例化IntentFilter和MyReceiver對象
IntentFilter intentFilter = new IntentFilter();
MyReceiver myReceiver = new MyReceiver();
//為IntentFilter添加action,廣播接收器才能監聽到發出以下值的廣播
intentFilter.addAction("android.intent.action.ACTION_POWER_CONNECTED");
//注冊,傳入廣播接收器對象和IntentFilter對象
registerReceiver(myReceiver,intentFilter);
//在onDestroy里解除注冊
@Override
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(myReceiver);
}
靜態注冊
- <application>下添加新標簽<receiver>
- Android Studio快捷創建廣播接收器,右鍵包名->New->Other->Broadcast Receiver
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<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=".MyReceiver" //廣播接收器名
android:enabled="true" //表示是否啟用此廣播接收器
android:exported="true"> //表示是否允許接收本程序以外的廣播
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
//添加相應廣播值的action
</intent-filter>
</receiver>
</application>
接收廣播
創建廣播接收器,定義一個類繼承自BroadcastReceiver,并重寫父類onReceive()方法,當接收到廣播時,就會執行onReceive()方法
- 廣播接收器中不允許開啟線程,因為廣播接收器生命周期非常短,容易對開啟的線程失去控制
- 不要在onReceive()方法中添加過多邏輯或耗時操作
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//實現邏輯
}
}
發送自定義廣播
1.發送標準廣播
Intent intent=new Intent("com.example.MY_BROADCAST");
sendBroadcast(intent);
構建一個Intent對象,將要發送的廣播值傳入,然后調用sendBroadcast()方法,就可以將此廣播發送出去
2.發送有序廣播
Intent intent = new Intent("com.example.MY_BROADCAST");
//傳入Intent對象,第二個參數與權限有關的字符串,可傳入null
sendOrderedBroadcast(intent,null);
- 發送有序廣播,廣播接收器有接收順序,優先級高的先接收到,并可以阻斷其繼續傳播,在onReceive()方法中調用abortBroadcast()方法,截斷這條廣播
- 在AndroidManifest.xml中設置廣播接收器的優先級priority
<receiver
.......
<intent - filter android:priority="100">
<action ........................../>
</intent - filter>
</receiver>
使用本地廣播
本地廣播只在應用內部傳遞,使用本地廣播主要使用LocalBroadcastManager對廣播進行管理,并提供發送廣播和注冊廣播接收器的方法
//調用getInstance()得到LocalBroadcastManager對象
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
//廣播接收器對象和IntentFilter對象
MyReceiver myreceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
//添加action
intentFilter.addAction("com.example.MY_BROADCAST");
//注冊本地廣播監聽器
localBroadCastManager.registerReceiver(myReceiver,intentFilter);
//解除注冊
localBroadcastManager.unregisterReceiver(myReceiver);
發送本地廣播
傳入intent對象
localBroadcastManager.sendBroadcast(intent);