startForeground失败,startForeground的通知错误



我试图启动前台服务,但失败了

val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)
val builder: NotificationCompat.Builder
builder =
if (Build.VERSION.SDK_INT >= 26) {
val channelId = "noti_channel"
val channel = NotificationChannel(channelId, "Notification Channel", NotificationManager.IMPORTANCE_DEFAULT)
if (!getSharedPreferences("Imhere", Context.MODE_PRIVATE).getBoolean("isNotificationCreated", false)) {
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
getSharedPreferences("Imhere", Context.MODE_PRIVATE).edit().putBoolean("isNotificationCreated", true).apply()
}
NotificationCompat.Builder(this, channelId)
} else {
NotificationCompat.Builder(this)
}
builder
.setContentTitle("Location Service")
.setContentText("Service running in foreground")
.setContentIntent(pendingIntent)
startForeground(502, builder.build())

此代码在Service本身中,因此Service onCreate方法调用此代码块上次它起作用了,但当我删除应用程序并重新安装时,它开始失败。

2020-08-30 05:08:19.233 706-706/{app package name} E/AndroidRuntime: FATAL EXCEPTION: main
Process: {app package name}, PID: 706
android.app.RemoteServiceException: Bad notification for startForeground
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2141)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8016)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1076)

我的代码出了什么问题?

自我回答:这是因为备份内容。在我的代码中,我使用SharedPreference来检查通知通道是否已创建。但BackupManager即使在应用程序被删除后也保存了我的SharedPreference,所以当重新安装应用程序时,不会创建通知通道。我更改了AndroidManifest.xml,如下所示,它清除了我的SharedPreference。现在效果很好。

<application
android:allowBackup="false"
android:fullBackupOnly="false"
android:fullBackupContent="false"

最新更新