启动前台服务,警告提示 @SuppressLint("ForegroundServiceType")
private fun createNotificationAndStartForeground() {
startForeground(NOTIFICATION_ID, createNotification())
}
@SuppressLint("ForegroundServiceType") 特别用于抑制与前台服务类型相关的 Lint 警告。在 Android 10 (API 级别 29) 及以上版本中,前台服务需要在 manifest 文件中声明特定的前台服务类型。
从 Android 10 开始,前台服务必须在 标签中使用 android:foregroundServiceType 属性指定其类型,例如:
-
"location"(位置)
-
"camera"(相机)
-
"microphone"(麦克风)
-
"mediaProjection"(媒体投影)
等等
如果你的前台服务没有正确声明其类型,Android Studio 的 Lint 检查会发出警告。使用 @SuppressLint("ForegroundServiceType") 注解可以抑制这个警告,但这并不意味着你可以忽略这个要求 - 在生产环境中,你应该正确声明前台服务类型。
正确的做法:
不是简单地抑制警告,而是在 AndroidManifest.xml 中正确声明服务类型:
<service
android:name=".MyForegroundService"
android:foregroundServiceType="location|camera"
... >
</service>
或者在代码中使用 ServiceInfo 类的常量:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)}