如何在 android 牛轧糖及更高版本中创建 Notification.contentView?

How to create Notification.contentView in android Nougat and above?

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

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

输出

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

builder.createContentView();

通过 Notification 创建 contentView

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

由于Notification.Builder.createContentView()是在api level 24中引入的,所以以上代码只能在Nougat 7.0或更新的设备上调用;对于较低版本的手机,直接引用非空 Notification.contentView 总是安全的,它是在调用 builder.build() 后由 android 系统自动创建的。