每日日记- Android 在fragment 监听系统音量,当不好取到上游的Activity,比如组件化了。

这边是helper 代码

package com.chase.shortvideo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.ContentObserver
import android.media.AudioManager
import android.os.Handler

/**
 * 系统音量监听
 *
 * @property context
 * @property listener 自定义listener
 */
class SystemVolumeChangeHelper(val 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()
                }
            }
        }

    }


}

只需要在fragmernt里面注册。并且实现,会有监听音量的接口方法抛出。很实用

你可能感兴趣的:(android)