-2

I am adding fragment in the activity.While user press back button from one fragment screen .I need to exit from the application can anybody tell how to do?

Thanks

user386430
  • 4,837
  • 13
  • 41
  • 45

6 Answers6

2

You can use following method to exit from from fragment

getActivity().moveTaskToBack(true); 
getActivity().finish();

may this will help you

Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
0

3 steps:

Capture the back button press, clear the stack of activities so your activity is at the back of it, and the close it.

@Override
public void onBackPressed() {
    moveTaskToBack (true)
    finish();
}
Antonio MG
  • 20,382
  • 3
  • 43
  • 62
0

Read More at

private Toast toast;
    private long lastBackPressTime = 0;
    @SuppressLint("WrongConstant")
    @Override
    public void onBackPressed() {
        int fragments = getFragmentManager().getBackStackEntryCount();
        if (fragments == 0) {
            // make layout invisible since last fragment will be removed
            if (this.lastBackPressTime < System.currentTimeMillis() - 3000) {
                toast = Toast.makeText(this, "Press back again to close this app", 3000);
                toast.show();
                this.lastBackPressTime = System.currentTimeMillis();

            }else{
                if (toast != null) {
                    toast.cancel();
                }
                super.onBackPressed();
            }

        }else{
            if (toast != null) {
                toast.cancel();
            }
            super.onBackPressed();
        }
    }
Firefog
  • 3,094
  • 7
  • 48
  • 86
0

One safe way when you may have multiple fragments added/replaced is to count the backstack and exit via this: (this would be inside main activity)

@Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
        getSupportFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

This way if you press BACK on a fragment that is not your main, only that fragment is removed and once you reach the lower-most fragment (first one you added) then it will call the onBackPressed of super class which could be your .. BaseActivity extends AppCompatActivity and then inside this BaseActivity add this:

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}
kevoroid
  • 5,052
  • 5
  • 34
  • 43
-1

Pressing back button will be detected from your Activity Try this code:

@Override
public void onBackPressed() {
    finish();
}
MineConsulting SRL
  • 2,340
  • 2
  • 17
  • 32
-2

Using getActivity.finish() I exit from at the application

user386430
  • 4,837
  • 13
  • 41
  • 45