03/25
2013

Android应用如何开机自启动、自启动失败原因

本文主要介绍Android应用如何开机自启动、自启动失败的原因、adb命令发送BOOT_COMPLETED
问题:应用程序是否可以在安装后自启动,没有ui的纯service应用如何启动?答案马上揭晓^_*
1、Android应用如何开机自启动
(1)、在AndroidManifest.xml中注册

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.trinea.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".BootBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
    </application>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>

注意不仅要添加android.intent.action.BOOT_COMPLETED对应的action,还需要添加对应的uses-permission

 

(2)、Receiver接收广播进行处理

public class BootBroadcastReceiver extends BroadcastReceiver {

    public static final String TAG = "BootBroadcastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction().toString();
        if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
			// u can start your service here
            Toast.makeText(context, "boot completed action has got", Toast.LENGTH_LONG).show();
            return;
        }
    }
}

 

2、自启动失败的原因
接收不到BOOT_COMPLETED广播可能的原因
(1)、BOOT_COMPLETED对应的action和uses-permission没有一起添加
(2)、应用安装到了sd卡内,安装在sd卡内的应用是收不到BOOT_COMPLETED广播的
(3)、系统开启了Fast Boot模式,这种模式下系统启动并不会发送BOOT_COMPLETED广播
(4)、应用程序安装后重来没有启动过,这种情况下应用程序接收不到任何广播,包括BOOT_COMPLETED、ACTION_PACKAGE_ADDED、CONNECTIVITY_ACTION等等。
Android3.1之后,系统为了加强了安全性控制,应用程序安装后或是(设置)应用管理中被强制关闭后处于stopped状态,在这种状态下接收不到任何广播,除非广播带有FLAG_INCLUDE_STOPPED_PACKAGES标志,而默认所有系统广播都是FLAG_EXCLUDE_STOPPED_PACKAGES的,所以就没法通过系统广播自启动了。所以Android3.1之后
(1)、应用程序无法在安装后自己启动
(2)、没有ui的程序必须通过其他应用激活才能启动,如它的Activity、Service、Content Provider被其他应用调用。
存在一种例外,就是应用程序被adb push you.apk /system/app/下是会自动启动的,不处于stopped状态。no broadcast received stopped state
具体说明见:
http://developer.android.com/about/versions/android-3.1.html#launchcontrols
http://commonsware.com/blog/2011/07/13/boot-completed-regression-confirmed.html

 

3、adb发送BOOT_COMPLETED
我们可以通过

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

命令发送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

 

8 thoughts on “Android应用如何开机自启动、自启动失败原因

    • 只是刚安装无法自启动,启动过一次后就没问题。另外各个系统也有自己的策略,比如小米为了开机速度默认就禁止三方应用获取开机广播

  1. 你好,那个Android3.1之后,系统为了加强了安全性控制,应用程序安装后或是(设置)应用管理中被强制关闭后处于stopped状态 ,这个stopped是在设置中的“强行停止”吗?

Comments are closed.