Android Crash:Bad notification for startForeground

Android 8.0开始Notification 需要指定一个channel,当target大于26时,这个channel需要进行系统注册,否则会crash,crash信息如下:

android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=default pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
  at android.os.Handler.dispatchMessage(Handler.java:106)
  at android.os.Looper.loop(Looper.java:164)
  at android.app.ActivityThread.main(ActivityThread.java:6494)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

修改方案

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  val channelId = "default"
  val channel = NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT)
  val nm = service.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
  nm?.let {
    if (it.getNotificationChannel(channelId) == null) {//没有创建
      it.createNotificationChannel(channel)//则先创建
    }
  }
  val notification: Notification
  val builder = Notification.Builder(service, channelId)
  .setContentTitle("")
  .setContentText("")
  notification = builder.build()
  service.startForeground(FOREGROUND_SERVICE_NOTIFICATION_ID, notification)
}


private void createNotificationChannel(NotificationManager manager) {
        if (manager.getNotificationChannel("default") == null) {
            NotificationChannel notificationChannel =
                    new NotificationChannel("default",
                            "notification_channel",
                            NotificationManager.IMPORTANCE_LOW);

            notificationChannel.setDescription(
                    "notification_channel_description");

            manager.createNotificationChannel(notificationChannel);
        }
    }

 

你可能感兴趣的:(Android,Crash合集)