Skip to content Skip to sidebar Skip to footer

How To Override Home Button In Android 4.0

I want to override the home button in my android activity. I have tried out few things related to this which are working for 2.3 and below but not for 4.0 above @Override public bo

Solution 1:

I also encountered such a problem and I am using the following class to listen to the home button click event.

publicclassHomeWatcher {

    staticfinalStringTAG="HomeWatcher";

    private Context mContext;

    private IntentFilter mFilter;

    private OnHomePressedListener mListener;

    private InnerRecevier mRecevier;

    publicHomeWatcher(Context context) {
        mContext = context;
        mFilter = newIntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    }

    /**
     * set the home pressed listener, if set will callback the home pressed
     * listener's method when home pressed.
     * 
     * @param listener
     */publicvoidsetOnHomePressedListener(OnHomePressedListener listener) {
        mListener = listener;
        mRecevier = newInnerRecevier();
    }

    /**
     * start watch
     */publicvoidstartWatch() {
        if (mRecevier != null) {
            mContext.registerReceiver(mRecevier, mFilter);
        }
    }

    /**
     * stop watch
     */publicvoidstopWatch() {
        if (mRecevier != null) {
            mContext.unregisterReceiver(mRecevier);
        }
    }

    classInnerRecevierextendsBroadcastReceiver {

        finalStringSYSTEM_DIALOG_REASON_KEY="reason";

        finalStringSYSTEM_DIALOG_REASON_GLOBAL_ACTIONS="globalactions";

        finalStringSYSTEM_DIALOG_REASON_RECENT_APPS="recentapps";

        finalStringSYSTEM_DIALOG_REASON_HOME_KEY="homekey";

        @OverridepublicvoidonReceive(Context context, Intent intent) {
            Stringaction= intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                Stringreason= intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null) {
                    Log.i(TAG, "receive action:" + action + ",reason:" + reason);
                    if (mListener != null) {
                        if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {

                            // home?
                            mListener.onHomePressed();
                        } elseif (reason
                                .equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {

                            // ??home?
                            mListener.onHomeLongPressed();
                        }
                    }
                }
            }
        }

    }

}

Usage is as follows:

HomeWatcher mHomeWatcher = new HomeWatcher(Context);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {

    publicvoidonHomePressed() {

        //do your somthing...
    }

    publicvoidonHomeLongPressed() {
    }

});

mHomeWatcher.startWatch();

Post a Comment for "How To Override Home Button In Android 4.0"