Android中有序广播的发送与接收
有序广播:
1.普通广播是完全异步的,可以在同一时刻(逻辑上)被所有接收者接收到,消息传递的效率比较高,但缺点是是不能控制接收的顺序,接收者不能将处理结果传递给下一个接收者,并且无法终止广播,而有序广播可以解决以上问题
2.有序广播是用权限控制多个广播接收器接收同一个广播时的接收顺序,并且可以中止广播,也可以将广播接收器接收的地方把值传给下一个接收的广播接收器(不能修改之前的值)
3.有序广播的发送,例:下面代码是发送了有序广播
该广播类型为farsight.inf,装有数据school:三人行,自定义广播权限为far.sight的广播
(例子1)
Intent intent = new Intent();
intent.setAction("farsight.inf");
Bundle bundle = new Bundle();
bundle.putString("school", "三人行");
intent.putExtras(bundle);
sendOrderedBroadcast(intent,"far.sight");
在发送广播时调用ContextWrapper类中的sendOrderedBroadcast函数(Activity继承了ContextWrapper),而不是sendBroadcast函数,并且sendOrderedBroadcast函数中有两个参数,第二个参数是为有序广播自定义权限,该权限是必须的。
4.接收有序广播的广播接收器,下面定义了三个广播接收器
public class OneBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "OneBroadcasReceiver...", Toast.LENGTH_LONG).show();
Bundle bundle = intent.getExtras();//可以用new Bundle();运行结果也一样
bundle.putString("school", "三人行私人培训");
bundle.putInt("age", 100);
this.setResultExtras(bundle);
}
}
public class TwoBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("TwoBroadcastReceiver");
Bundle bundle = intent.getExtras();
String school = bundle.getString("school");
int age = bundle.getInt("age");
String inf = "school:"+school+",age:"+age;
System.out.println(inf);
Bundle bundle2 =this.getResultExtras(true);
String school2 = bundle2.getString("school");
int age2 = bundle2.getInt("age");
String inf2 = "school:"+school2+",age:"+age2;
System.out.println(inf2);
abortBroadcast();//中断广播
}
}
public class ThreeBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("ThreeBroadcastReceiver");
}
}
在AndroidManifest.xml文件中配置广播接收器
......
t;
本文详细介绍了Android中的有序广播,包括其与普通广播的区别,如何发送有序广播,以及如何通过权限控制接收顺序。示例展示了如何创建并发送有序广播,以及在不同广播接收器中如何处理和传递数据,同时演示了如何中断广播。通过示例代码,读者能清晰地了解有序广播的工作原理和应用场景。

846

被折叠的 条评论
为什么被折叠?



