安卓四大组件三之-broadcastreceiver

xiaoxiao2021-02-28  112

什么是广播(broadcastreceiver)? 广播简单的理解为是监听,一种ui组件的监听,比如说对网络,电量,短信等的监听;广播的分类: 广播分为两类,普通广播和有序广播,两者的优缺点正好相反;广播不论有序还是普通他们的注册方式是一样的 分为静态注册和动态注册;静态注册时通过manifest来进行注册的如下: <!-- 静态注册 --> <receiver android:name=".mybroadcastreciver" > <intent-filter> <action android:name="android.intent.action.mybroadcastreciver"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </receiver>

动态注册方式是通过在java代码中注册:

mybroadcastreciver mbr=new mybroadcastreciver(); IntentFilter filter=new IntentFilter(); filter.addAction("android.intent.action.mybroadcastreciver"); registerReceiver(mbr, filter); 这里的mybroadcastreciver是我写的一个继承BroadcastReceiver的一个类,注册时需要该对象和一个 intentfilter; 静态和动态的区别: 静态注册是常驻型,就算我们关闭程序,如果有广播信息传入,receiver依然是可以被系统调用运行的,并不会说是在关闭后就不会运作,只要有符合我们intent-filter赛选的action相同就会被接受到; 动态注册:因为是在java中注册的,当acticity或者service 被注销或者销毁时没有解除我们的receiver,那么系统就会报异常,要求要解除注册,所以通常在 ondestroy中解除,结合前面我们所学习到的acticity声明周期中,如果说系统内存不足等情况,那么系统会跳过ondestroy直接终结程序,那么我们就需要在onpasume中去解除了。不过话说回来,你内存不足直接崩溃,系统直接终结,也就不会报什么异常了。这都是拓展,大家还是多想想好点,学习无止境,万千知识在于悟;言归正传,继续看: 普通广播 普通广播对于接受者来说完全是异步的,不存在先后,并且接受也是完全互相不干扰的,在普通广播中我们是不能终止广播,不能通过abordbroadcast()方法来终止–无效,更无法再当前广播中对其他广播产生任何的影响; 普通广播的发送,通过sendbroadcast(intent);有序广播 有序广播,言外之意就是有序的,这个有序是通过我们的优先级来控制:通过priority来控制,其值为1000-(-1000)越大优先级越高;示例: <!-- 静态注册 --> <receiver android:name=".mybroadcastreciver" > <intent-filter android:priority="1000" > <action android:name="android.intent.action.mybroadcastreciver"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </receiver> 有序广播的发送方式: sendorderedbroadcast(intent,permission ) 有序广播的控制,priority来控制一级一级的广播,那么广播的中存在先后是如何传递这种流程的,在最高级广播中我们通过使用setresultextras()来控制下级的结果。范例 这里只给出核心代码,manifest中如上配置:只是修改不同的priority的参数就可以: priority=1000; @Override public void onReceive(Context arg0, Intent arg1) { System.out.println(arg1.getStringExtra("msg")); Bundle bun=new Bundle(); bun.putString("msg", "我已经修改了你的msg"+arg1.getStringExtra("msg")); setResultExtras(bun); /* abortBroadcast();*/ } }

priority=”999”

System.out.println(arg1.getStringExtra("msg")); Bundle bun=new Bundle(); bun.putString("msg", "我再次经修改了你的msg"+arg1.getStringExtra("msg")); setResultExtras(bun);

最后一个广播: priority=998

System.out.println(arg1.getStringExtra("msg"));
转载请注明原文地址: https://www.6miu.com/read-69958.html

最新回复(0)