How can I detect user pressing Home button in Android

Total Post:154

 2473  View(s)
Rate this:
  I have used below code. But its not working.

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_HOME:		

Toast.makeText(getApplicationContext(), "Home button pressed", Toast.LENGTH_SHORT).show();

			return true;		
		return super.onKeyDown(keyCode, event);
  1. Post:26

    Re: How can I detect user pressing Home button in Android

    The Home button is a very dangerous button to override and, because of that, Android will not let you override its behavior the same way you do the BACK button.

    Use below code to find home button press.

    Create class HomeWatcher class.

    package com.example.test;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.util.Log;
    public class HomeWatcher {
    	static final String TAG = "hg";
    	private Context mContext;
    	private IntentFilter mFilter;
    	private OnHomePressedListener mListener;
    	private InnerRecevier mRecevier;
    	public HomeWatcher(Context context) {
    		mContext = context;
    		mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    	public void setOnHomePressedListener(OnHomePressedListener listener) {
    		mListener = listener;
    		mRecevier = new InnerRecevier();
    	public void startWatch() {
    		if (mRecevier != null) {
    			mContext.registerReceiver(mRecevier, mFilter);
    	public void stopWatch() {
    		if (mRecevier != null) {
    	class InnerRecevier extends BroadcastReceiver {
    	final String SYSTEM_DIALOG_REASON_KEY = "reason";
    	final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
    	final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
    	final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
    		public void onReceive(Context context, Intent intent) {
    			String action = intent.getAction();
    			if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
    		String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
    		if (reason != null) {
    			Log.e(TAG, "action:" + action + ",reason:" + reason);
    				if (mListener != null) {
    		if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
    		} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
    	public interface OnHomePressedListener {
    		public void onHomePressed();
    		public void onHomeLongPressed();

    Now call on your activity

    HomeWatcher mHomeWatcher = new HomeWatcher(this);
    mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
    			public void onHomePressed() {
    				// do something here...
    			public void onHomeLongPressed() {

      Modified On Dec-09-2015 10:07:05 PM