長時間運行任務(音樂播放、下載、定位)建議放在 Service 並呼叫 startForeground(),獲得最高優先級,幾乎不會被系統殺掉。
startForeground(int id, Notification notification):設為前台,需提供持續性通知(Ongoing)。stopForeground(boolean removeNotification):取消前台狀態。// Service onStartCommand 中
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification noti = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("播放中")
.setContentText("音樂服務運行中")
.setSmallIcon(R.drawable.ic_music)
.setContentIntent(pi)
.setOngoing(true)
.build();
startForeground(97789, noti); // 唯一 ID
Handler、AsyncTask(已棄用)、ExecutorService、Coroutines、RxJava 等非同步機制。理解進程優先級有助於設計穩健的後台服務;善用前台 Service 配合通知,可確保關鍵任務持續運行;嚴守主執行緒非阻塞原則,避免 ANR。