Android實現監聽音量的變化

本文實例為大傢分享瞭Android實現監聽音量變化的具體代碼,供大傢參考,具體內容如下

最近項目中涉及到瞭音量監聽然後作出改變的需求,特此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

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: