创建通知渠道
如果创建的通知渠道已存在,不会执行任何操作,因此启动应用时可以放心地执行以下代码(可先在application中执行)
public static NotificationManager notificationManager;
public static String CHANNEL_1 = "channel1";
public static void init(Context context){
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(CHANNEL_1,
"通知渠道1", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("通知渠道的描述1");
channel1.enableLights(true);
channel1.setLightColor(Color.WHITE);
notificationManager.createNotificationChannel(channel1);
}
}
创建通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,NotificationConfig.CHANNEL_1);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("标题")
.setContentText("内容");
发送通知
NotificationConfig.notificationManager.notify(1, builder.build());
注意事项
可以同时创建多个通知渠道
1.创建单个通知渠道
代码同上,效果如下:
2.创建多个通知渠道
代码:
public static NotificationManager notificationManager;
public static String CHANNEL_1 = "channel1";
public static void init(Context context){
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel("channel1",
"通知渠道1", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("通知渠道的描述1");
channel1.enableLights(true);
channel1.setLightColor(Color.WHITE);
NotificationChannel channel2 = new NotificationChannel("channel2",
"通知渠道2", NotificationManager.IMPORTANCE_HIGH);
channel2.setDescription("通知渠道的描述2");
channel2.enableLights(true);
channel2.setLightColor(Color.WHITE);
NotificationChannel channel3 = new NotificationChannel("channel3",
"通知渠道3", NotificationManager.IMPORTANCE_HIGH);
channel3.setDescription("通知渠道的描述3");
channel3.enableLights(true);
channel3.setLightColor(Color.WHITE);
List<NotificationChannel> channels = new ArrayList<>();
channels.add(channel1);
channels.add(channel2);
channels.add(channel3);
notificationManager.createNotificationChannels(channels);
}
}
效果如下: