-2

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?

AlexioVay
  • 4,338
  • 2
  • 31
  • 49

4 Answers4

0

Try using this in your main activity

 private boolean exit = false;
@Override
public void onBackPressed()
{
    if (exit) {
        finish(); // finish activity
    } else {
        Toast.makeText(this, "Press Back again to Exit.",
                       Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);

    }
}
user5894647
  • 544
  • 6
  • 15
0

Try like this

    Activity activity = this;
    if (activity instanceof MainActivity) {
        if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
            Toast 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();
        }
    } else {
        super.onBackPressed();
    }
Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
0

@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.

Sangeetha Pinto
  • 1,022
  • 3
  • 14
  • 32
-1

change other class to

@Override 
public void onBackPressed() {
   if (mWebView.canGoBack()) { return; }
            // ...
   super.onBackPressed(); 
}
Sanjay Kakadiya
  • 1,596
  • 1
  • 15
  • 32