Skip to content Skip to sidebar Skip to footer

Android Power Button Pressed

I am trying to create an application that could respond when the power button is pressed. To be more specific, which would respond to it when pressed 2 or 3 times. For now, I tried

Solution 1:

This is not even an Android problem. You never reset your countPowerOff variable after you have received the 3 key presses. Even after having done that you must consider adding an alarm that will reset your countPowerOff variable to zero after some small timeout. It will allow you to avoid situations where the user does not intend to interact with your application and just presses the button, but it still gets counted.

As to your second question, try implementing an IntentService.

Solution 2:

Here is the solution

publicclassMyReceiverextendsBroadcastReceiver {
privatestaticint countPowerOff = 0;

publicMyReceiver (){

}

@Override
publicvoidonReceive(Context context, Intent intent){
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){    
    Log.e("In on receive", "In Method:  ACTION_SCREEN_OFF");
    countPowerOff++;
}
elseif (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
    Log.e("In on receive", "In Method:  ACTION_SCREEN_ON");
}
elseif(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
    Log.e("In on receive", "In Method:  ACTION_USER_PRESENT");
    if (countPowerOff >= 2)
    {
        countPowerOff=0;
        Toast.makeText(context, "MAIN ACTIVITY IS BEING CALLED ", Toast.LENGTH_LONG).show();
        Intent i = new Intent(context, About.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(i);
    }
}
  }
 }

Post a Comment for "Android Power Button Pressed"