Service 是 Android 四大組件中無 UI 的後台執行單元。掌握其兩種啟動模式及混合場景下的生命周期回調順序,是構建穩健後台服務的關鍵。
| 維度 | startService (啟動模式) | bindService (綁定模式) |
|---|---|---|
| 啟動方式 | Context.startService(Intent) | Context.bindService(Intent, conn, flags) |
| 生命周期關鍵回調 | onCreate → onStartCommand (多次) | onCreate → onBind (返回 IBinder) |
| 停止方式 | stopService / stopSelf / stopSelfResult | unbindService (所有客戶端解綁) |
| 服務存活條件 | 調用 stop 前一直運行 | 至少一個客戶端綁定 |
| 通信方式 | Intent + Broadcast / ResultReceiver | IBinder 接口 (AIDL/Messenger/本地) |
| 適用場景 | 長時間後台任務 (下載、播放、同步) | 客戶端-服務端雙向通信、IPC |
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
// 1. 初始化:僅調用一次
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 2. 每次 startService 觸發
// 返回值決定殺死後重啟策略:
return START_STICKY; // 重建服務,Intent 為 null
// return START_NOT_STICKY; // 不重建
// return START_REDELIVER_INTENT; // 重建並重遞最後 Intent
}
@Override
public IBinder onBind(Intent intent) {
return null; // 不支持綁定
}
@Override
public void onDestroy() {
super.onDestroy();
// 3. 停止時清理資源
}
}
關鍵點:
startService → 多次 onStartCommand,但 onCreate 僅一次stopService 或單次 stopSelf() 停止START_STICKY 重建// 客戶端
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 獲取代理,開始調用
MyBinder binder = (MyBinder) service;
myService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// 異常斷開 (進程崩潰),非正常 unbind
myService = null;
}
};
bindService(new Intent(this, MyService.class), conn, BIND_AUTO_CREATE);
// 服務端
public class MyService extends Service {
private final IBinder binder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
return binder; // 必須返回非 null
}
public class MyBinder extends Binder {
MyService getService() { return MyService.this; }
}
// 無 onStartCommand 調用
// 所有客戶端 unbind 後 → onDestroy
}
startService 和 bindServiceonCreate → onStartCommand → onBindstopService 且 所有客戶端 unbindServicestopService 不會停止服務 (綁定計數 > 0)| 場景 | 調用 | 回調 | 條件 |
|---|---|---|---|
| 啟動模式停止 | stopService / stopSelf | onDestroy | 無綁定 或 啟動模式 |
| 綁定模式停止 | unbindService (最後一個) | onUnbind → onDestroy | 無啟動 或 綁定模式 |
| 混合模式停止 | stopService + 所有 unbind | onUnbind → onDestroy | 兩者計數歸零 |
| 系統殺死 | Low Memory Killer | onDestroy (盡力調用) | 內存不足,優先級低 |
@Override
public boolean onUnbind(Intent intent) {
// 返回 true:允許 onRebind,服務不銷毀
// 返回 false (默認):不調用 onRebind,最後一個 unbind 後 onDestroy
return true; // 支持斷開重連不重建服務
}
@Override
public void onRebind(Intent intent) {
// 客戶端再次 bind 時調用 (需 onUnbind 返回 true)
}
// 在 onCreate/onStartCommand 中盡快調用
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("下載中")
.setContentText("50%")
.setSmallIcon(R.drawable.ic_download)
.build();
startForeground(NOTIFICATION_ID, notification);
// 停止前台
stopForeground(true); // true=移除通知
android:exported 顯式聲明 (Android 12+)深入理解 Service 生命周期與雙模式交互,能避免 90% 的後台服務相關崩潰與洩漏,構建穩健的 Android 後台能力。