notification channel

[TOC]

目的

在开发过程中,现在的手机的版本8.0的越来越多了,决定去适配一些8.0的通知,前面的开发都是停留在25上面,也就是android7.1的设备,最近google在9.0的android设备上已经强制了 targetSdk的版本为当前手机的版本,所以适配还是很有必要的。

具体实现

1
2
3
4
5
6
7
8
9
10
11
12
String channelId = "upgrade"; //这个在发送通知的时候需要用到,不然通知无法显示
String channelName = "升级";
int importance = NotificationManager.IMPORTANCE_HIGH;
createNotificationChannel(this, channelId, channelName, importance);


private static void createNotificationChannel(Context context, String channelId, String channelName, int importance) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}

得到通知消息后的显示:

1
2
3
4
5
6
7
8
9
10
11
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
//这里使用在初始化的时候创建好的channelId 就是 upgrade 这个
Notification notification = new NotificationCompat.Builder(context, "upgrade")
.setContentTitle("加班")
.setContentText("程序员终于开始加班了。。")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setAutoCancel(true)
.build();
manager.notify(101, notification);

产考:

targetSdkVersion升级到28一些修改的地方(持续更新)

NotificationChannel 适配填坑指南