Android 通知栏自定义样式

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

上图,画质有些渣。。。
如图,画质有些渣。。。
这样,通知栏的样式适配就完成了,当然还有一些背景颜色和字体颜色的适配,这里就不展开讲了。
点击这里获取demo

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值