Android BroadcastReceiver使用,可實現程序間通訊
阿新 • • 發佈:2018-11-05
1、建立廣播接收器:
/** * 作者:created by meixi * 郵箱:[email protected] * 日期:2018/11/1 09 */ public class MyBroadcastReceiver extends BroadcastReceiver { //需要實現的方法 @Override public void onReceive(Context context, Intent intent) { Log.i("lgq","sssssssMyBroadcastReceiver"+intent.getStringExtra("br")); } }
2、靜態註冊廣播
<receiver android:name="com.administrator.receivers.MyBroadcastReceiver" android:exported="true" android:enabled="true"> <intent-filter> <action android:name="com.weimore.example.MY_BROADCAST"/> </intent-filter> </receiver>
3、動態註冊廣播
//自定義的廣播接收器 MyBroadcastReceiver mReceiver = new MyBroadcastReceiver(); //過濾器,其中傳入一個action IntentFilter filter = new IntentFilter("com.weimore.example.MY_BROADCAST"); //註冊廣播 registerReceiver(mReceiver,filter);
需要注意的是,動態註冊的廣播接收器一定要登出,在onDestroy方法中呼叫unregisterReceiver(recevier);
4、傳送廣播
//建立Intent物件 Intent intent = new Intent(); // Intent intent = new Intent( MainActivity.this, MyBroadcastReceiver.class);//靜態註冊寫法 //指定action intent.setAction("com.weimore.example.MY_BROADCAST");//動態註冊寫法 intent.putExtra("br","llllgggqqq"); //傳送廣播 sendBroadcast(intent);
5、外部應用通過action傳送廣播,實現程序間通訊
Intent intent = new Intent(); // Intent intent = new Intent( MainActivity.this, MyBroadcastReceiver.class); //指定action intent.setAction("com.weimore.example.MY_BROADCAST"); intent.putExtra("br","llllgggqqqweilaisssss"); //傳送廣播 sendBroadcast(intent);