知识点:
- 广播的发送分为:普通广播、有序广播
- 广播的注册分为:静态、动态
先看普通广播:
静态注册方式
1、定义一个广播接收类,继承BroadcastReceiver
public class MyBroadCast_One extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("MyBroadCast_One收到广播消息:"+intent.getExtras().getString("msg"));
}
2、AndroidManifest.xml注册这个广播接收器,注意filter筛选广播
<receiver android:name="com.bzx.androidlearning.MyBroadCast_One">
<intent-filter>
<action android:name="BC"/>
</intent-filter>
</receiver>
3、MainActivity中发送广播,注意是sendBroadcast普通广播。setAction可以理解为这个广播的名字,上一个步骤中intent-filter筛选出这个广播
Intent intent1 = new Intent();
intent1.putExtra("msg", "这是一条普通广播");
intent1.setAction("BC");
sendBroadcast(intent1);
动态注册方式
1、和静态区别在于,不用在manifest中进行注册 ,直接在activity中进行注册。注意,注册内容要写在发送广播前面。
//动态注册广播
myBroadCast_Two = new MyBroadCast_Two();
IntentFilter intentFilter = new IntentFilter("BC");
registerReceiver(myBroadCast_Two, intentFilter);
2、动态注册的广播要在activity销毁时进行解绑
@Override
protected void onDestroy() {
//动态注册广播要在销毁时取消注册
unregisterReceiver(myBroadCast_Two);
super.onDestroy();
}@Override
有序广播:
1、activity中有序广播发送,注意是sendOrderedBroadcast
Intent intent2 = new Intent();
intent2.putExtra("msg", "这是一条普通广播");
intent2.setAction("BC");
sendOrderedBroadcast(intent2, null);
2、与普通广播一点差别在于广播接收部分。有序广播可以对消息进行截断或者处理。这里MyBroadCast_Two 因为是动态注册,所以优先级高一些,先接收到广播后,可以对广播进行处理setResultExtras
public class MyBroadCast_Two extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("MyBroadCast_Two收到广播消息");
Bundle bundle = new Bundle();
//abortBroadcast();
bundle.putString("msg", "MyBroadCast_Two截断的消息");
setResultExtras(bundle);
}
}
3、MyBroadCast_One后接收到广播。通过 getResultExtras(true)接收MyBroadCast_Two 处理后的广播消息。另外,MyBroadCast_Two 中注释的部分abortBroadcast()如果使用的话,就会截断广播,MyBroadCast_One就不会收到发送的广播了
public class MyBroadCast_One extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("MyBroadCast_One收到广播消息:"+intent.getExtras().getString("msg"));
Bundle bundle = getResultExtras(true);
System.out.println("MyBroadCast_One收到截断的消息:"+bundle.getString("msg"));
}
}
网友评论