萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Service 生命周期完整解析:startService、bindService、混合模式與停止機制

Android Service 生命周期全景指南

Service 是 Android 四大組件中無 UI 的後台執行單元。掌握其兩種啟動模式及混合場景下的生命周期回調順序,是構建穩健後台服務的關鍵。

兩種啟動模式對比

維度startService (啟動模式)bindService (綁定模式)
啟動方式Context.startService(Intent)Context.bindService(Intent, conn, flags)
生命周期關鍵回調onCreate → onStartCommand (多次)onCreate → onBind (返回 IBinder)
停止方式stopService / stopSelf / stopSelfResultunbindService (所有客戶端解綁)
服務存活條件調用 stop 前一直運行至少一個客戶端綁定
通信方式Intent + Broadcast / ResultReceiverIBinder 接口 (AIDL/Messenger/本地)
適用場景長時間後台任務 (下載、播放、同步)客戶端-服務端雙向通信、IPC

模式一:純 startService 生命周期

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 重建

模式二:純 bindService 生命周期

// 客戶端
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
}

模式三:混合模式 (start + bind)

  • 同時調用 startService 和 bindService
  • 生命周期:onCreate → onStartCommand → onBind
  • 停止條件:需同時 stopService 且 所有客戶端 unbindService
  • 僅 stopService 不會停止服務 (綁定計數 > 0)
  • 適用:後台長任務 + 需要客戶端實時控制/查詢進度

模式四:停止服務機制詳解

場景調用回調條件
啟動模式停止stopService / stopSelfonDestroy無綁定 或 啟動模式
綁定模式停止unbindService (最後一個)onUnbind → onDestroy無啟動 或 綁定模式
混合模式停止stopService + 所有 unbindonUnbind → onDestroy兩者計數歸零
系統殺死Low Memory KilleronDestroy (盡力調用)內存不足,優先級低

onUnbind 返回值控制重綁行為

@Override
public boolean onUnbind(Intent intent) {
    // 返回 true:允許 onRebind,服務不銷毀
    // 返回 false (默認):不調用 onRebind,最後一個 unbind 後 onDestroy
    return true; // 支持斷開重連不重建服務
}

@Override
public void onRebind(Intent intent) {
    // 客戶端再次 bind 時調用 (需 onUnbind 返回 true)
}

前台服務 (Android 8.0+ 必須)

// 在 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=移除通知

常見坑點與最佳實踐

  • ❌ 在 onStartCommand 耗時操作 → ANR (主線程) → 用子線程/IntentService/WorkManager
  • ❌ 忘記 stopSelf 導致服務洩漏 → 電量/內存洩漏
  • ❌ bindService 未在 onDestroy/unbind 時解綁 → Activity 泄漏
  • ✅ 明確區分「任務型」用 startService、「交互型」用 bindService
  • ✅ Android 8+ 後台執行限制:用 WorkManager / JobScheduler 替代長運行 Service
  • ✅ 前台服務配合 Notification Channel,用戶可感知
  • ✅ 導出服務需 android:exported 顯式聲明 (Android 12+)

深入理解 Service 生命周期與雙模式交互,能避免 90% 的後台服務相關崩潰與洩漏,構建穩健的 Android 後台能力。

copyright © 萬盛學電腦網 all rights reserved