title: Android Power Button Pressed
body: <p>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.</p>
  
  <p>For now, I tried the following:</p>
  
  <pre><code>public class SMSKey extends BroadcastReceiver{
  
      static int countPowerOff = 0;
      private Activity activity = null;
      public SMSKey(Activity activity){
          this.activity = activity;
      }
  
      @Override
      public void onReceive(Context context, Intent intent) {
          // TODO Auto-generated method stub
  
          if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
              countPowerOff++;
          }else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
              if(countPowerOff == 2){
                  Intent i = new Intent(activity, SMSOptions.class);
                  activity.startActivity(i);
              }
          }
      }
  
  }
  </code></pre>
  
  <p>and in my <strong>manifest</strong>:</p>
  
  <pre><code>&lt;receiver android:name=".SMSKey"&gt;
          &lt;intent-filter &gt;
              &lt;action android:name="android.intent.action.SCREEN_OFF"/&gt;
              &lt;action android:name="android.intent.action.SCREEN_ON"/&gt;
              &lt;action android:name="android.intent.action.ACTION_POWER_CONNECTED"/&gt;
              &lt;action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/&gt;
              &lt;action android:name="android.intent.action.ACTION_SHUTDOWN"/&gt;
          &lt;/intent-filter&gt;
      &lt;/receiver&gt;
  </code></pre>
  
  <p>finally in my <strong>MainActivty.java</strong>:</p>
  
  <pre><code>IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
  filter.addAction(Intent.ACTION_SCREEN_OFF);
  SMSKey mReceiver = new SMSKey(this);
  registerReceiver(mReceiver, filter);
  </code></pre>
  
  <p>Even though this works, it only works for the 1st time, it won't work on the 2nd or 3rd attempt when the power button is pressed. Why is that so ?? </p>
  
  <p>And another question: as you can see, I am using this KeyPress event in my MainActivity, which means the application is to be open all the time. Is there any other way that I can implement this without getting into the MainActivity. </p>