android - 如何在 android Nougat 及以上版本中创建 Notification.contentView?

标签 android android-notifications android-7.0-nougat

我使用 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。

最佳答案

Notification.contentView()

示例代码

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

输出

enter image description here

关于android - 如何在 android Nougat 及以上版本中创建 Notification.contentView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52094633/

相关文章:

java - 在 Android 中处理暂停/恢复和使用通知(使用 AndEngine)

java - FontAwesome 图标不会显示在 Android 应用程序上

android - 当收到多个 Android 通知时,只有最新的一个上的操作按钮有效

android - 仅在牛轧糖上出现 TransactionTooLargeException

android - 状态栏覆盖图像在 android 中下移了

android - 键盘弹起时 ScrollView 不起作用

android - ListView 在滚动时显示错误位置的图像

android - 如何在工具栏上设置 NAVIGATION_MODE_LIST new appcompat v7 21

android - 从后台关闭应用程序后取消通知

android - Android N之后如何获取实际屏幕尺寸?