Android App开机自动启动的实现

版权声明:© Jie Zhuang 署名-非商用使用-禁止演绎 (CC BY-NC-ND 2.5) https://blog.csdn.net/jez/article/details/85762212

暮鼓集    行走集

原作于2014年01月28日

在开发Android行业应用过程中,常会要求App在系统开机时可以自动启动。这里,我将实现方法和遇到的一些问题总结于下文。

一. 实现

继承一个BroadcastReceiver用来处理BOOT_COMPLETED广播消息

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction().toString();
        if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
  ...
        }
    }
}

在AndroidManifest.xml中注册

<receiver android:name=".MyReceiver" >
    <intent-filter>
       <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

二. 不能自动启动的原因

  1. AndroidManifest.xml中BOOT_COMPLETED部分不正确,或者缺少必要的uses-permission。

  2. 应用安装到了sd卡内,安装在sd卡内的应用不能收到BOOT_COMPLETED。

  3. 系统开启了Fast Boot模式,这种模式下系统启动不会发送BOOT_COMPLETED。

  4. 应用程序安装后重来没有启动过,这种情况下应用程序接收不到任何广播,包括BOOT_COMPLETED、ACTION_PACKAGE_ADDED、CONNECTIVITY_ACTION等等。

所有,有些应用只有Background Service,而不包括任何Activity,是不能启动的。

Android3.1之后,系统为了加强了安全性控制,应用程序安装后或是(设置)应用管理中被强制关闭后处于Stopped状态,在这种状态下接收不到任何广播,直到被启动过(用户打开或是其他应用调用)才会脱离这种状态。要注意,如果用户在应用管理器中Force Stop,则应用又会回到Stopped状态。

但是应用程序作为系统App,被安装在/system/app/下是会自动启动的,不处于stopped状态。

三. 对应用程序进行测试

可以使用如下命令发送BOOT_COMPLETED。

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

而不用重启测试机或模拟器来测试BOOT_COMPLETED广播,这条命令可以更精确的发送到某个package,如下:

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n package_name/class_name

参考

http://developer.android.com/about/versions/android-3.1.html#launchcontrols http://commonsware.com/blog/2011/07/13/boot-completed-regression-confirmed.html http://www.trinea.cn/android/android-boot_completed-not-work/

猜你喜欢

转载自blog.csdn.net/jez/article/details/85762212
今日推荐