1. 清单文件

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">
    
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    
        <application
            android:allowBackup="true"
            android:dataExtractionRules="@xml/data_extraction_rules"
            android:fullBackupContent="@xml/backup_rules"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.AutoStart"
            tools:targetApi="31">
            <activity
                android:name=".MainActivity"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <receiver
                android:name=".SystemBootBroadcastReceiver"
                android:enabled="true"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.ACTION_SHUTDOWN"/>
                </intent-filter>
            </receiver>
        </application>
    
    </manifest>
    
  2. 代码

    /** 手机系统启动广播接收者,当系统启动时,启动我们的app。注:第一次安装时,需要手动启动一次,否则开机时不会自动启动  */
    class SystemBootBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                Intent.ACTION_BOOT_COMPLETED -> {
                    Log.i("BootComplete", "广播收到系统启动")
                    context.startActivity(Intent(context, MainActivity::class.java).also { it.flags = Intent.FLAG_ACTIVITY_NEW_TASK })
                }
                Intent.ACTION_SHUTDOWN -> {
                    Log.i("BootComplete", "广播收到系统关机")
                }
            }
        }
    
    }
    
05-11 18:46