I want the user to confirm closing my app. I use the following code for that in my MainActivity:
@Override
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
toast = Toast.makeText(this, "Press back again to close this app", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}
In other classes I use this:
@Override public void onBackPressed() {
if (!mWebView.onBackPressed()) { return; }
// ...
super.onBackPressed(); }
Now I get the confirm event in EVERY class, but I only want it in my MainActivity. How can I do that?
Note: I have to extent my MainActivity in other classes. That should be the main problem to solve, but I still dont know how exactly?
@Vala, If your adding fragments to the Activty
, then you can make use BackSackEntryCount
of FragmentManager
like below.
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
if (backStackCount == 1) {
Toast.makeText(this, "Press back again to close this app", Toast.LENGTH_LONG).show();
}
if backstackcount
is one, it means, on pressing the back button again, remaining frgament will be popped from back stack and app will be quit.