編輯:關於 Android 程式設計
Service 是 Android 四大元件之一,通常在後台執行較耗時的工作。要真正用好它,需要掌握:生命週期、建立方式、AIDL 跨進程通信,以及提高存活率的手段。以下逐一說明。

Service 有兩種啟動方式,行為差異很大:
這種方式啟動的服務與呼叫它的 Activity 沒有交互關係。即使啟動它的 Activity 被銷毀,服務仍會繼續運行。只有調用 stopService()(或 stopSelf()),或者服務所在進程被系統回收,它才會停止。
這種方式啟動的服務可以與 Activity 雙向通信,靠的是 Binder 機制。Activity 拿到 Binder 物件後,透過它調用 Service 對外暴露的方法——注意這不是直接調用 Service 內部實作,而是取得一個代理,再由代理轉發。
因為產生了綁定關係,Service 的生命週期會受 Activity 影響:Activity 銷毀時,綁定的 Service 也會跟著銷毀。記得在 Activity 銷毀前解除綁定,否則會出現記憶體洩漏警告。
不解除綁定的情況下,日誌大致如下:

可以看到 MainActivity 與 MyService 都正常回調了 onDestroy(),但系統仍拋出錯誤:
E/ActivityThread: Activity com.example.servertest.MainActivity has leaked
ServiceConnection com.example.servertest.MainActivity$1@b0ff6638
that was originally bound here
stopService() 無法硬中止進行中的操作。繼承 Service 類別,覆寫需要的方法即可。
public class MyService extends Service {
private static final String TAG = "MyService";
private final MyBinder mBinder = new MyBinder();
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() executed");
Log.d(TAG, "MyService thread id is " + Thread.currentThread().getId());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() executed");
// 與 Activity 同進程,耗時任務必須另開執行緒,避免 ANR
new Thread(() -> {
Log.d(TAG, "Download thread id is " + Thread.currentThread().getId());
// 執行具體的下载任務
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder; // 只有 bindService 時才會被呼叫
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() executed");
// 釋放不再使用的資源
}
/** 對外暴露的 Binder */
class MyBinder extends Binder {
public void startDownload() {
new Thread(() -> {
Log.d(TAG, "startDownload() executed");
// 執行具體的下载任務
}).start();
}
}
}
onBind() 回傳的 IBinder 是與 Service 通訊的唯一通道,而它只在 bindService 時才會被呼叫。
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
Intent intent = new Intent(MainActivity.this, MyService.class);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
其中 serviceConnection 是實作 ServiceConnection 的物件:
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 綁定成功後取得 Binder,即可呼叫 Service 對外的方法
MyService.MyBinder myBinder = (MyService.MyBinder) service;
myBinder.startDownload();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// 服務異常中斷時回調
}
};
上面的例子是本地服務:它依附主進程,不需要 AIDL,操作相對簡單。遠程服務則運行在獨立進程,必須用 AIDL 對外暴露接口。
為什麼需要 AIDL?打個比方:遠程服務對你而言是一台陌生機器,你不知道它能提供什麼。AIDL 就像它的說明書,列出所有可用操作;你(客戶端)照著上面的方法呼叫,就能取得服務,而不必關心機器內部怎麼運作。
把本地服務轉為遠程服務很簡單,在清單檔中加上 android:process=":remote":
<service
android:name=".RemoteService"
android:process=":remote" />
在 Android Studio 中於 java 同層的 aidl 目錄建立檔案(右鍵 → New → AIDL → AIDL File),檔名與套件結構需與 Java 一致。

// IMyAidlInterface.aidl
package com.example.servertest;
interface IMyAidlInterface {
int plus(int a, int b);
String toUpperCase(String str);
}
定義好之後執行一次 Make,Studio 會自動產生對應的 Java 接口(Binder 與 Stub 代理都在裡面),不要手動修改它。

