要讓 App 在裝置開機完成後自動啟動,Android 的機制其實相當直觀,只要三件事:定義廣播類、在 Manifest 註冊、加上權限。
步驟一:建立 BootReceiver
新增一個類別繼承 BroadcastReceiver,覆寫 onReceive(),攔截 BOOT_COMPLETED 這個系統廣播:
- package cn.etzmico;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.util.Log;
- public class BootReceiver extends BroadcastReceiver {
- public void onReceive(Context context, Intent intent) {
- if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
- Log.d("BootReceiver", "system boot completed");
- // context, AutoRun.class
- Intent newIntent = new Intent(context, AutoRun.class);
- /* MyActivity action defined in AndroidManifest.xml */
- newIntent.setAction("android.intent.action.MAIN");
- /* MyActivity category defined in AndroidManifest.xml */
- newIntent.addCategory("android.intent.category.LAUNCHER");
- /*
- * If activity is not launched in Activity environment, this flag is
- * mandatory to set
- */
- newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- /* if you want to start a service, follow below method */
- context.startActivity(newIntent);
- }
- }
- }
AutoRun.class 就是你想拉起的 Activity。FLAG_ACTIVITY_NEW_TASK 這行不可省略,因為廣播接收器不在 Activity 環境中,沒有 Task 棧可用。若你想啟動的是 Service,改呼叫 context.startService() 即可。
步驟二:在 Manifest 註冊
- <receiver android:name=".BootReceiver" android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.BOOT_COMPLETED" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </receiver>
步驟三:加上權限
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
三處都完成才算真正生效,特別是 Manifest 的註冊最常被遺漏。
兩個實務提醒
從 Android 3.1 起,未被使用者手動開啟過的 App 會進入 stopped 狀態而收不到 BOOT_COMPLETED;Android 8.0 之後對背景啟動的限制也更嚴格,若目標 SDK 較新,建議改用 WorkManager 或前景服務來承接啟動後的工作。另外,部分中國廠商 ROM 會自行攔截開機自啟,需在設定中另行授予權限。