監聽短信的 Service,靜態註冊退出 Activity 仍工作,但「清理內存/長按 Home 鍵清理」後被殺,失去監聽。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 關鍵:被異常殺死後,系統自動重啟並重傳 Intent
return START_REDELIVER_INTENT;
}
| 常量 | 被殺後行為 | Intent 保留 | 適用場景 |
|---|---|---|---|
| START_STICKY | 重啟 Service,onStartCommand(Intent=null) | 否 | 媒體播放器等狀態型 |
| START_NOT_STICKY | 不重啟 | 否 | 一次性任務 |
| START_REDELIVER_INTENT | 重啟並重傳最後 Intent | 是 | **關鍵監聽/下載/同步** |
| START_STICKY_COMPATIBILITY | 兼容模式,不保證重啟 | 否 | 舊版本兼容 |
// 在 onCreate 或 onStartCommand 中
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("短信監聽服務")
.setContentText("正在運行...")
.setSmallIcon(R.drawable.ic_notification)
.build();
startForeground(ONGOING_NOTIFICATION_ID, notification);
START_REDELIVER_INTENT,極大提升存活率。Android 7.0+ 限制隱式廣播靜態註冊(如 SMS_RECEIVED 除外),建議動態註冊 + 高優先級 Service 保活。
**Service 不死秘籍:前台服務 + START_REDELIVER_INTENT + 合理內存佔用。**