Oreo + уведомления о проблеме звука - PullRequest
0 голосов
/ 17 октября 2018

Я пытаюсь установить собственный звук для уведомлений.Проблема в том, что всегда воспроизводит первый звук в папке res / raw , независимо от того, сколько там файлов или сколько я пытаюсь изменить URI.Если я удаляю все файлы из необработанной папки , звук не воспроизводится вообще .На Android 6 работает хорошо.

Я хотел бы иметь возможность установить звук из внешнего / внутреннего хранилища, а также системный звук.Возможно ли это?

Вот мой код:

notificationSoundUri = GeneralSettingsManager.getSoundForNotification(getApplicationContext(), site, pushType);
                mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
                Intent notificationIntent = new Intent(this, Splash.class);
                notificationIntent.setAction(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
                int smallIcon = R.drawable.big_green_v;
                int backgroundColor = 0x8D1919;
                String channelId = "default2";
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(this, channelId)
                                .setSmallIcon(smallIcon)
                                .setColor(backgroundColor)
                                .setContentTitle(title)
                                .setContentText(message)
                                .setAutoCancel(true)
                                .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                                .setDefaults(Notification.DEFAULT_VIBRATE);


                if(TextUtils.isEmpty(notificationSoundUri))
                {
                    Timber.e("NOTIFICATION SOUND * MISSING");
                    mBuilder.setVibrate(new long[]{0L});
                }
                else
                {
                    Timber.e("NOTIFICATION SOUND * " + notificationSoundUri);
                    mBuilder.setSound(Uri.parse(notificationSoundUri));
                }

                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

                    if(!TextUtils.isEmpty(notificationSoundUri))
                    {
                        // Create an Audio Attribute
                        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                                .build();

                        //remove old channel
                        try {
                            mNotificationManager.deleteNotificationChannel(channelId);
                        }
                        catch (Exception e)
                        {
                            //do nothing
                        }


                        // Create new channel
                        NotificationChannel notificationChannel = new NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT);
                        notificationChannel.setSound(Uri.parse(notificationSoundUri), audioAttributes);
                      mNotificationManager.createNotificationChannel(notificationChannel);
                    }
                }

                PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                mBuilder.setContentIntent(contentIntent);

                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

РЕДАКТИРОВАТЬ: приведенный выше код от FirebaseMessagingService.Пользователь выберет нужный звук для уведомления из внешнего хранилища или из списка системных звуков, и этот звук должен воспроизводиться при отображении уведомления.

1 Ответ

0 голосов
/ 17 октября 2018

Да, Вы можете!Вы должны использовать RingtoneManager (для системного звука),

Uri ringSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.sound = ringSound;

Для внешнего / внутреннего вам нужно найти URI для конкретного звукового файла.

Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, 
RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
this.startActivityForResult(intent, 2);

Обрабатывать ответ

 @Override
 protected void onActivityResult(final int requestCode, final int resultCode, 
 final Intent intent)
 {
   if (resultCode == Activity.RESULT_OK && requestCode == 2)
   {
      Uri uri = Intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);

      if (uri != null)
      {
          this.chosenRingtone = uri.toString();
      }
      else
      {
          this.chosenRingtone = null;
      }
  }            

}

...