Sjk
Sjk

Reputation: 387

Capture Power Key press in android?

I need to capture power key press in android . I tried the following

      @Override
   public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(KeyEvent.KEYCODE_POWER == event.getKeyCode()){
              //some operations
          }
    return super.onKeyDown(keyCode, event);
    }

But using this code on pressing Power Key control not getting into onKeyDown method.

On a long press of power key , this method gets called.But what i need i on single pressing i need to capture this event

Can anyone help?

Upvotes: 1

Views: 10287

Answers (2)

Paul
Paul

Reputation: 5974

Plenty of threads on this, you have to add permission.

<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />

How to hook into the Power button in Android?

Upvotes: 2

Juan Cort&#233;s
Juan Cort&#233;s

Reputation: 21112

You are probably missing the permission in the manifest that allows your application to override the default behaviour for the power key, it is also important to return something if you've handled the event to prevent the default behaviour.

<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />

There's further discussion here

So your code would be:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(KeyEvent.KEYCODE_POWER == event.getKeyCode()){
              return true;//If event is handled, falseif 
        }
        return super.onKeyDown(keyCode, event);
    }

If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

Upvotes: 1

Related Questions