Service 是 Android 四大組件之一,代表無 UI 的長期背景執行組件。不像 Activity 有視覺介面,Service 在後台執行耗時操作:音樂播放、檔案下載、網路同步、感測器監聽、即時通訊心跳等。
| 模式 | 啟動方式 | 生命週期 | 通訊方式 | 典型場景 |
|---|---|---|---|---|
| Started Service (啟動型) |
startService() |
onCreate → onStartCommand → onDestroy 獨立於呼叫者,呼叫者結束不影響 |
Intent 傳遞參數 結果用 Broadcast/EventBus |
音樂播放、大檔下載、日誌上傳 |
| Bound Service (綁定型) |
bindService() |
onCreate → onBind → onUnbind → onDestroy 所有客戶端解綁則銷毀 |
IBinder 介面直接呼叫 支援跨進程 (AIDL) |
音樂控制器、資料庫存取、IPC |
public class MediaPlaybackService extends Service {
private static final String TAG = "MediaPlaybackService";
private MediaPlayer mediaPlayer;
private int resumePosition = 0;
// 前台服務通知 ID 與 Channel
private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "media_playback";
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build());
createNotificationChannel();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) return START_NOT_STICKY;
String action = intent.getAction();
String mediaUrl = intent.getStringExtra("media_url");
if (ACTION_PLAY.equals(action)) {
playMedia(mediaUrl);
showNotification("播放中");
} else if (ACTION_PAUSE.equals(action)) {
pauseMedia();
updateNotification("已暫停");
} else if (ACTION_STOP.equals(action)) {
stopMedia();
stopForeground(true); // 移除通知並停止服務
stopSelf(startId);
}
// 返回旗標決定被殺後行為
return START_STICKY; // 系統會嘗試重建並重新呼叫 onStartCommand(null)
}
private void playMedia(String url) {
try {
if (mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(mp -> {
mp.seekTo(resumePosition);
mp.start();
});
} catch (IOException e) {
Log.e(TAG, "Play failed", e);
}
}
private void pauseMedia() {
if (mediaPlayer.isPlaying()) {
resumePosition = mediaPlayer.getCurrentPosition();
mediaPlayer.pause();
}
}
private void stopMedia() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
resumePosition = 0;
}
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "媒體播放", NotificationManager.IMPORTANCE_LOW);
channel.setDescription("媒體播放控制通知");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
private void showNotification(String status) {
Intent pauseIntent = new Intent(this, MediaPlaybackService.class).setAction(ACTION_PAUSE);
Intent stopIntent = new Intent(this, MediaPlaybackService.class).setAction(ACTION_STOP);
PendingIntent pausePending = PendingIntent.getService(this, 0, pauseIntent,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent stopPending = PendingIntent.getService(this, 1, stopIntent,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("音樂播放器")
.setContentText(status)
.setSmallIcon(R.drawable.ic_music_note)
.addAction(R.drawable.ic_pause, "暫停", pausePending)
.addAction(R.drawable.ic_stop, "停止", stopPending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0, 1))
.setOngoing(true)
.build();
startForeground(NOTIFICATION_ID, notification);
}
private void updateNotification(String status) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentText(status)
.setOngoing(false)
.build();
NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
@Nullable @Override public IBinder onBind(Intent intent) { return null; }
// Action 常數
public static final String ACTION_PLAY = "com.example.ACTION_PLAY";
public static final String ACTION_PAUSE = "com.example.ACTION_PAUSE";
public static final String ACTION_STOP = "com.example.ACTION_STOP";
}
public class LocalDatabaseService extends Service {
private final IBinder binder = new LocalBinder();
private AppDatabase db;
public class LocalBinder extends Binder {
LocalDatabaseService getService() { return LocalDatabaseService.this; }
}
@Override
public void onCreate() {
super.onCreate();
db = Room.databaseBuilder(this, AppDatabase::class.java, "local.db").build();
}
@Nullable @Override
public IBinder onBind(Intent intent) {
return binder;
}
public User getUser(long id) { return db.userDao().getUserById(id).blockingFirst(); }
public void insertUser(User user) { db.userDao().insert(user); }
@Override
public void onDestroy() {
db.close();
super.onDestroy();
}
}
// 客戶端使用
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalDatabaseService.LocalBinder binder = (LocalDatabaseService.LocalBinder) service;
dbService = binder.getService();
// 現在可直接呼叫 dbService.getUser(1)
}
@Override
public void onServiceDisconnected(ComponentName name) {
dbService = null;
}
};
bindService(new Intent(this, LocalDatabaseService.class), connection, Context.BIND_AUTO_CREATE);
// IRemoteService.aidl
package com.example.remote;
interface IRemoteService {
void registerCallback(IRemoteCallback callback);
void unregisterCallback(IRemoteCallback callback);
long add(in long a, in long b);
List getData();
}
// IRemoteCallback.aidl
package com.example.remote;
interface IRemoteCallback {
void onDataChanged(String data);
void onError(String message);
}
// 服務端實作
public class RemoteService extends Service {
private final RemoteCallbackList callbacks = new RemoteCallbackList<>();
private final IRemoteService.Stub binder = new IRemoteService.Stub() {
@Override
public void registerCallback(IRemoteCallback callback) throws RemoteException {
callbacks.register(callback);
}
@Override
public void unregisterCallback(IRemoteCallback callback) throws RemoteException {
callbacks.unregister(callback);
}
@Override
public long add(long a, long b) throws RemoteException {
return a + b;
}
@Override
public List getData() throws RemoteException {
return Arrays.asList("A", "B", "C");
}
};
@Nullable @Override public IBinder onBind(Intent intent) { return binder; }
private void notifyClients(String data) {
int n = callbacks.beginBroadcast();
for (int i = 0; i < n; i++) {
try { callbacks.getBroadcastItem(i).onDataChanged(data); }
catch (RemoteException e) { Log.e(TAG, "Callback error", e); }
}
callbacks.finishBroadcast();
}
}
IntentService (API 30 棄用) 和 JobIntentService (AndroidX 封裝) 曾用於背景佇列任務。現代替代:
// WorkManager 替代方案
public class SyncWorker extends CoroutineWorker {
public SyncWorker(@NonNull Context context, @NonNull WorkerParameters params) {
super(context, params);
}
@Override
public suspend fun doWork(): Result {
val repository = getRepository()
try {
repository.syncWithServer()
return Result.success()
} catch (e: Exception) {
return Result.retry()
}
}
}
// 排程
val request = PeriodicWorkRequestBuilder(15, TimeUnit.MINUTES)
.setConstraints(Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build())
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"periodic_sync", ExistingPeriodicWorkPolicy.KEEP, request)
START_STICKY/START_NOT_STICKY/START_REDELIVER_INTENTstartForeground(),否則 5 秒後被殺| 問題 | 原因 | 解決 |
|---|---|---|
| Service 被系統殺死不重啟 | 返回 START_NOT_STICKY、記憶體不足、ANR | 用 START_STICKY、優化記憶體、WorkManager 替代 |
| bindService 失敗 | Intent 隱式、exported=false、權限不符 | 顯式 Intent、檢查 Manifest、signature 級權限 |
| 前台服務通知不顯示 | Channel 未建立、importance 太低、未呼叫 startForeground | onCreate 建立 Channel、onStartCommand 5秒內 startForeground |
| AIDL 通訊失敗 | Stub 未實作、Parcelable 未正確寫入、進程隔離 | 檢查 .aidl 同步、實作 Parcelable、使用 RemoteCallbackList |
Service 是 Android 背景運算核心。現代開發:
掌握生命週期、進程模型、通訊機制、電池優化,是打造穩定背景服務的關鍵。