Android 开机自启动 app

Android 开机自启动 app

新建一个广播监听器监听开机启动完毕的广播

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent

class BootCompletedReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        var intent1 = intent
        if (intent1.action == ACTION_BOOT_COMPLETED) {
            intent1 = Intent(context, MainActivity::class.java)
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent1)
        }
    }

    companion object {
        private const val ACTION_BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED"
    }
}

在AndroidManifest.xml静态注册该广播

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <!--申请权限-->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application>
        <!--注册广播-->
        <receiver
            android:name=".BootCompletedReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>
    </application>
</manifest>