最后,我通过阅读com.android.internal.location.GpsLocationProvider的源代码找到了该问题的解决方法.我注意到发送了一个com.android.internal.location.ALARM_WAKEUP意图阻止了位置提供程序打瞌睡.因此,为了防止GPS打瞌睡,我每隔10秒广播一次意图,我在服务类中添加了以下内容:
[...]
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");
[...]
}