Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

開機自動啟動 Service 並以前台方式運行

編輯:Android 開發教學

需求很常見:App 需要在裝置重開機後自動拉起一個背景服務,並且希望這個服務以前台形式運行,降低被系統回收的機率。實作上由三個部分組成:Service 本身、監聽開機廣播的 BroadcastReceiver,以及 Manifest 中的相應宣告。

一、建立 Service

在 onCreate 中呼叫 startForeground,把服務提升到前台,同時帶上一個通知。通知是前台服務的必要條件,使用者也應該能透過它感知服務存在。

public class SeasyService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        // 建立前台服務所需的通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        Notification notification = builder.build();
        startForeground(999, notification);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 取消前台狀態
        stopForeground(true);
    }
}

二、建立開機廣播接收器

接收 BOOT_COMPLETED 廣播後,啟動目標服務。

public class BootBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if ("android.intent.action.BOOT_COMPLETED".equals(action)) {
            Intent service = new Intent(context, SeasyService.class);
            context.startService(service);
        }
    }
}

三、Manifest 設定

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.androidservice"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="18" android:targetSdkVersion="18" />

    <!-- 接收開機完成廣播的權限 -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity android:name="com.example.service.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- 服務宣告 -->
        <service android:name="com.example.service.SeasyService"
            android:enabled="true"
            android:exported="true"
            android:process=":remote">
            <intent-filter>
                <action android:name="com.example.action.SeasyService" />
            </intent-filter>
        </service>

        <!-- 開機廣播接收器 -->
        <receiver android:name="com.example.service.BootBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>
</manifest>

新版本 Android 必須注意的事

上面這份寫法在 Android 8 以前的環境可以正常運作,但放在目前的目標 SDK 上會遇到幾個硬性限制,實作時務必一併處理:

  • 後台啟動限制(API 26+):App 進入背景後,startService 會直接拋出 IllegalStateException。此情境下應改用 startForegroundService,且必須在 5 秒內呼叫 startForeground,否則會觸發 ANR 或崩潰。
  • 通知 Channel(API 26+):前台服務的通知必須指定 NotificationChannel,否則通知不會顯示,也無法正常提升為前台服務。
  • 通知 PendingIntent:Android 12 起必須明確指定 FLAG_IMMUTABLE 或 FLAG_MUTABLE。
  • 啟動時機限制:基於系統資源考量,部分機型與 Android 版本對「從背景啟動 Activity/服務」有更嚴格的限制,開機廣播也未必即時送達。
  • exported 屬性:Android 12 起,帶有 intent-filter 的元件必須顯式宣告 android:exported。上例中的 service 若沒有對外需求,應設為 false。
  • 真正需要長期常駐時,正確方向是改用 WorkManager 搭配定期任務,或使用具正當理由的前台服務類型(如位置、播放、同步),而不是依賴開機自啟硬撐。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved