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

Android 開發:如何實現程式開機自啟動

編輯:關於 Android 程式設計

想要製作一個開機自啟動的應用程式其實並不複雜,甚至可以做出一個沒有界面的純後台啟動程式。實現步驟相當簡單。

一、建立廣播接收器

新建一個 Android 工程,在 MainActivity 所在包下建立 BootBroadcastReceiver.java,用於監聽開機完成的廣播:

public class BootReceiver extends BroadcastReceiver {

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

@Override

public void onReceive(Context context, Intent intent) {

Intent bootStartIntent = new Intent(context, MainActivity.class);

bootStartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(bootStartIntent);

}

}

二、配置 AndroidManifest.xml

首先需要聲明接收開機廣播所需的權限:

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

然後在 application 節點中註冊這個廣播接收器:

<receiver android:name=".BootReceiver">

<intent-filter>

<action android:name="android.intent.action.BOOT_COMPLETED" />

</intent-filter>

</receiver>

三、關鍵注意事項

核心在於兩點:一是必須申請 RECEIVE_BOOT_COMPLETED 權限;二是廣播接收器要在 intent-filter 中正確匹配 android.intent.action.BOOT_COMPLETED 這個 Action。完成以上配置後,應用在設備開機完成時便會自動啟動。

需要提醒的是,自 Android 8.0(API 26)起,系統對後台啟動與隱式廣播有更嚴格的限制,實際開發中可能需要搭配前台服務(Foreground Service)或使用其他合規方案,以適配較新的系統版本。

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