简体   繁体   中英

Android Custom Notification sound is Not working?

I am getting the custom sound name from the notification and added conditions based on key but always sound only playing in my notification.

I want to play different sounds based on sound keys and how to handle anyone have ideas to help the same.

         
          if (playOrderAssignmentTone) {
              if(key.equalsIgnoreCase("sound")){
                  alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.sound);
              } else {
                  alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.sound2);
              }

          } else {
              alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
          }
      } catch (Exception e) {
          LoggerUtility.PrintTrace(e);
          FirebaseCrashlytics.getInstance().log(e.getMessage());
          FirebaseCrashlytics.getInstance().recordException(e);
          alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      } 

Notification Builder

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ONE_ID)
              .setSmallIcon(R.drawable.notification_icon)
              .setContentTitle(notificationTitle)
              .setContentText(notificationBody)

              //Optional fields
              .setPriority(NotificationCompat.PRIORITY_MAX)
              .setCategory(NotificationCompat.CATEGORY_STATUS)
              .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
              .setTicker(notificationTicker)
              .setContentIntent(pendingIntent)
              .setAutoCancel(true)
              .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
              .setWhen(System.currentTimeMillis())
              //.setSound(alarmSound)
              //.setShowWhen(true)
              .setOngoing(isOngoing);

// Setting notification sound based on channel id
if (!CHANNEL_ONE_ID.equalsIgnoreCase("auto")) {
          notificationBuilder.setSound(alarmSound);
      }

So the issue with your code is you need to make separate notification channels for different sounds to work. Above is the code to attach a sound to the notification channel.

    private void createNotificationChannel() {

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

            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);

            Uri audio = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + File.pathSeparator + File.separator
                    + File.separator + getApplicationContext().getPackageName() + File.separator + R.raw.notification);

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

            channel.setSound(audio, attributes);

            NotificationManager notificationManager = getSystemService(NotificationManager.class);

            if (notificationManager != null) {

                notificationManager.createNotificationChannel(channel);

            }
        }
    }

So when you want to play some specific sound with a notification use that notification CHANNEL_ID with the notification builder.

You have to call setSound() method on NotificationChannel instance.

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

val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH).apply {
setSound(soundUri, audioAttributes)
}

select notification tone from your mobile:

  Uri ringtone=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);;
                    Intent intent=new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, ringtone);
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, ringtone);
                    ((Activity) getContext()).startActivityForResult(intent , 1);

get ringtone path in onActivity result:

 if (resultCode == MainActivity.RESULT_OK && requestCode == 1) {
   uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
 path = uri.toString();
}

saving this path in sqlite database and retrive from in service when you trigger your notification play this sound just once:

Uri uri;
 uri = Uri.parse(myDb.alarmGetRingtone(requestcode));
  r = RingtoneManager.getRingtone(getApplicationContext(), uri);
 r.play();

I Hope This Code Will Help You
Thank You

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM