萬盛學電腦網

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

Android Service 後台服務深度解析:生命週期、啟動模式、綁定通信、前台服務與進程保活

Service 是 Android 四大組件中唯一無 UI 的後台執行單元。本文系統講解 Service 概念、生命週期、兩種啟動模式、綁定通信、前台服務、進程保活策略,並提供完整代碼範例與避坑指南。

一、核心概念

  • Service 運行在主進程主線程,**不自動開啟新線程**,耗時操作必須手動創建線程/線程池。
  • 不直接與用戶交互,通過 Notification、Broadcast、EventBus、Interface (AIDL/Binder) 向 UI 傳遞數據。
  • 系統內存緊張時可能殺死 Service,需配合 START_STICKY、Foreground Service、WorkManager 提高存活率。

二、生命週期對比

啟動方式生命週期回調順序銷毀條件
startServiceonCreate → onStartCommand → (多次 onStartCommand) → onDestroy調用 stopService / stopSelf / 系統回收
bindServiceonCreate → onBind → (多次 onRebind) → onUnbind → onDestroy所有 Client unbindService / 系統回收

混合啟動: 先 start 再 bind,Service 不會因 unbind 而銷毀,需顯式 stopService。

三、代碼實戰:雙模式 Service

1. Service 實現

public class MyService extends Service {
    public static final String ACTION = "com.example.MY_SERVICE";
    private final IBinder binder = new LocalBinder();

    public class LocalBinder extends Binder {
        MyService getService() { return MyService.this; }
    }

    @Override public void onCreate() {
        super.onCreate();
        Log.d("MyService", "onCreate");
    }

    @Override public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("MyService", "onStartCommand flags=" + flags + " startId=" + startId);
        // 耗時任務開啟子線程
        new Thread(() -> doLongTask()).start();
        return START_STICKY; // 被殺後嘗試重建
    }

    @Nullable @Override public IBinder onBind(Intent intent) {
        Log.d("MyService", "onBind");
        return binder;
    }

    @Override public boolean onUnbind(Intent intent) {
        Log.d("MyService", "onUnbind");
        return super.onUnbind(intent); // 返回 true 觸發 onRebind
    }

    @Override public void onDestroy() {
        super.onDestroy();
        Log.d("MyService", "onDestroy");
    }

    public void doLongTask() { /* ... */ }
    public String getData() { return "Service Data"; }
}

2. Activity 啟動與綁定

public class MainActivity extends AppCompatActivity {
    private MyService.LocalBinder binder;
    private final ServiceConnection conn = new ServiceConnection() {
        @Override public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MyService.LocalBinder) service;
            Log.d("Main", "Service connected: " + binder.getService().getData());
        }
        @Override public void onServiceDisconnected(ComponentName name) {
            binder = null;
        }
    };

    void startService() {
        startService(new Intent(MyService.ACTION));
    }
    void bindService() {
        bindService(new Intent(MyService.ACTION), conn, BIND_AUTO_CREATE);
    }
    void stopService() {
        stopService(new Intent(MyService.ACTION));
    }
    void unbindService() {
        if (binder != null) unbindService(conn);
    }

    @Override protected void onDestroy() {
        super.onDestroy();
        unbindService();
    }
}

3. Manifest 註冊

<service android:name=".MyService" android:exported="false">
    <intent-filter>
        <action android:name="com.example.MY_SERVICE" />
    </intent-filter>
</service>

四、前台服務 — 保活核心 (API 26+ 強制)

// 在 onStartCommand 中
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("正在播放")
    .setContentText("歌曲名")
    .setSmallIcon(R.drawable.ic_music)
    .setOngoing(true)
    .build();
startForeground(NOTIFICATION_ID, notification);
  • 需聲明 FOREGROUND_SERVICE 權限 (API 28+ 需細分類型如 FOREGROUND_SERVICE_MEDIA_PLAYBACK)。
  • 通知不可滑動刪除,用戶可感知後台運行狀態。

五、進程保活現狀與合規建議

  • 雙進程守護、JobScheduler、AlarmManager、推送拉活 在 Android 8+ 限制極大,易被判定為惡意行為。
  • 合規路徑: 前台服務 + WorkManager 定時任務 + FCM/廠商推送喚醒 + 用戶手動加入白名單 (電池優化例外)。
  • 核心邏輯遷移至 WorkManager (保證執行) + Foreground Service (用戶感知) 組合。

理解 Service 生命週期與啟動模式本質,配合現代 Jetpack 組件,才能編寫穩健、合規的後台業務邏輯。

copyright © 萬盛學電腦網 all rights reserved