`
charlotte
  • 浏览: 121410 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

静态注册的receiver也是可以关闭滴

阅读更多

最近做了个demo,用到广播,目的是监听蓝牙连接是否断开。断开时,弹出对话框告知已断开。


开始的时候当连接断开时发出警告用的是AlertDialog,这个东西必须是由activity创建,而我有多个activity。于是就悲催的在N个Activity里注册and销毁receiver(这是有多彪啊)。。。。


而当你真正收到连接断开的时候其实早800年前就被断开了,这个时间差内,再读写之类的会有异常,这时就要有自定义广播~~于是我凌乱了。


凌乱之后,又自定义过滤器,静态注册接收器。这时AlertDialog的问题出现了。我又不淡定了,又是一阵凌乱后,发现再写个activity设置成dialog,再设置透明神马的不就OK(之前是有多蠢啊)。当收到广播的时候转到alertactivity,为了避免多次弹出对话框,在AndroidManifest.xml里设置了单例。


本以为这就完了,但是发现这个静态注册的广播在进程都kill了还在那给我提示,疯了。。。

各种去 groups.google上搜贴无果后各种看api,发现AndroidManifest中receiver里的enable属性,属性描述如下:


Whether or not the broadcast receiver can be instantiated by the system — "true" if it can be, and "false" if not. The default value is "true".The <application> element has its own enabled attribute that applies to all application components, including broadcast receivers. The <application> and <receiver> attributes must both be "true" for the broadcast receiver to be enabled. If either is "false", it is disabled; it cannot be instantiated.


水平太烂凑活瞎理解吧。。想着干脆得到PackageManager后直接把application的enable制成false,结果是收不到广播了,程序也再启动不起来了(这个应该可以解决,下面再说)。。,无奈~


继续看,看到setComponentEnabledSetting,描述如下:


Set the enabled setting for a package component (activity, receiver, service, provider). This setting will override any enabled state which may have been set by the component in its manifest.

觉得可行就,先得到receiver这个组件后把他的enable制成false,广播关闭了。but下次程序启动的时候广播木有了,真的木有了啊~~~百思不得其解

最终把AndroidManifest里receiver的enable属性显示声明成true,这次可以了。

觉得之前如果把在AndroidManifest里把application的enable属性也显示声明成true,也应该可以,不过没有试。



 

分享到:
评论
2 楼 jamkier 2014-07-19  
getPackageManager().setComponentEnabledSetting(new ComponentName(this, NetworkBroadcast.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); //设置静态全局网络监听广播失效
1 楼 阿狸爱吃potato 2013-02-13  
楼主好~
我也想编个小程序检测蓝牙连接断开 一直找不到合适的方法
楼主能方便把源码发给我参考一下吗?
这是我的邮箱:obliviate_pixie@163.com
谢谢谢谢!!感激不尽!!

相关推荐

Global site tag (gtag.js) - Google Analytics