【问题标题】:startForeground fails with Bad notification for startForegroundstartForeground 因 startForeground 的错误通知而失败
【发布时间】:2021-05-11 15:00:11
【问题描述】:

我正在尝试启动前台服务,但它失败了

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)

我的代码有什么问题?

【问题讨论】:

  • 您是否尝试在通知中添加图标?
  • @CommonsWare 是的,我尝试使用.setSmallIcon(R.drawable),但它也不起作用。

标签: android kotlin service


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 2019-11-23
    • 1970-01-01
    相关资源
    最近更新 更多