1. 程式人生 > >android 音量獲取和設定總結

android 音量獲取和設定總結

1、獲取音量值:

AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

其中AudioManager.STREAM_MUSIC代表媒體音量,也可以替換成其他的型別,獲取其他型別音量。

2、設定音量值:

例如我把媒體音量設定為0(靜音)

audioManager.setStreamVolume(AudioManager.STREAM_MUSIC

, 0, AudioManager.FLAG_PLAY_SOUND);

3、監聽音量鍵被按下:

在activity重寫onKeyDown方法

public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d(TAG, "onKeyDown" + keyCode + "" + (keyCode == KeyEvent.KEYCODE_VOLUME_UP));
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {

    // 音量+鍵

   }

   if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN

){

   // 音量-鍵

    }

}

4、監聽音量變化:

上面通過監聽按鍵來監聽調整音量的方法,不是很靠譜,因為可能使用者在設定裡調整音量,所以用下面方式監聽音量變化

private void registerVolumeChangeReceiver() {
mSettingsContentObserver = new SettingsContentObserver(mContext, new Handler());
mContext.getContentResolver()
.registerContentObserver(android.provider.Settings.System.CONTENT_URI

, true, mSettingsContentObserver);
}

private void unregisterVolumeChangeReceiver() {
mContext.getContentResolver().unregisterContentObserver(mSettingsContentObserver);
}

public class SettingsContentObserver extends ContentObserver {
Context context;

public SettingsContentObserver(Context c, Handler handler) {
super(handler);
context = c;
}

@Override
public boolean deliverSelfNotifications() {
return super.deliverSelfNotifications();
}

@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.d(TAG, "音量:" + currentVolume);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND);
}
}

5、監聽震動模式變化

public boolean isMuteMode() {
AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
return am.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
}

public boolean isVibrateMode() {
AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
return am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;
}

public boolean isNormalMode() {
AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
return am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
}

private void registerRingerModeReceiver() {
mRingerModeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
// 監聽到震動/靜音/響鈴的模式變化

                  if( isMuteMode()){

                 }
}
}
};
IntentFilter filter = new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
mContext.registerReceiver(mRingerModeReceiver, filter);
}