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

Я сталкиваюсь с некоторой Уведомлением , связанным с проблемой только в Oreo версии.Я перехожу по этой ссылке и успешно получаю собственный звук после удаления / установки приложения, как он предложил.

Теперь проблема в том, что я хочу использовать два пользовательских звука в своем приложении. Для этогоУ меня есть такой код:

private void sendNotification(NotificationBean notificationBean) {
    String textTitle = notificationBean.getTitle();
    String alert = notificationBean.getMessage().getAlert();
    int orderId = notificationBean.getMessage().getOrderId();
    String notificationType = notificationBean.getMessage().getNotificationType();
    String sound = notificationBean.getMessage().getSound();

    Intent intent = new Intent(this, NavigationDrawerActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri soundUri;

    if (notificationType.equals("Pending"))
        soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.sound);
    else
        soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.app_name))
            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle(textTitle)
            .setContentText(alert)
            .setSound(soundUri)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.app_name);
        String description = getString(R.string.app_name);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;

        NotificationChannel channel = new NotificationChannel(getString(R.string.app_name), name, importance);
        channel.setDescription(description);

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

        channel.enableLights(true);
        channel.enableVibration(true);
        channel.setSound(soundUri, attributes);

        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    // notificationId is a unique int for each notification that you must define
    notificationManager.notify(101, mBuilder.build());
}

Если я получу notificationType = "Pending", тогда я хочу использовать пользовательский звук, в противном случае DEFAULT звук, но здесь Он воспроизводит тот звук, который воспроизводится впервые (Когда я получаюуведомление впервые.).

Эта проблема возникает только в OREO.Во всех других устройствах он работает нормально.

Любая помощь?Ваша помощь будет оценена.

Ответы [ 2 ]

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

Я получил подсказку, чтобы решить мою проблему из ответа @Mehul Joisar.

Как он писал:

Либо вы должны создать отдельный канал, либо вы должны удалить свой собственный канал.

Я создал два отдельных канала дляразные звуки.

Как я думаю, мы не можем изменить настройки канала уведомлений после того, как мы создали канал.Мы должны удалить и создать новые, иначе мы должны создать отдельные каналы для разных настроек.

Здесь я делюсь полным кодом, чтобы помочь другим.

private void sendNotification(NotificationBean notificationBean) {
    String textTitle = notificationBean.getTitle();
    String alert = notificationBean.getMessage().getAlert();
    int orderId = notificationBean.getMessage().getOrderId();
    String notificationType = notificationBean.getMessage().getNotificationType();

    Intent intent = new Intent(this, NavigationDrawerActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Uri soundUri;
    String channelName;

    if (notificationType.equals("Pending")) {
        channelName = getString(R.string.str_chef);
        soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.sound);
    }
    else {
        channelName = getString(R.string.str_customer);
        soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channelName)
            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle(textTitle)
            .setContentText(alert)
            .setSound(soundUri)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.app_name);
        String description = getString(R.string.app_name);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;

        NotificationChannel channel = new NotificationChannel(channelName, name, importance);
        channel.setDescription(description);

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

        channel.enableLights(true);
        channel.enableVibration(true);
        channel.setSound(soundUri, attributes);

        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    // notificationId is a unique int for each notification that you must define
    notificationManager.notify(101, mBuilder.build());
}

ПРИМЕЧАНИЕ. Сначала необходимо удалить приложение, а затем протестировать его с помощью этого кода.

Спасибо.

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

Проблема:
Кажется, проблема канала уведомлений.

Решение: Либо вы должны создать отдельный канал, либо вы должны удалить свой собственный канал.

Стратегия: 1) Создать отдельный канал: Вы можете выбрать эту стратегию, если хотите сохранить несколько каналов вместе с различными конфигурациями для вашего приложения.Чтобы создать отдельный канал, просто укажите уникальный идентификатор канала при его создании.т.е.:

NotificationChannel channel = new NotificationChannel(uniqueChannelId, name, importance);

2) Удалите существующий канал и заново создайте его: Вы можете выбрать эту стратегию, если хотите сохранить только один канал вместе с обновленной конфигурацией для вашего приложения.

Чтобы удалить собственный канал и создать его заново, может работать нормально следующее:

NotificationManager mNotificationManager = getSystemService(NotificationManager.class);

NotificationChannel existingChannel = notificationManager.getNotificationChannel(channelId);

//it will delete existing channel if it exists
if (existingChannel != null) {
mNotificationManager.deleteNotificationChannel(notificationChannel);
}
//then your code to create channel
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
...