Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set notification sound volume programmatically?

I have this method in my main activity

private void beep()
{
    AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    manager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0,
            AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_PLAY_SOUND);
    Uri notification = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
            notification);
    r.play();
}

As I understand, notification sound volume should be regulated by STREAM_NOTIFICATION. But notification always plays with the same volume despite that volume number in setStreamVolume method. Why is that?

like image 972
Vitalii Korsakov Avatar asked Jul 02 '12 21:07

Vitalii Korsakov


2 Answers

I went another way. It's not exactly answer to my question but appropriate one. When I play notification in STREAM_MUSIC everything is fine. So notification plays exactly with volume I pass as parameter to the function

private void beep(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();
}
like image 77
Vitalii Korsakov Avatar answered Oct 08 '22 15:10

Vitalii Korsakov


First of all, I hope you realize that you are attempting to play two notifications right after each other, so there might be a conflict about that. AudioManager.FLAG_PLAY_SOUND and r.play() will both try playing the sound. It is usually enough to give user one type of information, either by UI or by playing the beep with new volume. I suggest you delete one of the flags. If you don't need any, just give it 0.

Coming to the main question, I am not sure if you can set volume level to 0. Try putting 1, like

manager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 1, AudioManager.FLAG_SHOW_UI);

If you want to mute the notification, try using setStreamMute, which is equivalent to setting the volume to 0.

like image 26
Erol Avatar answered Oct 08 '22 15:10

Erol