现在的位置: 首页 > 综合 > 正文

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

2017年12月24日 ⁄ 综合 ⁄ 共 2101字 ⁄ 字号 评论关闭

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

(1)、在AndroidManifest.xml中注册

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.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状态,在这种状态下接收不到任何广播。直到被启动过(用户打开或是其他应用调用)才会脱离这种状态,所以Android3.1之后
(1)、应用程序无法在安装后自己启动
(2)、没有ui的程序必须通过其他应用激活才能启动
,如它的Activity、Service、Content Provider被其他应用调用。
存在一种例外,就是应用程序被adb push you.apk /system/app/下是会自动启动的,不处于stopped状态。

stopped state

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

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

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

【上篇】
【下篇】

抱歉!评论已关闭.