尊重原创作者,转载请注明出处:
http://blog.csdn.net/gemmem/article/details/8859131
谈到如何实现程序的开机自启动,我想大多数朋友都会认为小菜一碟,不就是注册一个BOOT_COMPLETED消息嘛!
在AndroidManifest.xml里面加入一个receiver,就像这样:
当然还需要再加一个权限:
首先看看google的官方文档:
Starting from Android 3.1, the system's package manager keeps track of applications that are in a stopped state and provides a means of controlling their launch from background processes and other applications.
Note that an application's stopped state is not the same as an Activity's stopped state. The system manages those two stopped states separately.
The platform defines two new intent flags that let a sender specify whether the Intent should be allowed to activate components in stopped application.
FLAG_INCLUDE_STOPPED_PACKAGES
— Include intent filters of stopped applications in the list of potential targets to resolve against.FLAG_EXCLUDE_STOPPED_PACKAGES
— Exclude intent filters of stopped applications from the list of potential targets.When neither or both of these flags is defined in an intent, the default behavior is to include filters of stopped applications in the list of potential targets.
Note that the system adds FLAG_EXCLUDE_STOPPED_PACKAGES
to all broadcast intents. It does this to prevent broadcasts from background services from inadvertently or unnecessarily launching components of stoppped applications. A background service or application can override this behavior by adding the FLAG_INCLUDE_STOPPED_PACKAGES
flag to broadcast intents that should be allowed to activate stopped applications.
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).
上面的文档主要讲了以下几点:
1、android 3.1中有一类package 叫做stopped package, 它们就是那种安装了但是从来没有启动过的apk,或者被用户在程序管理里面force stop了的apk
2、intent中新加了一组flag(FLAG_INCLUDE_STOPPED_PACKAGES和FLAG_EXCLUDE_STOPPED_PACKAGES),带有FLAG_EXCLUDE_STOPPED_PACKAGES的 intent对stopped package是不起作用的。
3、系统对所有的广播intent都加了flag:FLAG_EXCLUDE_STOPPED_PACKAGES,当然boot complete广播也不例外。
看完这3点,大家应该知道为什么我在前面说:注册静态receiver无法保证app开机自动启。
原因很简单,如果我的apk安装到手机后,一直都没有被用户启动过(或者被force stop过),那么它就是一个stopped package,boot_complete广播是无法将其拉起的。
这里需要注意一点: /system/app下面的apk都是非 stopped package。所以如果你的手机root了,那就另当别论了,你可以把apk push到system/app,但是这个安装方式不是正常安装方式了。
所以朋友们如果碰到apk无法开机自启动的问题,请不必苦恼,先看看你的android 版本吧。
android为什么要加入这一机制呢?
很明显是出于安全考虑,因为开机自启动是病毒程序的惯用方式,这个机制可以在一定程度上防止病毒程序的开机自启动。