(1)apk通过,dispatchKeyEvent()函数监测按键事件:
// APK onCreate()时,初始化音频流音量,假定mediaPlayer播放使用STREAM_ALARM流:
mAudioManager = (AudioManager) this.getSystemService(this.AUDIO_SERVICE);
// 取出对应流,音量Max,Min
mMaxVol = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
mminVol = mAudioManager.getStreamMinVolume(AudioManager.STREAM_ALARM);
apk接收到按键事件,执行如下处理,调用AudioManager对象函数处理:
@Override
public boolean dispatchKeyEvent(@NonNull KeyEvent keyEvent){
final int keyCode = keyEvent.getKeyCode();
// 取出音频流,当前音量
int vol = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);
switch(keyCode){
case KeyEvent.KEYCODE_VOLUME_UP:
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) { // 限制按键按下,进行音量调整
if( vol< mMaxVol ){
// setStreamVolume()进行音量设置
mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, ++vol,0 );
}
}
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) { // 限制按键按下,进行音量调整
if(vol> mminVol ){
// setStreamVolume()进行音量设置
mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, --vol,0 );
}
}
break;
}
return true;
}
(2)AudioManager对象类文件:
文件路径:
frameworks/base/media/java/android/media/AudioManager.java
AudioManager类,音量调节函数:
public void setStreamVolume(int streamType, int index, int flags) {
final IAudioService service = getService();
try {
service.setStreamVolume(streamType, index, flags, getContext().getOpPackageName());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
apk通过监测按键事件,再调用AudioManager函数接口就可以进行音量调节。