2017-08-09 52 views
1

我想讓我的android應用程序檢查設備的音量(媒體,不是鈴聲)低於'x'百分比,但我不確定如何。我目前正在此:如何在Android上以百分比獲取設備音頻級別?

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

編輯:我想要的體積百分比,如10%/ 20%...

+0

[你如何在Android中獲取/設置媒體音量(不是鈴聲音量)?](https://stackoverflow.com/questions/4593552/how-do-you-get-set-media-volume -not-ringtone-volume-in-android) – Jonathan

回答

1
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將是你的百分比!

+1

我認爲你正在使用整數除法。它應該是'int currentVolumePercentage = 100.0 * currentVolume/maxVolume;' – user643011

+1

@ user643011你是對的,編輯。 –

+1

評估訂單從左到右。所以雙常數應該在左邊。否則,當「損壞」已經完成時,您只是乘以整數除法結果。 https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html Upvote讚賞。 :-) – user643011