Home > Enterprise >  Android Custom Notification sound is Not working?
Android Custom Notification sound is Not working?

Time:06-07

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);
      }

CodePudding user response:

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.

CodePudding user response:

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)
}

CodePudding user response:

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

  • Related