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

Android 開發:開機自動啟動無介面的應用程式

編輯:關於 Android 程式設計

在 Android 系統中,有介面的 app 一定有 Activity;而沒有介面的 app,通常就是一個 Service。Service 的啟動方式和 Activity 一樣,都是透過 Intent 物件。本文說明如何實作一個開機後在後台自動啟動的 app。

1. 註冊開機啟動權限

首先在 AndroidManifest 中註冊開機完成廣播所需的權限:


2. 註冊廣播接收者

接著註冊廣播訊息接收者:


    
        
    

3. 撰寫廣播接收者

BootReceiver 在收到開機廣播後,啟動目標 Service:

public class BootReceiver extends BroadcastReceiver {
    private String LOG = "BootReceiver";

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Log.i(LOG, "onReceive");
        Intent mBootIntent = new Intent(arg0, MyService.class);
        arg0.startService(mBootIntent);
    }
}

4. 撰寫目標 Service

public class APTService extends Service {
    private String LOG = "APTService";

    public void onCreate() {
        super.onCreate();
        Log.i(LOG, "Oncreate");
        Toast.makeText(getApplicationContext(), LOG + " onCreate start!", Toast.LENGTH_LONG).show();
        run(context);
        Toast.makeText(getApplicationContext(), LOG + " onCreate end!", Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(LOG, "onBind");
        Toast.makeText(getApplicationContext(), LOG, Toast.LENGTH_LONG).show();
        return null;
    }
}

這樣實作之後,每次開機時就能收到 Toast 訊息,代表後台服務已成功啟動。透過「RECEIVE_BOOT_COMPLETED 權限 + BootReceiver 廣播接收者 + Service」三者搭配,就能實現開機自啟動無介面應用的目標。

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