7

i am developing an app which listen volume events whenever hardware volume button is pressed. app can be in foreground or background. i have followed [this] (Is there a broadcast action for volume changes?) but its not working correctly. following issues i am facing

1) If I press the volume button once - the event is triggered 4-6 times.
2) If current volume is maximum and i increase the volume then event doesn't fire..

Please help me.

Community
  • 1
  • 1
tarun
  • 103
  • 1
  • 1
  • 10

3 Answers3

16

Try to use following code -

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)){
        //Do something
    }
    return true;
}

for background - any way to detect volume key presses or volume changes with android service?

Community
  • 1
  • 1
NehaK
  • 2,639
  • 1
  • 15
  • 31
0

On a rooted device, you can use the Xposed framework to hook yourself into PhoneWindowManager. A good example is the Xposed Torch Module. Just decompile it and see how they do things.

xxtesaxx
  • 6,175
  • 2
  • 31
  • 50
-1

You can detect this by polling AudioManager for current volume, it's not nice solution, but i don't know better.

private Handler handler;
public int volume;

private Runnable volumeUpdater = new Runnable() {
    private int updatesInterval = 100;      
    @Override
    public void run() {
        if(volume != audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)){
            //volume changed put logic here
        }
        handler.postDelayed(volumeUpdater, updatesInterval);
    }
};
Drake29a
  • 896
  • 8
  • 23
  • In your app just call handler.post(volumeUpdater), and every 100ms loop will check if volume changed, so if it is different from the one saved, you know that user pressed volume button. You may have to change AudioManager.STREAM_MUSIC to STREAM_NOTIFICATION – Drake29a Jan 04 '16 at 14:24
  • If you find better solution I will be glad to hear about it. I would be happy to get rid of this from inherited code. – Drake29a Jan 05 '16 at 11:48
  • first issue is resolved , i am working on second. i will post my answer as soon as second is resolved – tarun Jan 06 '16 at 05:20