BroadcastReceiver使用方式
2016-09-11 14:49
351 查看
BroadcastReceiver使用方式有两种启动方式
第一种 :静态注册第二种 : 动态注册
现在我们来讲第一种静态方式:
广播接收者简单地说就是接收广播意图的Java类,此Java类继承BroadcastReceiver类,重写:public void onReceive(Context context,Intent intent),其中intent可以获得传递的数据;
广播意图就是通过Context.sendBroadcast(Intent intent)或Context.sendOrderedBroadcast(Intent intent)发送的意图,通过这个语句,能够广播给所有满足条件的组件,比如intent设置了action=”ACTION”,则所有在AndroidManifest.xml中设置过的广播接收者都能够接收到广播;
注:onReceive方法必须在10秒内完成,如果没有完成,则抛“Application No Response”当广播接收者onReceive方法需要执行很长时间时,最好将此耗时工作通过Intent发送给Service,由Service完成,并且不能使用子线程解决,因为BroadcastReceiver是接收到广播后才创建的,并且生命周期很短,因此子线程可能在没有执行完就已经被杀死了。
public void onReceive(Context context,Intent intent){
Intent intent = new Intent(context,XxxService.class);
context.startService(intent);
}
2.广播发送者
通常广播发送方就是调用Context.sendBroadcast()的程序,而广播接收者就是继承BroadcastReceiver的程序;
通常广播发送方都是通过隐式意图,这样才能发送给多人;
广播发送方分为普通广播和有序广播;
同步广播:发送方发出后,几乎同时到达多个广播接收者处,某个接收者不能接收到广播后进行一番处理后传给下一个接收者,并且无法终止广播继续传播;Context.sendBroadcast(intent);
有序广播:广播接收者需要提前设置优先级,优先级高的先接收到广播,优先级数值为-1000~1000,在AndroidManifest.xml的设置;比如存在3个广播接收者A、B、C,优先级A>B>C,因此A最先收到广播,当A收到广播后,可以向广播中添加一些数据给下一个接收者(intent.putExtra()),或者终止广播(abortBroadcast());Context.sendOrderedBroadcast(intent);
二、广播接收者核心代码
同步广播发送方核心代码: Intent intent = new Intent(); intent.setAction("..."); Context.sendBroadcast(intent); 有序广播发送方核心代码: Intent intent = new Intent(); intent.setAction("..."); Context.sendOrderedBroadcast(intent,null) 接收者核心代码: public class Receiver extends BroadcastReceiver{ public void onReceive(Context context, Intent intent) { //接收内容 } } AndroidManifest.xml <application> <receiver android:name=".Receiver"> <intent-filter android:priority="1000"> <action android:name="ACTION"/> </intent-filter> </receiver> </application>
我们来讲第二种动态方式:
//注册广播IntentFilter filter = new IntentFilter();
filter.addAction(ACTION);
registerReceiver(myReceiver, filter);
//解除注册
unregisterReceiver(myReceiver);
//发送广播
Intent intent = new Intent();
intent.setAction(“…”);
Context.sendBroadcast(intent);
//接收广播
private BroadcastReceiver myReceiver = new BroadcastReceiver(){
@Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Toast.makeText(context, "myReceiver receive", Toast.LENGTH_SHORT).show(); } };
“`
ae75
相关文章推荐
- BroadcastReceiver使用方式
- BroadcastReceiver使用方式
- BroadcastReceiver 使用方式
- BroadcastReceiver使用方式
- android 使用 BroadcastReceiver 总结
- android BroadcastReceiver两种注册方式
- BroadcastReceiver中使用自定义Permission
- BroadcastReceiver使用之一(常驻BroadcastReceiver接收短信)
- Android中广播接收者BroadcastReceiver的理解与基本使用
- Android Broadcast receiver使用入门
- BroadcastReceiver—使用(II)
- Android学习指南之二十一:Broadcast Receiver 的使用
- 【Android】BroadcastReceiver简介和用法实例,两种注册方式 (二)
- Android开发学习笔记(3):BroadcastReceiver简介和注册方式
- Service两种不同的调用方式以及BroadcastReceiver两种不同的注册方式
- Android中广播BroadCastReceiver使用
- BroadcastReceiver—使用
- Android开发学习笔记:BroadcastReceiver简介和注册方式
- Android的短信接收处理----Broadcast和Receiver的使用
- BroadcastReceiver register 广播的动态注册方式