public class RemoteService extends Service {
private final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
@Override
public int plus(int a, int b) throws RemoteException {
return a + b;
}
@Override
public String toUpperCase(String str) throws RemoteException {
return str.toUpperCase();
}
};
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
Stub 本身就是 Binder 的子類,因此這個物件可以直接作為 onBind() 的回傳值,也就是客戶端在 onServiceConnected() 中拿到的那個 IBinder。
Intent intent = new Intent(MainActivity.this, RemoteService.class);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 把 IBinder 轉成 AIDL 接口
IMyAidlInterface api = IMyAidlInterface.Stub.asInterface(service);
try {
int result = api.plus(3, 5);
String upper = api.toUpperCase("hello world");
Log.d("iMyAidlService", "result is " + result);
Log.d("iMyAidlService", "upperStr is " + upper);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) { }
};
要讓另一個 App 也能綁定這個遠程服務,有兩個步驟:
intent-filter,自訂一個 action 供外部比對。
Intent intent = new Intent("com.example.servicetest.MyAIDLService");
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
在 Manifest 中為 Service 的 intent-filter 加上 android:priority="1000"(1000 為最高值,數字越小優先級越低)。這個屬性同樣適用於廣播接收器。

呼叫 startForeground(id, notification) 把 Service 提到前台,並顯示一則持續性通知,能顯著降低被回收機率。
public class ForegroundService extends Service {
@Override
public void onCreate() {
super.onCreate();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notification = new Notification.Builder(this)
.setAutoCancel(true)
.setContentTitle("有通知到來")
.setContentText("describe")
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setOngoing(true)
.build();
} else {
notification = new Notification.Builder(this)
.setContentTitle("有通知到來")
.setContentText("describe")
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.getNotification();
}
startForeground(1, notification);
}
@Override
public void onDestroy() {
stopForeground(true); // 別忘了取消前台狀態
super.onDestroy();
}
}
(近版 Android 對前台服務與通知權限有更嚴格的限制,實作時請對照目前 targetSdk 的規範調整。)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
四種回傳值的語意:
onStartCommand(),但未重投的 Intent 會是 null。onStartCommand() 後若被異常終止,系統不會自動重啟。建立一個廣播接收器,收到指定廣播時檢查服務是否還活著,沒活著就重新啟動。
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.ForegroundService.destroy" />
</intent-filter>
</receiver>
或者在 onDestroy() 中主動發送自定義廣播,由接收器把服務再拉起來:
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy() executed");
stopForeground(true);
// 銷毀時發送廣播,由接收器重新啟動服務
sendBroadcast(new Intent("com.ForegroundService.destroy"));
super.onDestroy();
}
在 Manifest 的 <application> 上添加 android:persistent="true"。系統啟動時,AMS 的 systemReady() 會優先加載所有標記為 persistent 的應用。

但要注意:單獨設定這個屬性無效,必須同時滿足 FLAG_SYSTEM(App 需置於 /system/app 目錄)與 FLAG_PERSISTENT 兩個條件。也就是說,這招基本上只有系統簽名或 ROM 定制應用能用。
Service 的思維要點其實只有一句:它是「元件」不是「執行緒」。想清楚它跑在哪個進程、由誰啟動、什麼時候該被解绑,剩下的 API 都是細節。至於提高存活率的各种技巧,在現代 Android 版本上愈發受限,正規做法仍是前台服務加使用者可感知的通知。
本文示例的完整源碼已放在我的 GitHub 上,註解較為詳細,歡迎參閱。
手寫 Android 餅狀圖:基於 android-charts 改造圓弧繪製與百分比標註
項目裡需要展示份額分佈,於是決定自己畫一個餅圖。直接搬 GitHub 上的 android-charts 又發現它本身帶著一些毛病——最典型的是文字偶爾會錯位,標籤壓到圓
Android 動態切換螢幕方向:程式碼與設定一次說明
有些 App 需要提供「鎖定方向」的切換按鈕,例如影片播放器或需要看寬表的報表頁。Android 透過 ActivityInfo 的常數搭配 setRequestedOr
Android圖片浏覽自動切換Gallery與ImageSwitcher實作
在Android中製作圖片浏覽器時,常需要讓下方縮圖與上方大圖同步切換。Gallery與ImageSwitcher是一組常見搭配,前者負責顯示縮圖列表,後者負責以大圖與切
Android Drawable mutations:為何改一個按鈕透明度會影響另一個?
前言Android 為節省記憶體,可能讓多個控制項共用同一個 Drawable 資源。若只修改其中一個控制項的 alpha,另一個也可能跟著變化。本文說明 Drawabl