title: Android Power Button Pressed to Close
body: <p>I have an app that works perfect but when I press power button some activity variables lost their value. So I decided to close the app.  I am using BroadcastReceiver to close the app.</p>
  
  <pre><code>public void onReceive(final Context context, Intent intent) {
  
      String intentAction = intent.getAction();
      if (intentAction!=null){
          String myLog = "Unknown intent action";
          switch (intentAction){
              case Intent.ACTION_SCREEN_OFF:
                  myLog = "Power Button Press SCREEN OFF";
                  break;
              case Intent.ACTION_SCREEN_ON:
                  myLog = "Power Button Press SCREEN ON";
                  break;
              case MY_BROADCAST:
                  myLog = "Custom Broadcase Reveived";
                  break;
          }
          if (myLog.equalsIgnoreCase("Power Button Press SCREEN OFF") || myLog.equalsIgnoreCase("Power Button Press SCREEN ON")) {
              AlertDialog.Builder builder = new AlertDialog.Builder(context);
              builder.setMessage("Close your app").setPositiveButton("OK", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      Activity a = (Activity) context;
                      a.finish();
                  }
              });
              Dialog dialog = builder.create();
              dialog.show();
  
          }
      }
  }
  </code></pre>
  
  <p><strong>In Activity onCreate ...</strong></p>
  
  <pre><code>private MyPowerReceiver mReceiver = new MyPowerReceiver();
  IntentFilter filter = new IntentFilter();
  filter.addAction(Intent.ACTION_SCREEN_OFF);
  filter.addAction(Intent.ACTION_SCREEN_ON);
  this.registerReceiver(mReceiver, filter);
  
  LocalBroadcastManager.getInstance(this).registerReceiver(
                  mReceiver, new IntentFilter(MY_BROADCAST)
  startMyBroadCase(); // call BroadCase to start
  </code></pre>
  
  <p><strong>In startMyBroadCase() function...</strong></p>
  
  <pre><code>private void startMyBroadCase() {
          Intent powerBroadCaseIntent = new Intent(MY_BROADCAST);
          LocalBroadcastManager.getInstance(this).sendBroadcast(powerBroadCaseIntent);
      }
  </code></pre>
  
  <p>But code does not working  </p>