一. 广播的机制
action是在广播接受器的创建一起定义的,只要广播一个action,符合action的值的就接受广播并进行操作。
-1.在配置文件中一个静态注册的Firstreceive广播接受器
<receiver android:name="com.example.n_2boradcast.Firstreceive" >
<intent-filter android:priority="100">
<action android:name="first" />
</intent-filter>
</receiver>
-2.在activity 的onCreate方法中动态注册的Second广播接受器
Second second = new Second();
IntentFilter filter = new IntentFilter();
filter.addAction("first");
// filter.setPriority(120);
registerReceiver(second, filter);
-3.动态注册需要注销掉second ,否则关闭应用出现异常:unregisterReceiver(receiver);这里用一个方法@Override
protected void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(second);
super.onDestroy();
}
*****有道云笔记 http://note.youdao.com/noteshare?id=0a48e1cba6c4cd88f9a170d9706a92b5
二,无序广播
这里拿一个按钮来实现发送一个action给全局进行广播操作,这里只有符合action的广播接收器就可以接受并处理
-1.在UI中的按钮去广播并带参数
public void btn1(View v) {
Intent intent = new Intent();
intent.setAction("first");
intent.putExtra("date", "我是超级英雄");
sendBroadcast(intent);
}
-2. 广播接收器接受数据并在实现方法进行处理数据
@Override
public void onReceive(Context context, Intent intent) {
String date = intent.getStringExtra("date");
Toast.makeText(context, "这是无序广播的数据+"+date, Toast.LENGTH_SHORT).show();
//中断广播
//abortBroadcast();