title: Detect home button press in android
body: <p>This has been driving me nuts for a while now. </p>
  
  <p>Is there any way of reliably detecting if the home button has been pressed in an android application?</p>
  
  <p>Failing that, is there a robust way of telling what caused an activity to go into onPause? i.e Can we detect if it was caused by a new activity launching or by pressing back/home.</p>
  
  <p>One suggestion I have seen is to override onPause() and call isFinishing() but this will return false when pressing the home button just as it would if a new activity is starting so this fails to distinguish between the two.</p>
  
  <p>Any help much appreciated.</p>
  
  <p>** Update** :
  Thanks to @android-hungry for this link: <a href="http://nisha113a5.blogspot.com/" rel="noreferrer">https://nishandroid.blogspot.com/</a></p>
  
  <p>Overiding the following method:</p>
  
  <pre><code>@Override
  public void onAttachedToWindow() {
      super.onAttachedToWindow();
      this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
  }
  </code></pre>
  
  <p>Then the following event WILL get fired for home button presses:</p>
  
  <pre><code>@Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {     
  
      if(keyCode == KeyEvent.KEYCODE_HOME)
      {
         //The Code Want to Perform. 
      }
  });
  </code></pre>
  
  <p>I'm not sure if there are any side effects with this line:</p>
  
  <pre><code>this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);   
  </code></pre>
  
  <p>So it would seem that contrary to popular belief, you can in fact listen out for the home key. Worryingly, you can return false and have the home key do nothing.</p>
  
  <p><em>Update</em>:
  As expected, there are some side affects with this - it seems that embedded videos and google maps are not visible with this mode enabled.</p>
  
  <p><em>Update</em>:
  Supposedly this hack no longer works as of Android 4.0 onwards</p>