廣播主要分為兩種類型:標準廣播(完全異步執行的廣播)和有序廣播(完全同步執行的廣播)。我們也可以根據廣播是否可以跨進程接收,將廣播分為:系統全局廣播和本地廣播
- 系統全局廣播:發出的廣播可以被其他任何程序接收到,并且我們也可以接收來自其他任何應用程序的廣播
- 本地廣播:發出的廣播只能在應用程序的內部進行傳遞,廣播接收器也只能接收本應用程序發出的廣播
發送系統全局廣播
- 標準廣播
發送廣播借助的是Intent
對象,使用的是Context對象的sendBroadcast()
方法發送廣播。
代碼實現:
//構建一個Intent對象,傳入要傳遞的廣播
Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
//調用sendBroadcast方法發送出標準廣播
sendBroadcast(intent);
- 有序廣播
發送有序廣播和發送標準廣播思路基本一致,發送有序廣播時,調用的是Context對象的sendOrderedBroadcast()方法:
Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
//發送有序廣播,第二個參數是與權限相關的字符串,傳入null即可
sendOrderedBroadcast(intent, null);
發送有序廣播時,進程接收廣播是有順序的,并且可以劫持廣播,設置廣播接收優先級:在配置文件中配置<receiver>
標簽時,給<intent-filter>
標簽添加屬性"android:priority="xxx""
,實現攔截廣播,調用方法:abortBroadcast()
發送本地廣播
發送本地廣播主要使用LocalBroadcastManager來對廣播進行管理,并提供了發送廣播和注冊廣播接收器的方法
代碼實現:
public class MainActivity extends Activity {
private IntentFilter intentFilter;
private LocalReceive localReceive;
private LocalBroadcastManager localBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取到LocalBroadcastManager實例對象
localBroadcastManager = LocalBroadcastManager.getInstance(this);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//創建Intent對象,指定廣播內容
Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
//發送本地廣播
localBroadcastManager.sendBroadcast(intent);
}
});
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
localReceive = new LocalReceive();
//注冊本地廣播接收器
localBroadcastManager.registerReceiver(localReceive, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
//動態注冊,同樣需要取消注冊廣播
localBroadcastManager.unregisterReceiver(localReceive);
}
class LocalReceive extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show();
}
}
}
本地廣播是無法通過靜態注冊的方式來接收的,因為靜態注冊主要就是為了讓程序在未啟動的情況下也能收到廣播,而發送本地廣播時,我們的程序肯定已經啟動了