6

I am trying to get my android app to check if the device's volume (media, not ringer) is lower than 'x' percent, but I am unsure how. I am currently trying this:

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
int volume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
if (volume <0.7) {message};

Edit: I want the percentage of the volume, such as 10%/20%...

eddyb
  • 63
  • 1
  • 5
  • Possible duplicate of [How do you get/set media volume (not ringtone volume) in Android?](https://stackoverflow.com/questions/4593552/how-do-you-get-set-media-volume-not-ringtone-volume-in-android) – Jonathan Aug 09 '17 at 22:03

2 Answers2

9
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int currentVolumePercentage = 100 * currentVolume/maxVolume;   

currentVolumePercentage will be your percentage!

Nasir
  • 515
  • 5
  • 17
Trenton Telge
  • 478
  • 3
  • 17
  • 1
    I think you are using integer division by accident. It should be `int currentVolumePercentage = 100.0 * currentVolume/maxVolume;` – user643011 Aug 10 '17 at 00:48
  • 1
    Evaluation order is left to right. So the double constant should be on the left. Otherwise you are just multiplying the integer division result when the "damage" is already done. https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html Upvote appreciated. :-) – user643011 Aug 10 '17 at 00:57
5

Same Trenton Telge answer in kotlin function

fun getCurrentAudioLevelPercentage(context: Context): Int {
    val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
    val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
    val percentage = 100 * currentVolume / maxVolume
    return percentage
}
Manohar
  • 22,116
  • 9
  • 108
  • 144