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.