Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finish activity when back button twice pressed? [duplicate]

I am creating an application here i need to finish activity when user twice pressed back button. Here is my code what i tried

 @Override
public void onBackPressed() {
        super.onBackPressed();
        this.finish();
}

tried this too

 @Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
    finish();
}
return super.onKeyDown(keyCode, event);
}

this helps me to finish activity once back button pressed.

Pls i need your suggestion. Thanks in advance

like image 908
Aristo Michael Avatar asked Dec 31 '13 06:12

Aristo Michael


1 Answers

Ok...here is a longer, but effective way of doing this...

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();
}

Hope this will help...:)

like image 105
umair.ali Avatar answered Sep 21 '22 10:09

umair.ali