使用NotificationChannel非常简单。
NotificationChannel实际上将多个通知分组到通道中。它基本上为用户提供了更多的通知行为控制。您可以在使用示例 | Working with Notification Channel中了解有关Notification Channel及其实现的更多信息。
创建Notification Channel
public static final String NOTIFICATION_CHANNEL_ID="channel_id";
public static final String CHANNEL_NAME="Notification Channel";
int importance=NotificationManager.IMPORTANCE_DEFAULT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setVibrationPattern(new long[]{500,500,500,500,500});
notificationChannel.setLockscreenVisibility(
Notification.VISIBILITY_PUBLIC);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
现在,在创建通知时,只需将频道 ID 传递给如下所示的通知构建器构造函数即可
//We pass the unique channel id as the second parameter in the constructor
NotificationCompat.Builder notificationCompatBuilder=new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID)
//Title for your notification
notificationCompatBuilder.setContentTitle("This is title")
//Subtext for your notification
notificationCompatBuilder.setContentText("This is subtext")
//Small Icon for your notificatiom
notificationCompatBuilder.setSmallIcon(R.id.icon)
//Large Icon for your notification
notificationCompatBuilder.setLargeIcon( BitmapFactory.decodeResource(getResources(),R.id.icon))
notificationManager.notify( NOTIFICATION_ID,notificationCompatBuilder.build())
通过这个通知,它将成为在第一步创建的通知渠道的一部分,并且其行为现在将与渠道设置相关。