最后,我找到了解决该问题的方法,在阅读了 com.android.internal.location.GpsLocationProvider 的源代码后,我注意到向它发送 com.android.internal.location.ALARM_WAKEUP Intent 可以防止位置提供程序打瞌睡。因此,为了防止 GPS 打瞌睡,我每 10 秒广播一次 Intent,我在服务类中添加了以下内容:
[...]
private Handler handler;
private PowerManager powerManager;
private PendingIntent wakeupIntent;
private final Runnable heartbeat = new Runnable() {
public void run() {
try {
if (isRecording && powerManager != null && powerManager.isDeviceIdleMode()) {
LOG.trace("Poking location service");
try {
wakeupIntent.send();
} catch (SecurityException | PendingIntent.CanceledException e) {
LOG.info("Heartbeat location manager keep-alive failed", e);
}
}
} finally {
if (handler != null) {
handler.postDelayed(this, 10000);
}
}
}
};
@Override
public void onCreate() {
handler = new Handler();
wakeupIntent = PendingIntent.getBroadcast(getBaseContext(), 0,
new Intent("com.android.internal.location.ALARM_WAKEUP"), 0);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TrackService");
[...]
}