Search code examples
androidandroid-studiobroadcastreceiverandroid-broadcastreceiver

Android Screen On And Off Handling Using Power Button


I am trying to detect if power button is pressed three times within 4 seconds. Below code is not working.

public class PowerButtonReceiver extends BroadcastReceiver{

    static int count = 0;
    long initialTime,finishTime;

    @Override
    public void onReceive(final Context context, Intent intent) {

        Log.v("onReceive", "Power button is pressed.");
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            if (count == 0){
                initialTime = System.currentTimeMillis();
            }
            count++;
            if (count == 3){
                finishTime = System.currentTimeMillis();

                if (finishTime - initialTime <= 4000){
                    Toast.makeText(context, "POWER BUTTON CLICKED 3 TIMES", Toast.LENGTH_LONG).show();
                    count = 0;
                }
            }

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {

            if (count == 0){
                initialTime = System.currentTimeMillis();
            }
            count++;
            if (count == 3){
                finishTime = System.currentTimeMillis();

                if (finishTime - initialTime <= 4000){
                    Toast.makeText(context, "POWER BUTTON CLICKED 3 TIMES", Toast.LENGTH_LONG).show();
                    count = 0;
                }
            }
        }
    }
  }

the code executes without error and it does not show toast


Solution

    1. Hope you are registering the receiver dynamically.
      ACTION_SCREEN_OFF --

      You cannot receive this through components declared in manifests,...

    2. Except the following scenario:

      if (finishTime - initialTime <= 4000){ Toast.makeText(context, "POWER BUTTON CLICKED 3 TIMES", Toast.LENGTH_LONG).show(); count = 0; }

    nothing else re-assigns the count to 0, so if you missed a toast once..the counter does not reset to 0 in a single run and the following events for the <=4000 condition won't enter the if, maybe you should reassign count to 0 if it is greater than 3 (?)

    1. What happens if your toast appeared during the click when screen was turned off--don't think it will be visible
    2. Should consider using || replacing the if-else, works better if you only want to detect power button events irrespective of screen off or on; like:

      if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF) || intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { ...

    if 1. is not a problem, at present your code seems fine, it is a combination of 2. and 3. 4. is just a suggestion