最近项目中涉及到了音量监听然后作出改变的需求,特此mark一下
想监听音量的变化通用的就两种方法:
1、监听音量键的变化
方法: 重写 activity onKeyDown函数
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
//音量键up
return false;
case KeyEvent.KEYCODE_VOLUME_DOWN:
//音量键down
return false;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
复制代码
优点: 快速,方便,简单
缺点:
1. 容易消耗音量键改变事件(返回false有时也没用),实测
2. 该监听针对当前Activity,不同的Ac要重新重写onKeyDown函数
3. 由第二点可知,无法做到整个应用范围监听
2、获取音量变化的广播
系统音量变化的时候会发送广播,监听这个就行,音量变化的action是
android.media.VOLUME_CHANGED_ACTION
具体的见代码:(kotlin版本)
class VolumeChangeHelper(var context: Context){
private var mVolumeBroadCastReceiver: VolumeBroadCastReceiver? = null
private var mVolumeChangeListener: VolumeChangeListener? = null
companion object{
const val VOLUME_CHANGE_ACTION = "android.media.VOLUME_CHANGED_ACTION"
const val EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE"
}
private var audioManager: AudioManager? = context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager
fun registerVolumeChangeListener(volumeChangeListener: VolumeChangeListener){
mVolumeChangeListener = volumeChangeListener
mVolumeBroadCastReceiver = VolumeBroadCastReceiver()
val filter = IntentFilter()
filter.addAction(VOLUME_CHANGE_ACTION)
if(mVolumeBroadCastReceiver != null){
//注册这个广播
context.registerReceiver(mVolumeBroadCastReceiver!!, filter)
}
}
fun unregisterReceiver(){
if(mVolumeBroadCastReceiver != null){
context.unregisterReceiver(mVolumeBroadCastReceiver!!)
mVolumeBroadCastReceiver = null
}
}
interface VolumeChangeListener{
fun onVolumeDownToMin()
fun onVolumeUp()
}
//定义一个想监听音量变化的广播接受者
inner class VolumeBroadCastReceiver : BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
if(intent?.action == VOLUME_CHANGE_ACTION && intent?.getIntExtra(EXTRA_VOLUME_STREAM_TYPE, -1) == AudioManager.STREAM_MUSIC){
val currentVolume = audioManager?.getStreamVolume(AudioManager.STREAM_MUSIC) ?: -1
if(currentVolume > 0){
mVolumeChangeListener?.onVolumeUp()
} else if( currentVolume == 0){
mVolumeChangeListener?.onVolumeDownToMin()
}
}
}
}
}
复制代码
想实现全局监听的话,可以在在一个app生命周期内都存在的Context里去监听,比如MainActivity