You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测Android系统杀死后台Service?VIVO Y15s后台服务异常终止求助

针对VIVO Y15s(Funtouch OS 12 Global)后台Service被自动杀死的解决方案

问题背景

  • 设备:VIVO Y15s(搭载Funtouch OS 12 Global)
  • 异常现象:应用后台Service/任务运行5-6分钟后被系统自动杀死,Android Studio日志无任何异常或报错信息
  • 已尝试无效方案:重写onDestroy()和onTaskRemoved()方法,通过AlarmManager实现服务重启机制,代码如下:
val restartServiceIntent = Intent(applicationContext, AppService::class.java).also {
    it.setPackage(packageName)
    it.action = Actions.START.name
}
val restartServicePendingIntent: PendingIntent =
    PendingIntent.getService(this, 1, restartServiceIntent,
        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE);
applicationContext.getSystemService(Context.ALARM_SERVICE)
val alarmService: AlarmManager =
    applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmService.set(
    AlarmManager.ELAPSED_REALTIME,
    SystemClock.elapsedRealtime() + 1000,
    restartServicePendingIntent
)

针对性解决方案

1. 手动配置VIVO系统后台白名单

VIVO的Funtouch OS有严格的后台管控策略,必须将应用加入白名单才能避免被查杀:

  • 路径1:设置 > 电池 > 后台高耗电,找到你的应用并开启「允许后台高耗电」
  • 路径2:设置 > 应用与权限 > 权限管理 > 特殊权限 > 忽略电池优化,将应用设置为「允许」
  • 路径3:长按应用图标 → 应用信息 > 后台管理,选择「允许后台运行」(不要选智能后台或禁止后台)

2. 优化Service的运行模式

  • 改用前台Service:Android 8.0+对后台Service限制极严,前台Service会显示常驻通知,系统优先级更高。在onStartCommand()中调用startForeground(),传入通知ID和合规的Notification(注意适配Android 13+的POST_NOTIFICATIONS权限)
  • 调整onStartCommand()返回值:设置为START_STICKY或START_REDELIVER_INTENT,让系统在资源回收后自动尝试重启Service

3. 修复AlarmManager重启逻辑

现有代码存在两个关键问题,修改后才能生效:

  • 替换AlarmManager.set()为setExactAndAllowWhileIdle():Android 6.0+的Doze模式会阻止普通定时任务,该API能确保任务在设备休眠时也触发
  • 动态生成PendingIntent请求码:固定请求码会导致复用旧的PendingIntent,改用System.currentTimeMillis().toInt()作为请求码避免冲突

修改后的代码示例:

val restartServiceIntent = Intent(applicationContext, AppService::class.java).apply {
    setPackage(packageName)
    action = Actions.START.name
}
val restartServicePendingIntent = PendingIntent.getService(
    this,
    System.currentTimeMillis().toInt(), // 动态请求码避免复用
    restartServiceIntent,
    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

val alarmService = applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    alarmService.setExactAndAllowWhileIdle(
        AlarmManager.ELAPSED_REALTIME_WAKEUP, // 唤醒设备执行任务
        SystemClock.elapsedRealtime() + 1000,
        restartServicePendingIntent
    )
} else {
    alarmService.setExact(
        AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() + 1000,
        restartServicePendingIntent
    )
}

4. 规避系统智能清理机制

  • 关闭应用自动清理:打开i管家 > 空间清理 > 设置,关闭针对该应用的自动清理选项
  • 拆分耗时任务:不要在Service中直接执行耗时操作,改用WorkManager或IntentService处理,避免因ANR触发系统查杀

内容的提问来源于stack exchange,提问作者Ahmed Rehman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:05:12