萬盛學電腦網

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

Android Service 完整開發指南:類型、生命週期、通訊與最佳實踐

Service 核心定位

Service 是 Android 四大組件之一,代表無 UI 的長期背景執行組件。不像 Activity 有視覺介面,Service 在後台執行耗時操作:音樂播放、檔案下載、網路同步、感測器監聽、即時通訊心跳等。

兩種基本運行模式

模式啟動方式生命週期通訊方式典型場景
Started Service
(啟動型)
startService() onCreate → onStartCommand → onDestroy
獨立於呼叫者,呼叫者結束不影響
Intent 傳遞參數
結果用 Broadcast/EventBus
音樂播放、大檔下載、日誌上傳
Bound Service
(綁定型)
bindService() onCreate → onBind → onUnbind → onDestroy
所有客戶端解綁則銷毀
IBinder 介面直接呼叫
支援跨進程 (AIDL)
音樂控制器、資料庫存取、IPC

Started Service 完整實作


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";
}

Bound Service 完整實作 (含跨進程 AIDL)

本地綁定 (同進程)


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);

跨進程 AIDL (Android Interface Definition Language)


// 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 / JobIntentService (已棄用) 現代替代:WorkManager

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)

前台服務類型 (Android 14+ 細分)



    


Service 生命週期管理最佳實踐

  1. onCreate:一次性初始化 (MediaPlayer、資料庫連線、執行緒池)
  2. onStartCommand:處理啟動意圖,返回 START_STICKY/START_NOT_STICKY/START_REDELIVER_INTENT
  3. onBind/onUnbind:返回 IBinder,管理客戶端連線
  4. onDestroy:釋放所有資源、關閉連線、停止執行緒
  5. 前台服務:Android 8+ 長期運行必須 startForeground(),否則 5 秒後被殺
  6. 避免記憶體洩漏:Context 使用 Application Context、靜態變數持有 WeakReference、取消所有回調

常見問題排查

問題原因解決
Service 被系統殺死不重啟返回 START_NOT_STICKY、記憶體不足、ANR用 START_STICKY、優化記憶體、WorkManager 替代
bindService 失敗Intent 隱式、exported=false、權限不符顯式 Intent、檢查 Manifest、signature 級權限
前台服務通知不顯示Channel 未建立、importance 太低、未呼叫 startForegroundonCreate 建立 Channel、onStartCommand 5秒內 startForeground
AIDL 通訊失敗Stub 未實作、Parcelable 未正確寫入、進程隔離檢查 .aidl 同步、實作 Parcelable、使用 RemoteCallbackList

總結

Service 是 Android 背景運算核心。現代開發:

  • 長期前台任務 (音樂、導航、下載) → Foreground Service + Notification
  • 客戶端-伺服器介面 (IPC) → Bound Service + AIDL/Binder
  • 延遲/週期/條件觸發任務 → WorkManager (取代 IntentService/JobScheduler/AlarmManager)
  • 應用內背景邏輯 → ViewModel + Coroutine/Flow (不需 Service)

掌握生命週期、進程模型、通訊機制、電池優化,是打造穩定背景服務的關鍵。

copyright © 萬盛學電腦網 all rights reserved