gpt4 book ai didi

android - 在打瞌睡模式下获取位置更新

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:46 28 4
gpt4 key购买 nike

我正在尝试在打瞌睡模式下在我的 android 应用程序中获取位置更新,这曾经适用于 android 5.x。随着 android 6 和 doze 的出现,无论我做什么,更新都会在某个时候停止。在阅读了有关该主题的一些文章和 stackoverflow 答案后,我进行了以下更改:

  • 使我的服务成为前台服务
  • 让服务持有部分唤醒锁
  • 我已授予我的应用 WAKE_LOCK 权限
  • 使服务在单独的进程中运行(以解决一些 android 错误)
  • 我已为我的应用停用电池优化

但是,当打瞌睡开始时,我仍然没有获得位置更新。我已经验证我的服务线程在打瞌睡开始时继续运行(通过定期记录消息),但是位置管理器以某种方式停止发送更新。关于打瞌睡和 LocationManager 的文档在这方面非常少,所以我想知道是否有人知道让位置管理器在打瞌睡时保持 Activity 状态的方法? LocationManager 上是否有一些方法,如果定期调用将使 LocationManager 保持 Activity 状态?请注意,我只对 GPS 更新感兴趣,更新频率很高,每秒一次。

最佳答案

最后,我找到了解决该问题的方法,在阅读了 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");
[...]
}

关于android - 在打瞌睡模式下获取位置更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46254488/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com