How can I manage audio volumes sanely in my Android app?

后端 未结 5 863
生来不讨喜
生来不讨喜 2020-11-28 03:33

I have an app that plays intermittent sounds while its activity is open, and the user is always expecting it to make these noises, but unfortunately it is constrained by the

相关标签:
5条回答
  • 2020-11-28 03:55

    If you are using the 'OnKeyDown' method, you can get around this issue by doing the following:

    public boolean onKeyDown(int keyCode, KeyEvent event) {    
    if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    setVolumeControlStream(AudioManager.STREAM_MUSIC);}}
    
    0 讨论(0)
  • 2020-11-28 03:59
       var audioManager:AudioManager?=null
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            registerReceiver(mVolumeReceiver, IntentFilter("android.media.VOLUME_CHANGED_ACTION"))
            audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
        }
    
        private var mVolumeReceiver: BroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
    
                if (intent.action == "android.media.VOLUME_CHANGED_ACTION") {
                    var currentVolume = audioManager?.getStreamVolume(AudioManager.STREAM_MUSIC)
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-28 04:02

    Got another suggestion via Google Groups that is the platform integrated solution I was looking for and works fine:

    Please don't handle the volume keys yourself - it is almost impossible to guarantee that you won't break the behavior of the volume keys.

    Call this API in your onCreate():

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    This tells the AudioManager that when your application has focus, the volume keys should adjust music volume.

    0 讨论(0)
  • 2020-11-28 04:12

    It is usefull of this API: setVolumeControlStream(AudioManager.STREAM_MUSIC);

    Unless this I will spend more time to fix that volume bug.

    0 讨论(0)
  • 2020-11-28 04:14

    This won't help you if you have override onKeyDown(int keycode,KeyEvent event) method of an activity.

    0 讨论(0)
提交回复
热议问题