Thursday, 13 August 2015

finish activity when back button twice pressed? [duplicate]

1) Make a global vairable in your class like...
private boolean backPressedToExitOnce = false;
private Toast toast = null;
2) Then implement onBackPressed of activity like this...
@Override
public void onBackPressed() {
    if (backPressedToExitOnce) {
        super.onBackPressed();
    } else {
        this.backPressedToExitOnce = true;
        showToast("Press again to exit");
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                backPressedToExitOnce = false;
            }
        }, 2000);
    }
}
3) Use this trick to handle this toast efficiantly...
/**
 * Created to make sure that you toast doesn't show miltiple times, if user pressed back
 * button more than once. 
 * @param message Message to show on toast.
 */
private void showToast(String message) {
    if (this.toast == null) {
        // Create toast if found null, it would he the case of first call only
        this.toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);

    } else if (this.toast.getView() == null) {
        // Toast not showing, so create new one
        this.toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);

    } else {
        // Updating toast message is showing
        this.toast.setText(message);
    }

    // Showing toast finally
    this.toast.show();
}
4) And use this trick to hide toast when you activity is closed...
/**
 * Kill the toast if showing. Supposed to call from onPause() of activity.
 * So that toast also get removed as activity goes to background, to improve
 * better app experiance for user
 */
private void killToast() {
    if (this.toast != null) {
        this.toast.cancel();
    }
}
5) Implement you onPause() like that, to kill toast immidiatly as activity goes to background
@Override
protected void onPause() {
    killToast();
    super.onPause();
}

No comments:

Post a Comment