4

There seem to be several other questions related to this topic, but each one I've found has a solution that either doesn't use notifications or doesn't work on recent Android versions. The reason I want to use notifications is to ensure the volume for the sound corresponds to the user's notification volume.

Q: How can I play the default notification sound, that doesn't display anything to the user, and responds to the notification volume level?

One solution, which used to work, was to build a notification but leave off the icon, title, and content. This worked on older Android versions (with an error in the log E/NotificationService: WARNING: In a future release this will crash the app:), but is no longer an option.

Other solutions use MediaPlayer or RingTone, but these have the down-side of different user volume controls which mean the sound level won't match that of displayed notifications. In other words, if the user has their media and ring volume set very low, then these approaches may not be heard.

Some similar questions that don't solve this:

Play notification default sound only (Android)

Android Notification to play sound only

Android Marshmallow sound only Notification?

How to play an android notification sound

This plays the right sound, but not at the notification volume:

Uri uriSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
try {
    RingtoneManager.getRingtone(getApplicationContext(), uriSound).play();
} catch (Exception e) {
    e.printStackTrace();
}

This is a sound-only notification, but only worked (contrary to documentation) on older Android versions:

Notification notification = new NotificationCompat.Builder(this, "channel_id")
    .setDefaults(NotificationCompat.DEFAULT_SOUND)
    .build();

An example of this working as I desire is Google's Android Messages app. When the app is open to a conversation thread and a new message is received, the notification sound is played and the sound correctly responds to the notification volume level.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Steve
  • 101
  • 5
  • https://developer.android.com/reference/android/media/MediaPlayer.html#setAudioStreamType(int) with `STREAM_NOTIFICATION` should work. – CommonsWare Jan 15 '18 at 14:52
  • Following that link, it appears the method is depreciated. The new method seems to make use of `AudioAttributes`. I'll look into that and report back if I can get it to work. Thanks for the input. – Steve Jan 16 '18 at 01:54

0 Answers0