如果您想要在创建通知渠道时,默认情况下发送声音或震动通知,请将以下代码添加到通知渠道构建器中:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(channelDescription);
channel.enableLights(true);
channel.setLightColor(Color.RED);
channel.enableVibration(true);
channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), attributes);
mNotificationManager.createNotificationChannel(channel);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
mNotificationManager.notify(notificationId, builder.build());
}
这将允许您使用默认的通知设置,并在 Android SDK 版本号为O或更高版本时启用声音和震动通知。