我正在实现一个带有返回位置的服务的 Android 应用程序,因此我已将属性 foregroundServiceType 设置为“location”。这是清单文件中我的服务:
<service
android:name=".Services.PositionService"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE"
android:foregroundServiceType="location"
/>
这是我的清单中声明的权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION"/>
但是当我的应用程序尝试启动时,它突然崩溃并给出错误:
java.lang.RuntimeException: Unable to start service com.mhealthcs.Services.PositionService@12db7c9 with Intent { cmp=com.mhealth/com.mhealthcs.Services.PositionService }: java.lang.SecurityException: Starting FGS with type location callerApp=ProcessRecord{ea33e0e 3543:com.mhealth/u0a251} targetSDK=34 requires permissions: all of the permissions allOf=true [android.permission.FOREGROUND_SERVICE_LOCATION] any of the permissions allOf=false [android.permission.ACCESS_COARSE_LOCATION, android.permission.ACCESS_FINE_LOCATION] and the app must be in the eligible state/exemptions to access the foreground only permission
我该如何解决
您遇到的问题似乎与 Android 14 上的前台服务权限有关。从 Android 12 开始,请求位置更新的前台服务必须同时拥有前台服务权限 (FOREGROUND_SERVICE) 和位置权限(ACCESS_FINE_LOCATION 或 ACCESS_COARSE_LOCATION)。此外,如果您的应用面向 API 级别 34 (Android 14),它还必须显式请求 FOREGROUND_SERVICE_LOCATION 权限。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />