Android APP开机自启动基本方法

前言

应用自启动主要是通过接收系统广播BOOT_COMPLETED来实现的,在receiver中执行APP启动的方法。

实现

主要分为两个部分:

  1. AndroidManifest.xml配置,包括权限配置和广播注册。
  2. 广播中添加应用启动的代码。

1. 权限添加

AndroidManifest.xml文件中添加BOOT监听权限:

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

2. 安装方式配置

manifest根目录下设置为安装方式:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:installLocation="internalOnly">

设置为将应用安装到内部存储中,安装在SD卡中可能会导致自启动失败。

3. 广播注册

AndroidManifest.xml文件中注册广播:

        <receiver
            android:name=".receiver.BootReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

4. receiver中添加应用启动逻辑

示例代码如下:

class BootReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent == null) return
        if (TextUtils.equals(intent.action, "android.intent.action.BOOT_COMPLETED")) {
            val newIntent = Intent(context, MainActivity::class.java)
            ContextCompat.startActivity(context, newIntent, null)
        }
    }
}

设置一下应用启动逻辑。

5. 问题说明

在执行如上步骤之后,在模拟器运行已经可以启动后应用重启。
但是在手机上测试可以会无法启动,原因是手机上可能安装有手机管家之类的软件。需要在其中将当前应用的自启动选项打开才能生效。

总结

Android开机自启动示例

猜你喜欢

转载自blog.csdn.net/cat_is_so_cute/article/details/124292014
今日推荐