How do I listen to an event volume buttons on android?

0

For example, let's say that in MainActivity.class I have a TextView that if we press the volume key + automatically in TextView will show a 1 and if we keep pressing the volume key + it will increase, the opposite will happen with the volume button -

    
asked by Cokóro R1 08.10.2018 в 06:15
source

1 answer

1

Try the following

 AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

//Obtenemos el click del boton de volumen + y -

    @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            int action = event.getAction();
            int keyCode = event.getKeyCode();
            int cont = 0;
            switch (keyCode) {
                case KeyEvent.KEYCODE_VOLUME_UP:
                    if (action == KeyEvent.ACTION_DOWN) {
                          cont++;
                         //si queres ajustar el volumen
                        //audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
                     textView.setText("Volumen: "+cont);
                    }
                    return true;
                case KeyEvent.KEYCODE_VOLUME_DOWN:
                    if (action == KeyEvent.ACTION_DOWN) {
                        cont--;
//audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);

                    textView.setText("Volumen: "+cont);
                    }
                    return true;
                default:
                    return super.dispatchKeyEvent(event);
            }
        }

With that we generate a whole variable that is counter, in this case cont.

When we press the volume up button we increase the counter and we pass it to TextView , when we lower the volume the opposite happens. Leave commented the lines that you can use to adjust the volume

    
answered by 08.10.2018 / 13:43
source