My question is can we override home button or Can't?
Answer: since android 4.0, you can not override home button as a non-system app.
But there are some ways to listen whether users have pressed home button. If you are interested in this, I would supply some solutions for you.
Edit: Add some solutions to listen home button pressed.
I supply you two ways to listen home button pressed event.
First, reigster a Broadcast Receiver.
class HomeKeyBroadCastReceiver extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
//press Home button
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
//press recent app button
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
// long press home button
final String SYSTEM_DIALOGS_REASON_LONG_PRESS_HOME_KEY = "globalactions";
@Override
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) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
// press home , do something
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
// press recent app , do something
} else if (reason.equals(SYSTEM_DIALOGS_REASON_LONG_PRESS_HOME_KEY)) {
// long press home button , do something
}
}
}
}
}
// register Receiver
AppUtils.context.registerReceiver(homeKeyBroadCastReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
Another way, you can register lifecycle callback in your application.
application.registerActivityLifecycleCallbacks(new HomeButtonListerLifecycleCallbacks());
public class HomeButtonListerLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
// check threshold
private final int CHECK_DELAY = 200;
private Handler handler;
private Runnable checkRunnable;
public HomeButtonListerLifecycleCallbacks() {
this.handler = new Handler(Looper.getMainLooper());
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ZZLocalPushInfoManager.getInstance().onCreateActivity(activity);
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
if (handler != null && checkRunnable != null) {
handler.removeCallbacks(checkRunnable);
}
}
@Override
public void onActivityPaused(final Activity activity) {
if (handler != null) {
if (checkRunnable != null) {
handler.removeCallbacks(checkRunnable);
}
handler.postDelayed(checkRunnable = new Runnable() {
@Override
public void run() {
// Here user has left your app. mostly they pressed home button,
// but they also can go to other app by notification,etc.
}
}, CHECK_DELAY);
}
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}