我正在使用特别的前台服务,并根据 Google 指南进行 Android 14 更新。
在大多数 Android 14 设备上,这工作正常,但在某些设备上,我遇到以下异常 我正在捕捉:
Non-fatal Exception: java.lang.SecurityException
Starting FGS with type specialUse callerApp=ProcessRecord{a5fde95 20787:com.myapp/u0a432} targetSDK=34 requires permissions: all of the permissions allOf=true [android.permission.FOREGROUND_SERVICE_SPECIAL_USE]
这是由以下代码触发的:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
{
ServiceCompat.startForeground(this, COUNTDOWN_SERVICE_ID, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
}
else
{
startForeground(COUNTDOWN_SERVICE_ID, notification);
}
我已经看到其他代码位的问题,即使已授予服务权限,我也必须在运行时显式检查三星设备上的服务权限,因此我添加了以下内容:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE) == PackageManager.PERMISSION_GRANTED)
{
// start foreground service
但这并没有解决问题。 如果我检查
if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_SPECIAL_USE) == PackageManager.PERMISSION_GRANTED)
,那么它在我测试过的 Android 14 设备上返回 false。
为了完整起见,我的清单包含以下内容:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
...
<service
android:name=".CountService"
android:foregroundServiceType="specialUse"
android:exported="false">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="[Description of why foreground service is needed]" />
</service>
Google 明确表示 FGSspecialUse 不需要运行时检查。 有人知道缺少什么吗?
在防止此错误的最后一次尝试中,我添加了以下双重检查,该检查在 Samsung Android 14 Galaxy 选项卡上返回 true:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_SPECIAL_USE) == PackageManager.PERMISSION_GRANTED)
{
ServiceCompat.startForeground(this, COUNTDOWN_SERVICE_ID, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
}
现在还为时过早,但到目前为止我还没有看到最初的异常:
Non-fatal Exception: java.lang.SecurityException
Starting FGS with type specialUse callerApp=ProcessRecord{a5fde95 20787:com.myapp/u0a432} targetSDK=34 requires permissions: all of the permissions allOf=true [android.permission.FOREGROUND_SERVICE_SPECIAL_USE]