我使用 Notification.contentView
复制通知 View :
View notificationView = notification.contentView.apply(context, parent);
不幸的是,从版本 N 开始,Notification.contentView
可能为 null 且已弃用,那么如何手动创建 Notification.contentView
?
通常我这样创建通知:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
builder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentTitle(title)
.setContentText(text)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(when)
.setSmallIcon(smallIcon);
那么如果我手动创建contentView,我可以做些什么来映射以上所有设置?
重要提示:我没有调用 setCustomContentView,我想为标准通知重现一个 contentView。
最佳答案
<YES
从android N,这个字段可能是null
通知 View 由
Notification.Builder;
的输入决定Notification.Builder.setCustomContentView(RemoteViews)
可以选择提供自定义RemoteViews
示例代码
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "Nilesh_channel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("");
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
mNotificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.custom_layout);
notificationBuilder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentTitle(getString(R.string.app_name))
.setContentText("")
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setCustomContentView(notificationView) // set here your RemoteViews
.setAutoCancel(true);
输出
关于android - 如何在 android Nougat 及以上版本中创建 Notification.contentView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52094633/