編輯:進階開發
以下提供一個開機自啟動的完整範例,示範如何攔截開機廣播並啟動一個計時服務。
<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>
早期 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();
}
}
}
後來 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 即可。
Android 應用程式到底用什麼語言寫?兼談它與 Linux 的距離
Android 應用程式最初由 Google 開發,是一套基於 Linux 平台的開源手機作業系統,內容涵蓋作業系統、使用者介面與應用程式。Android 還包含一個核心
Android 實例剖析筆記(六)
2. UI 優化 Android 的 tools 目錄下提供了許多實用工具,這裡介紹其中一個用於查看當前 UI 結構視圖的工具 hierarchyviewer。打開 t
Android 開發實作:打造帶圖片與勾選框的 ListView
專案裡需要一個 ListView,每個列表項既要顯示圖片,後面還要附上一個勾選框(CheckBox)。下面記錄完整的實作流程。 首先新建一個 MyAdapter 類別,讓
Android開源語言總結:GPL與Apache許可的取捨
Android採用軟體堆層(software stack,也稱軟體疊層)架構,主要分成三部分:底層以Linux核心為基礎,以C語言開發,只提供最基本的功能。以下就從許可證