(1)apk通过,dispatchKeyEvent()函数监测按键事件:
//apk onCreate()初始化mAudioManager,假定mediaPlayer使用STREAM_ALARM流:
mAudioManager = (AudioManager) this.getSystemService(this.AUDIO_SERVICE);
apk接收到按键事件,执行如下处理:
@Override
public boolean dispatchKeyEvent(@NonNull KeyEvent keyEvent){
final int keyCode = keyEvent.getKeyCode();
switch(keyCode){
case KeyEvent.KEYCODE_VOLUME_UP:
// 按下vom+按键,调高音量
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
mAudioManager.adjustStreamVolume(AudioManager.STREAM_ALARM,AudioManager.ADJUST_RAISE ,0);
}
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:
// 按下vom-按键,调低音量
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
mAudioManager.adjustStreamVolume(AudioManager.STREAM_ALARM,AudioManager.ADJUST_LOWER ,0);
}
break;
}
return true;
}
(2)AudioManager对象类文件:
文件路径:
frameworks/base/media/java/android/media/AudioManager.java
AudioManager类,音量调节函数:
public void adjustStreamVolume(int streamType, int direction, int flags) {
final IAudioService service = getService();
try {
service.adjustStreamVolume(streamType, direction, flags, getContext().getOpPackageName());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
apk通过监测按键事件,再调用AudioManager函数接口,变更音频流音量。