8

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

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

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

4

3 回答 3

2

最后,我找到了解决该问题的方法,在阅读了 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");
    [...]
}
于 2017-10-19T13:15:48.293 回答
0

您的应用程序的行为正是doze旨在停止的行为。Android 6 中引入的 Doze 通过将活动推迟到维护时段来降低设备的功耗。GPS 耗电巨大,不允许在打盹模式下持续运行。如果允许,电池可能会以与屏幕打开时相似的速度耗尽;网络流量的优化不会增加电池寿命。如果您希望 GPS 位置每 1 秒更新一次,则必须阻止设备进入打盹模式。

Android 5 中没有打盹模式。

于 2017-09-16T13:57:17.553 回答
0

如果您使用“adb shell dumpsys deviceidle force-idle”等命令在模拟器上测试位置和打盹模式。您可能注意到位置在打盹模式下停止。

但是......作为“文档”代表:

“只要用户通过移动设备、打开屏幕或连接充电器唤醒设备,系统就会退出 Doze,所有应用程序都会恢复正常活动”

来源:https ://developer.android.com/training/monitoring-device-state/doze-standby

所以......使用 GPS 操纵杆应用程序或类似的移动您的模拟器,您会注意到该位置从打盹模式中唤醒。

于 2019-12-10T16:16:44.517 回答