Android 问 - 前台服务需要后台位置权限吗?

Android Q - Background Location Permission needed for Foreground service?

本文档的第一点指出,如果在应用程序处于前台启动时启动前台定位服务,则需要后台定位权限 Android 11.

https://developer.android.com/guide/components/foreground-services#bg-access-restrictions

我的用例是用户点击按钮开始位置跟踪。点击该按钮会启动一个前台服务,该服务会发出通知。现在,我希望应用程序即使在后台运行后也能继续跟踪。 在 Android 10 之前,完成此操作不需要后台位置权限。

我的问题是,为了支持Android11,我是否也需要开始请求后台权限?另外,我是否需要为 Android 10 做同样的事情?在互联网上找不到任何其他参考来验证这一点。请让我知道你的想法。

根据the definition of background work

An app is considered to be running in the background as long as each of the following conditions are satisfied:

  1. None of the app's activities are currently visible to the user.
  2. The app isn't running any foreground services that started while an activity from the app was visible to the user.

Otherwise, the app is considered to be running in the foreground.

在您的情况下,您属于第二点,当用户看到 activity 时启动前台服务,因此从技术上讲,您的应用程序仍被视为在前台,而服务通知是即使用户导航离开您的应用程序也会显示。

如果您的目标是 Android 10 及以上,则前台服务的清单声明中需要包含 android:foregroundServiceType="location"。参见 here

如果您在创建的前台服务中获取位置更新,则您不一定需要 ACCESS_BACKGROUND_LOCATION 权限,因为从技术上讲,您并不是在后台访问位置。但是,在您的服务中,如果您使用任何可能需要后台位置权限的 API,例如 Geofencing,那么您将需要将后台权限添加到清单中,并相应地请求和处理权限。