Zelig
Zelig

Reputation: 1808

Setting notification sound volume

I am using a NotificationChannel to define my app's notification. I set it's sound with the following code :

AudioAttributes.Builder constructeurAttributsAudio=new AudioAttributes.Builder();
constructeurAttributsAudio.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT);
canalNotification.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE    + "://" + contexte.getPackageName() + "/raw/cloche"),constructeurAttributsAudio.build());

When the notification appears, the sound is correctly emitted, but it's volume is set at the maximum and doesn't take into account the sound level set for notifications by the user. Does anyone know how I can have my app set the notification sound level to the value choosen by the user?

Edit #1 : if I copy the code to execute it in the app's body (triggered by a Button click) instead of in the onReceive method of my BroadcastReceiver, the notification sound is correctly emitted at the sound level chosen by the user for notifications.

Edit #2 : strangely, the notification sound level is correct when the app is executed on the emulator! Could the reason be a parameter in the phone's configuration? (They both run under Android 9).

Upvotes: 0

Views: 1263

Answers (3)

Chocos
Chocos

Reputation: 3

Had this same issue. Realised it was because I wasn't using the correct context to call getSystemService

Here is how I checked to see if I was getting the correct volume:

val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager
Log.d("log", "volume: ${audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION)}"

It worked correctly after removing this and using applicationContext

Upvotes: 0

Zelig
Zelig

Reputation: 1808

Uninstalling and reinstalling the app solved the problem!

Upvotes: 1

mehdi musavi
mehdi musavi

Reputation: 443

I use the following code, hopefully useful for you too:

 private void setvolume(int volume)
 {
AudioManager manager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
manager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);

Uri notification = RingtoneManager
        .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

MediaPlayer player = MediaPlayer.create(getApplicationContext(), notification);
player.start();

}

Upvotes: 0

Related Questions