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

时间:2018-08-30 10:20:50

标签: android android-notifications android-7.0-nougat

我使用Notification.contentView复制通知视图:

View notificationView = notification.contentView.apply(context, parent);

不幸的是,从版本N开始,Notification.contentView可能为空且已弃用,那么如何手动创建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。

2 个答案:

答案 0 :(得分:2)

  

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

答案 1 :(得分:1)

回答我自己的问题:
通过contentView创建Notification.Builder

builder.createContentView();

通过contentView创建Notification

Notification.Builder.recoverBuilder(context, notification).createContentView();

由于Notification.Builder.createContentView()是在api级别24中引入的,因此上述代码只能从Nougat 7.0或更高版本的设备中调用;对于较低版本的手机,直接引用非null的Notification.contentView始终是安全的,它是在调用builder.build()之后由android系统自动创建的。