我们的app需要监控系统的一些广播,比如电量变化,wifi变化,开机广播等来启动我们的服务,于是在xml中配置的如下:
<receiver android:name="com.ctr.ReminderReceiver" android:enabled="true" >
<intent-filter android:priority="10000">
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
<action android:name="android.intent.action.BATTERY_CHANGED" />
</intent-filter>
</receiver>
<service android:name="com.ctr.MyService"></service>
在IDE调试下完全正常,wifi的开关和重启手机ReminderReceiver都能够收到信号,然后启动我们的服务MyService。
做完以后又收到新的需求,要让我们的app自动运行,而且要在没有被打开过一次的情况下自动运行。想了下,这样是不是个流氓程序做的
事情啊,自动运行?!如果我们的程序没有被打开过一次能否收到这些系统广播呢?
猜测不能解决问题,只有自己手动测试了,在IDE调试下程序会自动被打开。于是先生成apk后,用adb push命令复制到手机的sdcard,然后从
手机手动安装。安装好了后,测试wifi变化,重启手机等过程,发现app没有任何反应。跟我的猜测一致,但是还得找找原因。
于是一番google后得到如下的解释:
"
It can't be done, on newer Android versions at least. Ever since Android 3.1, apps are installed in a stopped state, and require that the user open it at least once before components like your BroadcastReceiver can function. This is for security reasons, to prevent, or at least hamper, malicious program behavior.
"原来在3.1以后,app安装后处于stop状态,不能自启动,只有在激活状态才能监听到BOOT_COMPLETED广播。
Stop状态在 http://developer.android.com/about/versions/android-3.1.html#launchcontrols的解释是:“Applications are in a stopped state when they are first installed but are not yet launched and when they are manually stopped by the user (in Manage Applications).”
所以在一次也没有打开app的情况下是接受不到系统开机广播的。
附参考:
http://bbs.csdn.net/topics/390216017