Android Q - 从后台启动前台定位服务

Android Q - Start foreground location service from the background

我不确定在这种情况下应该有什么行为。

文档中说:

An app is considered to be accessing location in the background unless one of the following conditions is satisfied:

  • An activity belonging to the app is visible.
  • The app is running a foreground service that has declared a foreground service type of location.

在 google 提供的示例中,他们使用 Activity 在前台 启动前台服务 :

https://github.com/android/location-samples/tree/master/LocationUpdatesForegroundService

就我而言,一旦蓝牙设备连接到我的设备(使用清单注册的广播接收器),我就需要开始跟踪位置 - 这可能在后台,或者在应用程序终止后)。

所以,我像他们说的那样在清单中声明服务:

 <service
       android:name=".MyForegroundService"
       android:foregroundServiceType="location"
       android:exported="false" />

问题是:

如果我的应用程序收到广播,在后台/终止 - 如果我启动前台服务,它是否被视为正在访问位置后台正在前台访问位置?

我应该请求 ACCESS_BACKGROUND_LOCATION 吗?或者 ACCESS_COARSE_LOCATION 在这种情况下应该足够了吗?

在 API 29,如果你有一个 android:foregroundServiceType"location",你不需要 ACCESS_BACKGROUND_LOCATION。在 Service 为 运行 时进行的任何位置访问都被视为 "foreground access".

但这假设您可以获得前台服务运行。您必须继续某种 user-initiated action。如果 Service 已经是 运行,那就没问题; Service 表示用户启动的操作的继续。如果您需要在 BT 设备连接时启动它,那么,我不确定是否符合条件。那可能行不通。 (如果您发现...请提出修改建议!)

需要 ACCESS_BACKGROUND_LOCATION 许可的应用程序示例是在没有 Activities 可见且没有 "location" 类型的前台服务通知正在显示。在 Android Q 上,未经许可,不允许持续很长时间(超过约 30 秒)。

我相信 OS 还会将 ACCESS_BACKGROUND_LOCATION 分配给用户在位置权限对话框中选择 "Allow all the time" 的旧版应用程序。