tarun
tarun

Reputation: 103

Detect event when hardware volume button is pressed in android

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.

Upvotes: 7

Views: 16838

Answers (3)

xxtesaxx
xxtesaxx

Reputation: 6419

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.

Upvotes: 0

Drake29a
Drake29a

Reputation: 896

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);
    }
};

Upvotes: -1

NehaK
NehaK

Reputation: 2727

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?

Upvotes: 16

Related Questions