Reputation: 933
I'm currently working on an app that uses a lot the back button of android devices. I was wondering how to check if the activity is the last one and if the user presses back again, it doesn't exit the app except if the user presses back again, like with the 9gag app.
Thank you!
Upvotes: 3
Views: 6963
Reputation: 1
This will not Worke OnBackpress method
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
Upvotes: 0
Reputation: 16910
With the method Activity.isTaskRoot()
you can check if the user will exit the app on pressing the back button.
Then you just have override onBackPressed()
to handle it differently than usual.
Upvotes: 4
Reputation: 6546
Here example:
private boolean doubleBackToExitPressedOnce;
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, this.getResources().getString(R.string.exit_toast), Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
DrawerLayout
block is optional.
Upvotes: 3
Reputation: 1042
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
Upvotes: 7