Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 開機自啟動實作:三個步驟搞定

要讓 App 在裝置開機完成後自動啟動,Android 的機制其實相當直觀,只要三件事:定義廣播類、在 Manifest 註冊、加上權限。

步驟一:建立 BootReceiver

新增一個類別繼承 BroadcastReceiver,覆寫 onReceive(),攔截 BOOT_COMPLETED 這個系統廣播:

  1. package cn.etzmico;
  2. import android.content.BroadcastReceiver;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.util.Log;
  6. public class BootReceiver extends BroadcastReceiver {
  7.     public void onReceive(Context context, Intent intent) {
  8.         if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
  9.             Log.d("BootReceiver", "system boot completed");
  10.             // context, AutoRun.class
  11.             Intent newIntent = new Intent(context, AutoRun.class);
  12.             /* MyActivity action defined in AndroidManifest.xml */
  13.             newIntent.setAction("android.intent.action.MAIN");
  14.             /* MyActivity category defined in AndroidManifest.xml */
  15.             newIntent.addCategory("android.intent.category.LAUNCHER");
  16.             /*
  17.              * If activity is not launched in Activity environment, this flag is
  18.              * mandatory to set
  19.             */
  20.             newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  21.             /* if you want to start a service, follow below method */
  22.             context.startActivity(newIntent);
  23.         }
  24.     }
  25. }

AutoRun.class 就是你想拉起的 Activity。FLAG_ACTIVITY_NEW_TASK 這行不可省略,因為廣播接收器不在 Activity 環境中,沒有 Task 棧可用。若你想啟動的是 Service,改呼叫 context.startService() 即可。

步驟二:在 Manifest 註冊

  1. <receiver android:name=".BootReceiver" android:label="@string/app_name">
  2.     <intent-filter>
  3.         <action android:name="android.intent.action.BOOT_COMPLETED" />
  4.         <category android:name="android.intent.category.LAUNCHER" />
  5.     </intent-filter>
  6. </receiver>

步驟三:加上權限

  1. <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 會自行攔截開機自啟,需在設定中另行授予權限。

Copyright © Linux教程網 All Rights Reserved