将通知声音设置为默认闹钟铃声
Set Notification sound as default alarm ringtone
我发现,如果我将通知声音设置为设备默认闹钟铃声,如下所示:
val alarmTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
val builder = NotificationCompat.Builder(
context,
CHANNEL_ID
)
builder.setDefaults(Notification.DEFAULT_VIBRATE or Notification.DEFAULT_LIGHTS)
builder.priority = NotificationCompat.PRIORITY_DEFAULT
builder.setSound(alarmTone)
这适用于几乎所有较旧的设备版本,但只要我在 Android 8.0
设备上测试它,它就会将声音设置为默认通知声音。如何获取设备 8.0 的默认闹钟铃声?
Oreo 8.0之后您可能已经创建了播放通知音的通道。
private static void initChannels(NotificationManager notificationManager) {
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationChannel channel = new NotificationChannel("ID",
"NAME",
NotificationManager.IMPORTANCE_LOW);
channel.setDescription("DESC");
channel.enableVibration(false);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
channel.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification), audioAttributes);
notificationManager.createNotificationChannel(channel);
}
确保您使用的是 targetSdkVersion 26 或更高版本
我发现,如果我将通知声音设置为设备默认闹钟铃声,如下所示:
val alarmTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
val builder = NotificationCompat.Builder(
context,
CHANNEL_ID
)
builder.setDefaults(Notification.DEFAULT_VIBRATE or Notification.DEFAULT_LIGHTS)
builder.priority = NotificationCompat.PRIORITY_DEFAULT
builder.setSound(alarmTone)
这适用于几乎所有较旧的设备版本,但只要我在 Android 8.0
设备上测试它,它就会将声音设置为默认通知声音。如何获取设备 8.0 的默认闹钟铃声?
Oreo 8.0之后您可能已经创建了播放通知音的通道。
private static void initChannels(NotificationManager notificationManager) {
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationChannel channel = new NotificationChannel("ID",
"NAME",
NotificationManager.IMPORTANCE_LOW);
channel.setDescription("DESC");
channel.enableVibration(false);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
channel.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification), audioAttributes);
notificationManager.createNotificationChannel(channel);
}
确保您使用的是 targetSdkVersion 26 或更高版本