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

Android 開機自啟動的完整範例

編輯:進階開發

以下提供一個開機自啟動的完整範例,示範如何攔截開機廣播並啟動一個計時服務。

一、AndroidManifest.xml 設定

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<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>

二、舊版寫法(IntentReceiver)

早期 Android 使用的是 IntentReceiver,並覆寫 onReceiveIntent() 方法:

public class OlympicsReceiver extends IntentReceiver {
    /* 要接收的 intent 來源 */
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";

    public void onReceiveIntent(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION)) {
            context.startService(new Intent(context, OlympicService.class), null); // 啟動計時服務
            Toast.makeText(context, "OlympicsReminder service has started!", Toast.LENGTH_LONG).show();
        }
    }
}

三、新版寫法(BroadcastReceiver)

後來 IntentReceiver 已改名為 BroadcastReceiver,onReceiveIntent 也相應改為 onReceive。更新後的程式碼如下:

public class OlympicsReceiver extends BroadcastReceiver {
    /* 要接收的 intent 來源 */
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";

    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION)) {
            context.startService(new Intent(context, OlympicService.class), null); // 啟動計時服務
            Toast.makeText(context, "OlympicsReminder service has started!", Toast.LENGTH_LONG).show();
            // 這裡可以加入開機自動啟動的應用程式程式碼
        }
    }
}

重點整理

無論新版或舊版,開機自啟動的核心邏輯一致:註冊 BOOT_COMPLETED 廣播、加上 RECEIVE_BOOT_COMPLETED 權限,並在接收到廣播時啟動目標服務或應用。若你參考的是較老的教學,記得把 IntentReceiver 與 onReceiveIntent 相應替換為現行 API 即可。

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