由于我用的AS版本比较高,创建布局文件时默认使用ConstraintLayout
布局作为根布局,再用RemoteViews加载自定义布局就会出现发送通知不显示的情况。
解决办法就是将根布局换成RelativeLayout
或者LinearLayout
这两个常用的都行,反正通知栏也不会用到太复杂的布局。
下面贴上创建通知栏以及RemoteViews使用的代码:
val intent = Intent(this@TestCustomViewActivity,MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this@TestCustomViewActivity,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
val channelId = "channelId"
val channelName = "channelName"
val channel = NotificationChannel(channelId,channelName,NotificationManager.IMPORTANCE_LOW)
val remoteViews = RemoteViews(packageName,R.layout.test_notification_custom_layout)
remoteViews.setTextViewText(R.id.content_tv,"自定义通知栏文字内容")
remoteViews.setImageViewResource(R.id.notification_iv,R.drawable.abc_vector_test)
remoteViews.setOnClickPendingIntent(R.id.custom_btn,pendingIntent)
val notification = NotificationCompat.Builder(this,channelId)
// .setContentTitle("hello world")
// .setContentText("我是一个notification")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_LIGHTS)
.setContentIntent(pendingIntent)
.setCustomContentView(remoteViews)
.build()
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
manager.notify(1,notification)
网友评论