我收到了一些用户在Android 8+上的Google Pixel 2,LG Nexus 5X和Nokia 6、7或8等设备上的以下崩溃报告。我无法在8.0版的LG V30,Android 9.0版的Google Pixel或8.1版的模拟器上重现此崩溃。
Fatal Exception: android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=-2 contentView=null vibrate=null sound=null smartAlertCount=0x0 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:6501)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
在我的代码中,有关startForeground的唯一通知是使用android.media.MediaPlayer播放音频时显示的通知。我怀疑此通知是例外的通知,因为许多用户告诉我MediaPlayer无法在他们的手机上工作-但我不太确定,因为崩溃日志无法准确告知发生此错误的位置。
用于创建此通知的Kotlin代码如下:
class MediaPlayerService : Service() {
private var mediaPlayer: MediaPlayer? = null
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
mediaPlayer = MediaPlayer()
mediaPlayer?.let { mediaPlayer ->
mediaPlayer.setOnPreparedListener(MediaPlayer.OnPreparedListener {
mediaPlayer.start()
showNotification()
})
try {
mediaPlayer.setDataSource(URL)
mediaPlayer.prepareAsync()
} catch (exception: IOException) {
exception.printStackTrace()
}
}
return Service.START_NOT_STICKY
}
fun showNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
val channel = NotificationChannel(
"channel_id",
"Channel",
android.app.NotificationManager.IMPORTANCE_LOW
).apply {
lightColor = Color.GREEN
enableVibration(true)
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
setSound(Settings.System.DEFAULT_NOTIFICATION_URI, null)
setShowBadge(false)
}
notificationManager?.createNotificationChannel(channel)
}
NotificationCompat.Builder(context, "channel_id")
.setPriority(NotificationCompat.PRIORITY_LOW)
.setGroup("channel_id")
.setGroupSummary(false)
.setColor(Color.GREEN)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setAutoCancel(true)
.setSmallIcon(R.drawable.icon_small)
.setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.icon_large))
.setContentTitle("Title")
.setContentText("Text")
.setTicker("Text")
.setStyle(NotificationCompat.BigTextStyle().bigText("Text"))
.setNumber(1)
.build()
}
我正在使用所有通知的通知通道,包括上面的通知。我无法重现这些通知的任何问题,因为它们对于推式通知似乎都可以正常工作-而且在大多数情况下,对于前台服务也是如此。
有什么我想念的吗?
答案 0 :(得分:0)
“ mysun”的观察结果减少了对我的前台服务的投诉:
setSmallIcon(R.drawable.icon_small)
所致,在某些情况下(例如,当您启动重新启动系统以发送通知时)尚未准备就绪,导致应用程序异常。setSmallIcon(context.getApplicationInfo().icon)
请参阅mysun的fatalerrors.org post here