和网上大多数方法一样,使用广播手段:
ACTION_PACKAGE_ADDED 一个新应用包已经安装在设备上,数据包括包名(最新安装的包程序不能接收到这个广播)
ACTION_PACKAGE_REPLACED 一个新版本的应用安装到设备,替换之前已经存在的版本
ACTION_PACKAGE_CHANGED 一个已存在的应用程序包已经改变,包括包名
ACTION_PACKAGE_REMOVED 一个已存在的应用程序包已经从设备上移除,包括包名(正在被安装的包程序不能接收到这个广播)
ACTION_PACKAGE_RESTARTED 用户重新开始一个包,包的所有进程将被杀死,所有与其联系的运行时间状态应该被移除,包括包名(重新开始包程序不能接收到这个广播)
ACTION_PACKAGE_DATA_CLEARED 用户已经清除一个包的数据,包括包名(清除包程序不能接收到这个广播)
直接思路:注册广播接收以上需要的action来实现。
但是,在安卓3.1之后,有了以下机制:
Here is what Google describes
What is Stopped StateWhy Android Adds thisStarting 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.
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.
As the above references point out it will prevent broadcast intents delivering to stopped packages. Actually this control mechanism will ensure safety and save energy.
Android 3.1 APIs
1、触发ACTION_PACKAGE_REPLACED 广播(也就是apk覆盖替换安装才接收的到,初次安装的广播ACTION_PACKAGE_ADDED 不会被当前安装包触发,因为该app未运行过)
2、在app项目中使用静态注册广播(因为动态广播是app运行后才可以接受到)
3、app曾经运行过(即不处于stopped状态)
在Android5.1真机上测试:
初次安装的app不会触发广播。
覆盖安装未运行过的app,不会触发广播
安装完运行app后,退出App(点击返回键、并从recent任务中移除,此时在设置-应用中查看,app仍未处于stop状态)。覆盖安装后,app成功自动运行。(可看做实现安装后自启动)
此时退出App,并在设置-应用中把app进行【强制停止】。覆盖安装后,app没有自动运行。(此时在设置-应用中查看,app处于stop状态)
所以,只要在App运行时,直接覆盖安装apk,是可以用广播接收器实现安装完后自启动的。 (至少在android 5.1上 ^,^)
下面简单介绍下代码:
(1)自定义广播接收器:
(2)AndroidManifest.xml中静态注册广播接收器