How to set notification sound volume programmatically?

Vitalii Korsakov picture Vitalii Korsakov · Jul 2, 2012 · Viewed 18.8k times · Source

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?

Answer

Vitalii Korsakov picture Vitalii Korsakov · Jul 4, 2012

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