美文网首页
Android 通知栏自定义样式

Android 通知栏自定义样式

作者: 笑慢 | 来源:发表于2019-11-10 20:00 被阅读0次

    8.0系统的通知栏适配

    在8.0之前我们通知栏的使用:

     notification = new NotificationCompat.Builder(mContext)
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.drawable.small_icon)
    

    但如果SDK升级到8.0或者以上你会发现这个构建通知的方法已经废弃,并且无法显示通知,这是因为在8.0上引用了产商通道的概念,所以在8.0及以上构建通知的方法改为:

    NotificationManager  mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    int importance = NotificationManager.IMPORTANCE_HIGH;
    NotificationChannel mChannel = new NotificationChannel(channelId, channelName, importance);
    mNotificationManager.createNotificationChannel(mChannel);
    

    通知栏自定义样式

    自定义通知栏我们就要使用RemoteViews了,在SDK为16及以上才支持。

    private RemoteViews getContentBigView() {
            mRemoteViews = new RemoteViews(mContext, R.layout.view_baig_notify);
            return mRemoteViews;
        }
    

    自定义通知栏会有大图样式和小图样式即普通样式和扩展样式,高度上边会有要求限制,普通样式高度不能超过64dp,扩展高度不能超过256dp。
    今天我们主要讲一下大小图样式显示的适配。
    如果我们可爱的产品和设计妹子给到了优美的大图样式,那我们的设置方法如下:

     Notification notification = new NotificationCompat.Builder(mContext, id)
                        .setSmallIcon(R.drawable.small_icon)
                        .setWhen(System.currentTimeMillis())
                        .setContentIntent(getDefaultIntent(Notification.FLAG_ONGOING_EVENT))
                        .setCustomBigContentView(getContentBigView()
                        .setChannelId(mChannel.getId())
                        .build();
     mNotificationManager.notify(NOTIFICATION_ID, notification);
    

    在手机上运行一下,看到了大图样式那么好看,美滋滋的提交代码,提测给测试。but,,,测试拿着手机来告诉你通知栏大图样式显示不完整,what。。。拿起手机一看,真的是。。。 为什么自己手机上是可以的呢?天杀的通知栏适配,这个通知栏的高度不同的机型不同的room可能测绘出来的大小不同。
    仔细看了网易云音乐通知栏的样式,发现适配了默认样式和扩展样式,那么,我们就再适配一套默认样式吧。

    Notification notification = new NotificationCompat.Builder(mContext, id)
                        .setSmallIcon(R.drawable.small_icon)
                        .setWhen(System.currentTimeMillis())
                        .setContentIntent(getDefaultIntent(Notification.FLAG_ONGOING_EVENT))
                        .setCustomContentView(getContentView())
                        .setCustomBigContentView(getContentBigView()
                        .setChannelId(mChannel.getId())
                        .build();
     mNotificationManager.notify(NOTIFICATION_ID, notification);
    
    private RemoteViews getContentView() {
            mRemoteViews = new RemoteViews(mContext, R.layout.view_notify);
            return mRemoteViews;
        }
    

    上图,画质有些渣。。。


    QQ图片20191217104750.gif

    这样,通知栏的样式适配就完成了,当然还有一些背景颜色和字体颜色的适配,这里就不展开讲了。
    demo地址:https://github.com/still-soul/LockDemo

    相关文章

      网友评论

          本文标题:Android 通知栏自定义样式

          本文链接:https://www.haomeiwen.com/subject/fkgabctx.html