Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

讓 Android 的 Service 開機自啟:廣播接收器的實作要點

編輯:初階開發

開機自啟的關鍵,是攔住系統在啟動完成後送出的那一次標準廣播 android.intent.action.BOOT_COMPLETED。這個 Action 整個開機流程只會發送一次,因此不需要擔心重複觸發。

實作三步

第一步:寫一個繼承 BroadcastReceiver 的類別,在 onReceive 中判斷 Action 並啟動目標 Service。

第二步:在 AndroidManifest.xml 中申請權限:

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

第三步:註冊接收器,並在 intent-filter 中宣告要攔的 Action。

Manifest 設定

<receiver android:name=".OlympicsReceiver" 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>

Java 端實作

public class OlympicsReceiver extends BroadcastReceiver {

    static final String ACTION = "android.intent.action.BOOT_COMPLETED";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION)) {
            context.startService(new Intent(context, OlympicsService.class));
            Toast.makeText(context, "OlympicsReminder service has started!",
                    Toast.LENGTH_LONG).show();
            // 若要開機自啟 App,也可在此直接 startActivity
        }
    }
}

版本差異提醒

早期 SDK 中這個角色叫 IntentReceiver,方法名是 onReceiveIntent(Context, Intent);後來更名為 BroadcastReceiver,方法改為 onReceive。查舊教學時要特別注意這點,否則會找不到對應的 API。

另外,從 Android 8.0 起,背景啟動 Service 受到限制,開機自啟通常需要改用 WorkManager 或 foreground service,這份寫法適用於舊版本系統的維護情境。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved