Пользовательский звук уведомления, Android Oreo? - PullRequest
0 голосов
/ 25 июня 2018

Я хочу установить собственный звук уведомления из необработанного mp3 или wav-файла в моем приложении.Ниже мой код

private void sendMyNotification(String message) {
    Intent intent;
    if (sharedPreferences.getBoolean(SPConstants.IS_LOGGED_IN, false)) {
        intent = new Intent(this, ActivityNotification.class);
    } else {
        intent = new Intent(this, ActivitySplash.class);
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.panic);
    AudioManager manager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    manager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(soundUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
        notificationManager.createNotificationChannel(mChannel);
    }
    notificationManager.notify(0, notificationBuilder.build());
}

Аудио файл паники находится в res-> raw.Я пытался использовать как mp3, так и wav форматы звука, но, похоже, ничего не помогло установить звук уведомления.В настоящее время я тестирую на Pixel 2 OS 8.1.

Есть предложения, в чем может быть проблема?

Ответы [ 2 ]

0 голосов
/ 18 сентября 2018

Простой ответ:

Uri soundUri = Uri.parse(
                         "android.resource://" + 
                         getApplicationContext().getPackageName() +
                         "/" + 
                         R.raw.push_sound_file);

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

// Creating Channel
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
                                                      "YOUR_CHANNEL_NAME",
                                                      NotificationManager.IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);

((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                           .createNotificationChannel(notificationChannel);
0 голосов
/ 25 июня 2018
  • Протестировал ударный код и работал со мной, как и ожидалось.

  • Добавить контент намерения, и это все еще работает без каких-либо проблем со мной.

    private void sendMyNotification(String message) {
    
    Intent intent = new Intent(this, SplashActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    
    Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.correct_answer);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(soundUri)
            .setContentIntent(pendingIntent);
    
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    
        if(soundUri != null){
            // Changing Default mode of notification
            notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
            // Creating an Audio Attribute
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build();
    
            // Creating Channel
            NotificationChannel notificationChannel = new NotificationChannel("CH_ID","Testing_Audio",NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setSound(soundUri,audioAttributes);
            mNotificationManager.createNotificationChannel(notificationChannel);
        }
    }
    mNotificationManager.notify(0, notificationBuilder.build());
    }
    

Обновление

  • Вам может понадобиться удалить приложение, чтобы изменить настройки звука. Проверьте эти ссылку для более подробной информации.
...