代码之家  ›  专栏  ›  技术社区  ›  wgm

如何创建通知.contentView在安卓牛轧糖及以上?

  •  1
  • wgm  · 技术社区  · 6 年前

    我用 Notification.contentView 要复制通知视图,请执行以下操作:

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

    不幸的是,从N版开始, 通知.contentView 通知.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 回复  |  直到 6 年前
        1
  •  3
  •   AskNilesh    6 年前

    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

        2
  •  2
  •   wgm    6 年前

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

    builder.createContentView();
    

    内容视图 Notification

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

    Notification.Builder.createContentView() 是在api级别24中引入的,因此上面的代码只能从Nougat 7.0或更新的设备调用;对于较低版本的手机,引用非null总是安全的通知.contentView它直接由android系统自动创建生成器.build()已调用。