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

Android 開機自啟動實作:BroadcastReceiver 捕捉 BOOT_COMPLETED

編輯:關於 Android 程式設計

有些應用天生需要在設備重啟後立刻恢復工作,比如定時同步內容的後台服務。Android 實現這件事的關鍵,是理解一句總結得極好的話:Don't call me, I'll call you back——不要主動去呼叫系統,而是做好準備,等系統來呼你。

使用場景

開機完成後自動啟動應用,並在屏幕上顯示「Hello. I started!」。

背景知識

Android 啟動完成時會發出一個有序廣播,action 為 android.intent.action.BOOT_COMPLETED。只要在應用中「捕捉」到這個消息,再啟動自己即可。實現手段就是一個 BroadcastReceiver——我們唯一能做的,是把接收器準備好,剩下的交給系統。

一、Activity:SayHello.java

代碼很簡單,啟動時建立一個 TextView 顯示文字:

package com.ghstudio.BootStartDemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SayHello extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        tv.setText("Hello. I started!");
        setContentView(tv);
    }
}

二、接收廣播:BootBroadcastReceiver.java

該類派生自 BroadcastReceiver,在 onReceive 中檢查 action 是否為 BOOT_COMPLETED,符合則啟動目標 Activity。注意這裡必須加上 FLAG_ACTIVITY_NEW_TASK,因為此時上下文並非 Activity:

package com.ghstudio.BootStartDemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BootBroadcastReceiver extends BroadcastReceiver {
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION)) {
            Intent sayHelloIntent = new Intent(context, SayHello.class);
            sayHelloIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(sayHelloIntent);
        }
    }
}

三、配置:AndroidManifest.xml

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SayHello" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".BootBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>

    <uses-sdk android:minSdkVersion="3" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
</manifest>

receiver 節點向系統註冊了接收器,子節點 intent-filter 聲明感興趣的 action。千萬別漏掉 android.permission.RECEIVE_BOOT_COMPLETED 這項權限,缺了它 receiver 永遠收不到回呼。

四、幾個實務上的注意事項

第一,開機廣播有時間限制。onReceive 裡禁止做耗时操作,也不能直接啟動 Service 就丟著不管;正規做法是在 onReceive 中呼叫 context.startService() 或調度 WorkManager / JobScheduler 任務,把實際工作交給後台組件。第二,從 Android 8.0 起後台啟動限制收緊,直接 startService 可能拋 IllegalStateException,需改用 startForegroundService 並在 5 秒內發出通知。第三,部分國產 ROM 與 Android 10 以後的系統對「開機自啟」有額外限制,使用者手動授予的自啟權限往往不可省,因此最好在引導頁說明並跳轉到系統設置。

最後,從用戶角度出發:如果不是必要功能,不建議默認開機自啟。它會拖慢開機速度並持續消耗電量,容易招致負評。把開關交給使用者在設置中自行決定,是更穩妥的產品選擇。

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