Service 是 Android 四大組件中唯一無 UI 的後台執行單元。本文系統講解 Service 概念、生命週期、兩種啟動模式、綁定通信、前台服務、進程保活策略,並提供完整代碼範例與避坑指南。
START_STICKY、Foreground Service、WorkManager 提高存活率。| 啟動方式 | 生命週期回調順序 | 銷毀條件 |
|---|---|---|
| startService | onCreate → onStartCommand → (多次 onStartCommand) → onDestroy | 調用 stopService / stopSelf / 系統回收 |
| bindService | onCreate → onBind → (多次 onRebind) → onUnbind → onDestroy | 所有 Client unbindService / 系統回收 |
混合啟動: 先 start 再 bind,Service 不會因 unbind 而銷毀,需顯式 stopService。
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"; }
}
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();
}
}
<service android:name=".MyService" android:exported="false">
<intent-filter>
<action android:name="com.example.MY_SERVICE" />
</intent-filter>
</service>
// 在 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)。WorkManager (保證執行) + Foreground Service (用戶感知) 組合。理解 Service 生命週期與啟動模式本質,配合現代 Jetpack 組件,才能編寫穩健、合規的後台業務邏輯。