(1)apk通过,dispatchKeyEvent()函数监测按键事件:
//apk onCreate()初始化mAudioManager:
mAudioManager = (AudioManager) this.getSystemService(this.AUDIO_SERVICE);
apk接收到按键事件,执行如下处理,调用AudioManager对象函数处理:
@Override
public boolean dispatchKeyEvent(@NonNull KeyEvent keyEvent){
final int keyCode = keyEvent.getKeyCode();
switch(keyCode){
case KeyEvent.KEYCODE_VOLUME_UP:
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
mAudioManager.adjustVolume(AudioManager.ADJUST_RAISE ,0);
}
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
mAudioManager.adjustVolume(AudioManager.ADJUST_LOWER ,0);
}
break;
}
return true;
}
(2)AudioManager对象类文件:
文件路径:
frameworks/base/media/java/android/media/AudioManager.java
AudioManager类,音量调节函数:
public void adjustVolume(int direction, int flags) {
MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
helper.sendAdjustVolumeBy(USE_DEFAULT_STREAM_TYPE, direction, flags);
}
apk通过监测按键事件,再调用AudioManager函数接口,调节STREAM_MUSIC流音量调节。