将通知声音设置为默认闹钟铃声

时间:2018-05-26 10:27:52

标签: android notifications alarm

我发现,如果我将通知声音设置为设备默认闹铃铃声,如下所示:

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的默认警报铃声?

1 个答案:

答案 0 :(得分:1)

8.0 Oreo之后您可能已经创建了播放通知声音的频道。

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或更高版本