Пользовательский звук уведомления не работает в NotificationChannel для Android P

У меня есть собственный звук уведомления, но когда устройство принимает уведомление, поэтому устройство не молчит, звук уведомления не работает. Устройство воспроизводит звук по умолчанию.

NotificationChannel mChannel = new NotificationChannel(MISSED_CALL, "missedCall", NotificationManager.IMPORTANCE_HIGH);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mChannel.setShowBadge(true);
mChannel.enableLights(true);
mChannel.enableVibration(true);

Uri soundUri = Uri.parse("android.resource://" + Util.getPackageName(context) + "/" + R.raw.missed_notification);
AudioAttributes audioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build();
mChannel.setSound(soundUri, audioAttributes);
mChannel.setLightColor(Color.BLUE);
notificationManager.createNotificationChannel(mChannel);

builder.setChannelId(MISSED_CALL)
.setContentIntent(pendingIntent)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setNumber(totalNotificationCount);

NotificationCompat.BigTextStyle notification = new NotificationCompat.BigTextStyle().bigText("");
notification.setBuilder(builder);
notificationManager.notify(MISSED_CALL_NOTIFICATION_ID, 
builder.build());

person propoLis    schedule 24.09.2019    source источник


Ответы (2)


Я запустил сервис и медиаплеер. Он работает.

public class NotificationSoundService extends Service {

        private MediaPlayer mMediaPlayer;
        public static final String ACTION_START_PLAYBACK = "start_playback";
        public static final String ACTION_STOP_PLAYBACK = "stop_playback";
        public static final String EXTRA_SOUND_URI = "soundUri";

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        public int onStartCommand(Intent intent, int flags, int startId) {

            if (intent == null || intent.getAction() == null) {
                return START_NOT_STICKY;
            }

            String action = intent.getAction();
            switch (action) {
                case ACTION_START_PLAYBACK:
                    startSound(intent.getStringExtra(EXTRA_SOUND_URI));
                    break;
                case ACTION_STOP_PLAYBACK:
                    stopSound();
                    break;
            }

            return START_NOT_STICKY;
        }

        private void startSound(String uriString) {

            Uri soundUri;
            try {
                soundUri = Uri.parse(uriString);

                // play sound
                if (mMediaPlayer == null) {
                    mMediaPlayer = new MediaPlayer();

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

                        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                                .build();

                        mMediaPlayer.setAudioAttributes(audioAttributes);
                    } else {
                        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
                    }

                    mMediaPlayer.setOnPreparedListener(MediaPlayer::start);
                    mMediaPlayer.setOnCompletionListener(mediaPlayer -> stopSound());
                }

                mMediaPlayer.setDataSource(this, soundUri);
                mMediaPlayer.prepareAsync();

            } catch (Exception e) {
                stopSound();
            }
        }

        private void stopSound() {
            if (mMediaPlayer != null) {
                mMediaPlayer.stop();
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
            cleanup();
        }

        private void cleanup() {
            stopSelf();
        }

Когда придет уведомление, запустите службу.

getNotification(){

  Intent intent = new Intent(mContext, NotificationSoundService.class);
  intent.setAction(NotificationSoundService.ACTION_START_PLAYBACK);
  intent.putExtra(EXTRA_SOUND_URI, "" + soundUri);
  mContext.startService(intent);

  builder.setChannelId(MISSED_CALL)
         .setContentIntent(pendingIntent)
         .setSound(null)
         .setCategory(NotificationCompat.CATEGORY_CALL)
         .setNumber(totalNotificationCount);
}
person propoLis    schedule 25.09.2019
comment
как вы используете это с уведомлением? - person arao6; 29.11.2019
comment
я добавил свой ответ - person propoLis; 05.12.2019
comment
Я думаю, вы немного создали велосипед. Надо дунуть, чтобы найти причину отсутствия звука - person AlexS; 12.12.2019

R.raw. missed_notification – целочисленный идентификатор ресурса; вам нужно имя звукового ресурса в этом Uri. Так что попробуйте:

Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
            + "://" + getPackageName() + "/raw/missed_notification");
    notification.setSound(soundUri, audioAttributes);
person Anas Mehar    schedule 24.09.2019
comment
@propoLis Попробуйте поместить пропущенное_уведомление во внутренний каталог и получить пропуск - person Anas Mehar; 24.09.2019
comment
Это тоже не работает, я ошибаюсь в застройщике? - person propoLis; 24.09.2019
comment
Создатель @propoLis кажется подходящим для получения дополнительной информации, проверьте эту ссылку .com/questions/51029659/ - person Anas Mehar; 24.09.2019
comment
То же самое, но не работало только над 8.0 - person propoLis; 24.09.2019
comment
@propoLis позвольте мне проверить - person Anas Mehar; 24.09.2019