Search code examples
androidbroadcastreceiver

Reset the counter if the power key is not pressed for 30 seconds


I am developing an application which would start sending out the message, if the power key is pressed four times.. I have used Broadcast Service and Receiver to make this work.

The problem now is if I click power key two times in the morning and two more times in the evening, still it sends out the message.

I want to restrict the time interval between the power key presses.

This is how my receiver looks like.

private static int countPowerOff=0;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            screenOff = true;
            countPowerOff++;
            if(countPowerOff==3) {
                countPowerOff = 0;
                SendMessage sms = new SendMessage(context);
                try {
                    sms.sendSMS();
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                catch (IOException ie)
                {
                    ie.printStackTrace();
                }
            }
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            screenOff = false;
            countPowerOff++;
            if (countPowerOff == 3) {
                countPowerOff = 0;
                SendMessage sms = new SendMessage(context);
                try {
                    sms.sendSMS();
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
            }
        }

Solution

  • Create a CountDownTimer to reset the counter to 0 after a particular time intervel. Refer CountDownTimer