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
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
You can use following method to exit from from fragment
getActivity().moveTaskToBack(true);
getActivity().finish();
may this will help you
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();
}
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();
}
}
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();
}
Pressing back button will be detected from your Activity
Try this code:
@Override
public void onBackPressed() {
finish();
}