android有序广播终止广播,Android有序广播

本文详细介绍了Android中的有序广播,包括其与普通广播的区别,如何发送有序广播,以及如何通过权限控制接收顺序。示例展示了如何创建并发送有序广播,以及在不同广播接收器中如何处理和传递数据,同时演示了如何中断广播。通过示例代码,读者能清晰地了解有序广播的工作原理和应用场景。

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值