1

I need to know when the user will press the power key continuously 2 or 3 times. But in the case the user is out of the application lets say on the home screen or even using any other application.

I getting the listener event of the power key on the activity but not on the service.

   @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(KeyEvent.KEYCODE_POWER == event.getKeyCode()){

        Log.e("POWER", "pow");
          return true;//If event is handled, falseif 

    }
    return super.onKeyDown(keyCode, event);
}

How can i know if the user has pressed the power button outside the activity?

WISHY
  • 11,067
  • 25
  • 105
  • 197
  • There is something else which works for me absolutely fine http://stackoverflow.com/questions/15609008/android-count-power-button-clicks-and-start-activity – WISHY Oct 24 '13 at 10:44

1 Answers1

3

You cannot override the power button press from your application. But when you press power button the screen turns on/off. So you can detect this using a broadcast receiver

<receiver android:name=".MyBroadCastReciever">
    <intent-filter>
        <action android:name="android.intent.action.SCREEN_OFF"/>
        <action android:name="android.intent.action.SCREEN_ON"/>
    </intent-filter>
</receiver>

and a broadcast receiver class

public class MyBroadCastReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            //Take count of the screen off position
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            //Take count of the screen on position
        }
    }
}

Hope this is helpful for you.

Anu
  • 1,884
  • 14
  • 30
  • How do i call the broadcast....I suppose I am missing some intent action here....I put log in the if-else part but dun seem to go froward – WISHY Oct 09 '13 at 06:51
  • No need to call broadcast receiver. Just write the class and define the receiver in manifest file(the first code). Now whenever the screen mode chenges the receiver will be triggered. – Anu Oct 09 '13 at 07:25
  • if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { //Take count of the screen off position Log.e("POWER", "off"); } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { //Take count of the screen on position Log.e("POWER", "on"); } – WISHY Oct 09 '13 at 07:28