Android 10及以上系统GPS追踪前台服务运行一段时间后停止问题求助
核心根因
Android 10开始对后台位置更新、前台服务生命周期、低功耗模式下的GPS调度做了严格限制,现有实现存在4个核心问题:
- 定位监听器每次拿到位置就主动注销,后续GPS硬件休眠后再次注册无法主动唤醒
- 主线程Handler的定时逻辑在设备进入低功耗模式后会被系统拉长执行间隔,甚至暂停
- 未持有适配Android 10+的定位相关唤醒锁,无法保持GPS硬件活跃
- PendingIntent未适配Android 12+ flag规则,导致前台服务容易被系统回收
具体修改步骤
1. 调整定位监听器逻辑,避免频繁注册/注销
原有逻辑每次拿到位置就调用stopLocationListener注销监听器,是GPS休眠后无法唤醒的核心原因,修改CustomerLocationListener代码:
@Override public void onLocationChanged(Location location) { this.location = location; // 直接触发位置上报,不要注销监听器 writeLocationToServer(location); } // 仅在服务销毁、全局定位开关关闭时调用注销逻辑 public void stopLocationListener() { if(locationManager != null) { locationManager.removeUpdates(this); } }
保持定位监听器长期注册,设置合理的GPS_TIME_INTERVAL(推荐60秒)和GPS_DISTANCE(推荐10米),由系统自动按间隔回调位置,不需要主动轮询触发注册。
2. 替换主线程Handler为AlarmManager实现定时保活
主线程Handler在设备锁屏进入低功耗模式后会被系统限制,替换为AlarmManager的精确唤醒任务,保证定时逻辑正常执行。
在LocationTracker的onCreate中添加如下代码替换原有Handler逻辑:
// 初始化定时唤醒任务 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent alarmIntent = new Intent(this, LocationTracker.class); alarmIntent.setAction("CHECK_LOCATION_ACTION"); int pendingFlag = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_UPDATE_CURRENT; PendingIntent pendingIntent = PendingIntent.getService(this, 0, alarmIntent, pendingFlag); // 每隔60秒触发一次定位检查 long interval = 60 * 1000; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, pendingIntent); } else { alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, pendingIntent); }
在onStartCommand中新增CHECK_LOCATION_ACTION处理逻辑,检查位置是否正常更新,无更新则主动触发一次requestLocationUpdates唤醒GPS。
3. 新增GPS唤醒锁持有逻辑
Android 10+需要单独持有唤醒锁才能保持GPS硬件活跃,在LocationTracker的onCreate中添加:
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock gpsWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp:GPSWakeLock"); gpsWakeLock.setReferenceCounted(false); // 服务运行期间长期持有 gpsWakeLock.acquire();
在LocationTracker的onDestroy中释放唤醒锁:
if (gpsWakeLock != null && gpsWakeLock.isHeld()) { gpsWakeLock.release(); }
4. 修复PendingIntent兼容性问题
原有PendingIntent使用flag=0,在Android 12+上会导致前台服务被系统强制回收,修改onStartCommand中的PendingIntent配置:
int pendingFlag = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_UPDATE_CURRENT; PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, pendingFlag);
5. 优化前台服务优先级
针对Zebra工业设备特性,在Manifest的LocationTracker服务配置中添加persistent属性提升服务优先级:
<service android:name=".Services.LocationTracker" android:enabled="true" android:foregroundServiceType="location" android:persistent="true"> </service>
内容的提问来源于stack exchange,提问作者Boeykes

