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

Android Service 完全指南:從基本用法到定時任務實踐

編輯:關於 Android 程式設計

Service 是 Android 四大元件之一,適合執行不需要使用者介面的背景作業。本文從定義、啟動、通訊一路談到生命週期、前台服務,最後以 Alarm 定時任務收尾。

一、定義一個服務

新增 MyService 類別並繼承 Service,必須實作唯一的抽象方法 onBind():

public class MyService extends Service {
    @Override public IBinder onBind(Intent arg0) { return null; }
}

若要處理實際邏輯,可再重寫三個最常用到的方法:

public class MyService extends Service {
    @Override public IBinder onBind(Intent arg0) { return null; }
    @Override public void onCreate() { super.onCreate(); }        // 服務建立時呼叫
    @Override public void onDestroy() { super.onDestroy(); }      // 服務銷毀時呼叫
    @Override public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);      // 每次啟動時呼叫
    }
}

通常希望服務一啟動就立刻執行動作,就把邏輯寫在 onStartCommand();服務銷毀時則在 onDestroy() 回收資源。別忘了,任何服務都必須在 AndroidManifest.xml 中註冊才能生效。

二、啟動與停止服務

啟動與停止主要透過 Intent 搭配 startService() 與 stopService() 完成,這兩個方法都定義在 Context 類別中:

case R.id.start_service:
    startService(new Intent(this, MyService.class));
    break;
case R.id.stop_service:
    stopService(new Intent(this, MyService.class));
    break;

若希望服務自己停下來,只要在服務內任何位置呼叫 stopSelf() 即可。想確認服務是否真的啟動或停止,最直接的方式就是在各方法中加上 Log 輸出。

onCreate 與 onStartCommand 的差別:onCreate 只在服務「第一次建立」時呼叫,而 onStartCommand 則在「每次啟動」時都會呼叫。因此第一次點擊時兩者都會觸發,之後再點就只剩 onStartCommand 會執行。

三、活動與服務通訊

若要在服務中提供下載功能,並讓活動能隨時查看進度,可以建立一個專用的 Binder 物件來管理:

public class MyService extends Service {
    private DownloadBinder mBinder = new DownloadBinder();

    class DownloadBinder extends Binder {
        public void startDownload() { Log.d("MyService", "startdownload executed"); }
        public int getProgress()   { Log.d("MyService", "getProgress executed"); return 0; }
    }

    @Override public IBinder onBind(Intent intent) { return mBinder; }
}

活動端透過 bindService() 綁定服務,並在 ServiceConnection 的 onServiceConnected() 中取得 DownloadBinder 實例,就能直接呼叫服務裡的 public 方法:

private ServiceConnection connection = new ServiceConnection() {
    @Override public void onServiceConnected(ComponentName name, IBinder service) {
        downloadBinder = (MyService.DownloadBinder) service;
        downloadBinder.startDownload();
        downloadBinder.getProgress();
    }
    @Override public void onServiceDisconnected(ComponentName name) { }
};

// 綁定:第三個參數 BIND_AUTO_CREATE 表示綁定後自動建立服務
bindService(new Intent(this, MyService.class), connection, BIND_AUTO_CREATE);
// 解除綁定
unbindService(connection);

值得留意的是,同一個服務在整個應用程式範圍內都是通用的,任何活動綁定後都能取得相同的 Binder 實例。

四、服務的生命週期

一旦呼叫 startService(),服務就會啟動並回呼 onStartCommand;若之前未建立過,onCreate 會先執行。服務啟動後會持續運行,直到 stopService() 或 stopSelf() 被呼叫。雖然每次呼叫 startService 都會觸發一次 onStartCommand,但每個服務實際上只存在一個實例,因此不管啟動多少次,只需停止一次即可。

另一條路是透過 bindService() 取得持久連線,此時會回呼 onBind,只要連線不中斷,服務就會持續運行。特別要注意:若同時呼叫了 startService 與 bindService,必須同時呼叫 stopService 與 unbindService,onDestroy 才會執行。

五、使用前台服務

服務的系統優先級較低,記憶體不足時可能被回收。若希望服務保持運行,可改用「前台服務」,它會在狀態列顯示一個持續的通知。做法是在 onCreate 中建立 Notification,然後呼叫 startForeground():

Notification notification = new Notification(R.drawable.ic_launcher,
        "Notification comes", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "this is title", "this is content", pendingIntent);
startForeground(1, notification);

六、使用 IntentService

服務中的程式碼預設運行在主線程,若直接處理耗時邏輯容易引發 ANR。標準做法是在方法裡另開子線程,並在結束時呼叫 stopSelf()。但這樣容易忘記開線程或忘記停止,因此 Android 特別提供了 IntentService 來解決這兩個痛點——它天生運行在子線程,且任務完成後會自動停止。

public class MyIntentService extends IntentService {
    public MyIntentService() {
        super("MyIntentService");   // 必須呼叫父類的有參構造
    }
    @Override protected void onHandleIntent(Intent arg0) {
        // 已在子線程運行,不必擔心 ANR
        Log.d("MyIntentService", "Thread id is " + Thread.currentThread().getId());
    }
    @Override public void onDestroy() {
        super.onDestroy();
        Log.d("MyIntentService", "onDestroy() executed");
    }
}

別忘了在 AndroidManifest.xml 中註冊服務,執行後即可看到 onHandleIntent 的線程 id 與主線程不同,且 onDestroy 確實會被執行。

七、最佳實踐:後台定時任務

Android 實作定時任務有兩種方式:Java 的 Timer 與 Android 的 Alarm。Timer 不適合長期在後台運行的定時任務,因為手機休眠時 CPU 進入睡眠狀態,可能導致任務無法執行。而 Alarm 具備喚醒 CPU 的能力,更為可靠(注意:喚醒 CPU 與喚醒螢幕是兩回事)。

Alarm 主要透過 AlarmManager 實作:

AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
long triggerAtTime = SystemClock.elapsedRealtime() + 10 * 1000;
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent);

set() 的第一個參數決定工作類型,共有四種:ELAPSED_REALTIME、ELAPSED_REALTIME_WAKEUP、RTC、RTC_WAKEUP。前兩者以開機時間為基準,後兩者以 1970 年 1 月 1 日為基準;帶 WAKEUP 的版本會喚醒 CPU。第三個參數是 PendingIntent,通常搭配 getBroadcast(),讓廣播接收器的 onReceive 得以觸發。

以下建立一個能長期在後台定時執行的服務:

public class LongRunningService extends Service {
    @Override public IBinder onBind(Intent intent) { return null; }
    @Override public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override public void run() {
                Log.d("LongRunningService", "executed at " + new Date().toString());
            }
        }).start();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour = 10 * 1000;
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }
}

public class AlarmReceiver extends BroadcastReceiver {
    @Override public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, LongRunningService.class));
    }
}

這樣就形成一個循環:LongRunningService 啟動後設定一個 10 秒後觸發的鬧鐘,時間到時 AlarmReceiver 再啟動 LongRunningService,如此周而復始。只要在打開程式時啟動一次 LongRunningService,它就能持續運行。

最後提醒:從 Android 4.4 起,Alarm 的觸發時間會變得「不精準」,這是系統為了省電所做的優化——它會把觸發時間相近的任務合併執行,以減少 CPU 被喚醒的次數。若你要求精準執行,可改用 setExact() 取代 set()。

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