Android Activity Recognition Service运行15小时后停止接收更新
针对你的Activity Recognition Service运行15-16小时后停止接收更新的问题,结合代码实现,核心问题点和修复建议如下:
1. PendingIntent 广播匹配失败
你的ActivityTransitionReceiver在Manifest中声明了自定义action <action android:name="com.example.driver.ACTIVITY_RESULT" />,但创建PendingIntent时未给Intent设置该action。Google Play Services发送的广播会严格匹配Intent的action、component等属性,不匹配会导致Receiver无法接收事件。
修复代码:
修改getPendingIntent()方法,为Intent添加对应action:
private fun getPendingIntent(): PendingIntent { val intent = Intent(this, ActivityTransitionReceiver::class.java).apply { action = "com.example.driver.ACTIVITY_RESULT" // 与Manifest中声明的action完全一致 } return PendingIntent.getBroadcast(this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE) }
2. 服务重启后更新注册丢失
你仅在onCreate()中注册Activity更新,但系统回收服务后重启时,onCreate()不会再次执行,导致更新注册逻辑缺失。
修复代码:
将更新注册逻辑移至onStartCommand(),确保每次服务启动(包括重启)都能重新注册:
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { // 每次启动服务都重新注册更新,避免重启后丢失监听 requestForUpdates() return START_STICKY }
同时在onDestroy()中取消已注册的更新,避免重复注册导致的资源泄漏:
override fun onDestroy() { AppLogger.log(applicationContext, "ActivityRecognitionService", "Service destroyed.") // 取消已注册的更新任务 client.removeActivityTransitionUpdates(getPendingIntent()) client.removeActivityUpdates(getPendingIntent()) super.onDestroy() }
3. WorkManager 调度逻辑矛盾
你的scheduleActivityRecognitionWorker()方法中,周期性任务设置为30分钟间隔,但日志误写为“每8小时”,容易导致调度逻辑混乱。此外需确保Worker能真正重建Activity识别客户端。
修复代码:
修正日志描述,并在ActivityRecognitionWorker中重启服务触发更新注册:
// ActivityRecognitionWorker的doWork()方法 override fun doWork(): Result { val context = applicationContext val intent = Intent(context, ActivityRecognitionService::class.java) ContextCompat.startForegroundService(context, intent) AppLogger.log(context, "ActivityRecognitionWorker", "Recreated Activity Recognition client.") return Result.success() }
同时修正scheduleActivityRecognitionWorker()中的日志:
AppLogger.log(context, "WorkManagerScheduler", "Repeating worker scheduled every 30 minutes.")
4. 系统权限与优化限制
- 确保已动态申请
ACTIVITY_RECOGNITION权限(Android 13+必须动态申请); - 引导用户关闭应用的电池优化,部分厂商的省电策略会强制停止后台服务(即使是前台服务);
- 若无需修改Intent内容,可将
PendingIntent.FLAG_MUTABLE替换为FLAG_IMMUTABLE,提升安全性(需适配目标SDK版本)。
额外监控建议
- 增加日志监控
ActivityTransitionReceiver的调用频率,以及服务的生命周期(onCreate/onStartCommand/onDestroy),便于定位服务是否被系统回收; - 定期记录最后一次接收活动更新的时间,通过WorkManager检查超时情况,主动触发服务重启。
内容的提问来源于stack exchange,提问作者Vishwas Bhatt

