1

Exit from Activity with twice “Back” button click

 1 year ago
source link: https://chintanrathod.com/2015/04/08/exit-from-activity-with-twice-back-button-click/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Exit from Activity with twice “Back” button click

Byadmin April 8, 2015

When we are doing some important operation or work on activity and it may possible that by mistake we pressed “back” button. Then what?? This will simply stop all your important work and you are redirect to previous activity.

To overcome this situation, we can provide a confirmation to the user that you need to press once again to exit from activity. This will give user a great experience in application.

To add this functionality in you application, use following code snippet.

[java]
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press once again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
[/java]

Expatiation

doubleBackToExitPressedOnce” is core of this snippet. When user presses “back” button, value for “doubleBackToExitPressedOnce” is “false” and he will get a message for “Press once again to exit“.

If user presses “back” button one more time, he will redirect to previous activity as “doubleBackToExitPressedOnce” is now “true“.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK