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

Android 開機自動啟動實作教學

編輯:進階開發

許多工具型 App 需要在裝置重開機後立即恢復運作,例如鬧鐘、備份服務或監控程式。Android 提供了 BOOT_COMPLETED 廣播作為切入點,本文透過一段完整程式碼說明實作方式。

1. 定義 BroadcastReceiver

建立一個繼承 BroadcastReceiver 的類別,在 onReceive() 中啟動 Activity 或 Service:

public class BootReceiver extends BroadcastReceiver {
    public void onReceive(Context ctx, Intent intent) {
        Log.d("BootReceiver", "system boot completed");

        // 啟動 Activity
        String action = "android.intent.action.MAIN";
        String category = "android.intent.category.LAUNCHER";
        Intent myi = new Intent(ctx, CustomDialog.class);
        myi.setAction(action);
        myi.addCategory(category);
        myi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(myi);

        // 啟動 Service
        Intent s = new Intent(ctx, MyService.class);
        ctx.startService(s);
    }
}

這裡有個細節值得注意:Receiver 本身沒有 Task 堆疊,因此啟動 Activity 時必須加上 FLAG_ACTIVITY_NEW_TASK,否則會直接丟出例外。

2. 申請接收開機廣播的權限

在 AndroidManifest.xml 中宣告權限:

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

3. 註冊 Receiver 與 Intent Filter

同樣在 AndroidManifest.xml 中,把 Receiver 攔截的 action 指定為 BOOT_COMPLETED:

<receiver android:name=".app.BootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <category android:name="android.intent.category.HOME" />
    </intent-filter>
</receiver>

4. 驗證結果

啟動模擬器後重新開機,開機完成時就會看到自訂的對話框跳出,代表流程已成功串接。

實務上的注意事項

第一,開機後系統有大量服務同時啟動,onReceive() 內不宜執行耗時工作,重 logic 應該丟給 Service 處理,且 onReceive() 返回後 Receiver 實例就可能被回收。

第二,使用者可能手動停用應用的自啟動權限,加上部分廠商 ROM 對背景啟動有額外限制,因此建議在程式內提供開關讓使用者自行決定,而不是假設一定會被啟動。

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