GPS定位跟踪,即使应用程序关闭(不在后台运行)/屏幕锁定应用程序、后台、屏幕、GPS

2023-09-07 04:53:01 作者:烟比女人亲,伤肺不伤心

我想跟踪与 strava 非常相似的用户位置,即使在关闭之后也是如此.

I want to track user location very similar to strava, even after the is closed.

我尝试了 AlarmManager,但它没有每分钟执行一次

I tried AlarmManager but it's not giving me execution after every one minute

推荐答案

如果设备进入睡眠模式,仅使用 BiGGZ 解释的服务将不起作用.虽然服务不会被杀死,但您的应用程序不会获得任何 CPU.因此,您必须获取部分唤醒锁以防止设备进入睡眠模式.

Just using a Service as BiGGZ explained won't work in case the device enters sleep mode. The Service won't be killed though but your app won't get any CPU. Therefore you would have to acquire a partial Wakelock to prevent the device from entering sleep mode.

@Override
public void onCreate() {
  super.onCreate();
  PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
  wakeLock = m.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Some Tag");
  wakeLock.acquire();
  ...
}

@Override
public void onDestroy() {
  wakeLock.release();
}

如果您需要的位置更新频率较低,您可以使用 AlarmManager 并设置触发位置更新的重复警报.警报应该触发一个 BroadcastReceiver,因为它不能保证在设备再次进入睡眠状态之前成功启动服务.见这里:https://developer.android.com/reference/android/app/AlarmManager.html

If you need Location updates less frequently you could use the AlarmManager and set a repeating alarm which triggers a Location update. The alarm should trigger then a BroadcastReceiver, since it's not guaranteed that a Service is successfully started before the device goes back to sleep again. See here: https://developer.android.com/reference/android/app/AlarmManager.html