背景
Android中的廣播有兩種注冊方式:
1,程序中動態(tài)注冊;
2,清單文件中靜態(tài)注冊;
#區(qū)別:作用域不同,動態(tài)注冊的接收者只能在進(jìn)程內(nèi)通訊,而靜態(tài)注冊范圍更廣佩研,可以跨進(jìn)程通訊础嫡。
廣播發(fā)送器
Button send = (Button) findViewById(R.id.send);//初始化控件
send.setOnClickListener(new View.OnClickListener() {//監(jiān)聽
@Override
public void onClick(View v) {
//通過Itent攜帶信息
Intent intent = new Intent();
intent.putExtra("flag","高級配置");
//設(shè)置廣播的action,只有和這個action一樣的接受者才能接受才能接收廣播
intent.setAction("flag");
//發(fā)送廣播
sendBroadcast(intent);
Log.d("send", "高級配置");
}
});
廣播接收者
在背景中可知投剥,要想實現(xiàn)跨進(jìn)程通訊需要靜態(tài)注冊廣播
代碼如下:
manifest文件中:
<receiver android:name=".MyBroadCastReceiver">
<intent-filter>
<action android:name="flag"></action>
</intent-filter>
</receiver>
知識點:靜態(tài)注冊廣播需要單獨寫成類焕梅,不能寫成內(nèi)部類
/**
* Created by xuchen on 2017/4/17 9:22.
* Email:chenxu4@iflytek.com
*
* 清單文件中靜態(tài)注冊:需要單獨寫成類
*/
public class MyBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("flag");
Log.d("message","message="+message );
}
}
日志切圖
Paste_Image.png