问题
I tried to background services like this code, but after first alert app crashed. And gave this error:
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
My code :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mNotification = Notification.Builder(this, CHANNEL_ID)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(Notification.BigTextStyle()
.bigText(message))
.setContentText(message).build()
} else {
mNotification = Notification.Builder(this)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX)
.setContentTitle(title)
.setStyle(Notification.BigTextStyle()
.bigText(message))
.setContentText(message).build()
}
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(mNotificationId, mNotification)
回答1:
You forgot to create a channel. It should be like this:
mNotification = Notification.Builder(this, CHANNEL_ID)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(Notification.BigTextStyle()
.bigText(message))
.setContentText(message).build()
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID,
"Channel title",
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(mNotificationId, mNotification)
来源:https://stackoverflow.com/questions/61067561/bad-notification-for-startforeground-error