Android Crash:Bad notification for startForeground

从Android8.0开始,应用在启动前台服务并显示通知时,必须为通知指定一个渠道。若目标API级别大于等于26且未正确设置通知渠道,应用将崩溃。本文详细介绍了如何为应用创建并注册通知渠道,确保应用在高版本Android系统上正常运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值