Уведомление setSound (), кажется, на самом деле не устанавливает звук - PullRequest
0 голосов
/ 03 декабря 2018

Я недавно начал кодировать свой первый проект для Android, включая уведомления (SDK 21 - Android 5)

В настоящее время у меня есть маленькая маленькая кнопка, которая при нажатии создает уведомление и отправляет его в само приложение.Звучит глупо, но цель состоит в том, чтобы проверить, используется ли пользовательский шаблон звука и вибрации.

Это уведомление, которое создается при нажатии:

Notification note = new Notification.Builder(this.requireContext(), "channel_id")
        .setSmallIcon(R.mipmap.icon)
        .setContentTitle("Title")
        .setContentText("Text")
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setCategory(NotificationCompat.CATEGORY_MESSAGE)
        .setVibrate(new long[] {500, 500, 500, 500, 500})
        .setSound(SettingsHandler.getRingtoneUri(this.requireContext())
        .setContentIntent(anyIntent)
        .setAutoCancel(true)
        .build();

SettingsHandler - вспомогательный классЯ создал для обработки настроек.Например, включить или выключить вибрацию или выбрать мелодию звонка.getRingtoneUri() выполняет следующие действия:

public synchronized static Uri getRingtoneUri(Context context) {
    SharedPreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
    return Uri.parse(prefs.getString("ringtone_uri_key", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString()));
}

При отладке этого результата результат getRingtoneUri выглядит как "content://media/internal/audio/media/31".Это выглядит актуально для меня.Однако в более поздней строке свойство звука созданного уведомления по-прежнему равно нулю.Эми, что я делаю не так?Спасибо вперед.

1 Ответ

0 голосов
/ 03 декабря 2018

попробуйте это:

   Uri alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/raw/ding");
       NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getString(R.string.checkout_channel));
                mBuilder.setContentTitle(context.getString(R.string.passenger_name)).setContentText(context.getString(R.string.pit, name)).setSmallIcon(R.drawable.notification_icon).setSound(alarmSound);
                Notification notification = mBuilder.build();
                notification.flags |= Notification.FLAG_AUTO_CANCEL;


                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                String channelDescription = "Checkout Channel";
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    AudioAttributes audioAttributes = new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_ALARM)
                            .build();

                    NotificationChannel notificationChannel = new NotificationChannel(context.getString(R.string.checkout_channel),
                            channelDescription, notifManager.IMPORTANCE_HIGH);
                    notificationChannel.enableLights(true);
                    notificationChannel.setLightColor(Color.GREEN);
                    notificationChannel.setShowBadge(true);
                    notificationChannel.setSound(alarmSound, audioAttributes);
                    notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                    notificationManager.createNotificationChannel(notificationChannel);
                }
                notificationManager.notify(iUniqueId, notification);

Вам необходимо установить атрибуты audio и создать свой канал уведомлений.Это работает для меня для всех Android от 4,2 до 9

...