防止 Oreo 或 Pie 在后台暂停 LocationListener

Prevent Oreo or Pie to pause LocationListener when in background

我已经完成了一个供个人使用的应用程序(徒步旅行时进行 GPS 跟踪,并将位置发送给另一个 phone,用于调查)。

它在 Lolipop 下运行良好。

新 phone,在 Pie 下。

如果应用程序在前台工作正常,但在后台时由 Pie 设置为暂停。

如何让它在后台运行?

我在“Device Care” > “Battery” > “App power management”取消选中“自适应电池”或“让未使用的应用程序进入睡眠状态”不起作用。 我把我的应用程序放在 "Apps that won't be put to sleep" 但也不起作用。

是否有 "simple way" 以编程方式使我的应用程序在后台保持活动状态?

安卓清单?或者与屏幕相同: getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

我的应用基于onLocationChanged(final Location location)

感谢帮助 问候

其中一个选项是使用 Alarm Manager to request a run of a receiver time to time (say, every minute, or even every few seconds), or request location updates from LocationManager

经过大量搜索,我想我在这里找到了解决方案:https://developer.android.com/training/location/permissions

问题是我获得了需要新权限的 API29 (android 10)(在 android 8 或 9 中不需要)。

它在 androidManifest.xml

如果在前景中:

<!-- Recommended for Android 9 (API level 28) and lower. -->
<!-- Required for Android 10 (API level 29). -->
<service
    android:name="MyNavigationService"
    android:foregroundServiceType="location" ... >
    <!-- Any inner elements would go here. -->
</service>

或者如果在后台:

<manifest ... >
  <!-- Required only when requesting background location access on
       Android 10 (API level 29). -->
  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
</manifest>

我只测试了前台解决方案 android:foregroundServiceType="location",它工作正常。

编程是一项艰巨的工作。知识更难。

玩得开心。谢谢