Press back button twice to exit the app with some condition - android

All I want is to exit the application only when back stack is empty.
One section of my app contains a gallery,in which, when a picture is clicked, a fragment showing the full screen image is opened. When back button is pressed in this full screen image, I want to go back to the gallery fragment. I did this by adding the fragment to back stack.
But in other parts of the application, when back button is pressed, I want to show a toast "Please click BACK again to exit". And when the back button is pressed again, the app closes. How can I do this?
This is what I have done so far:
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
commonTasks.ShowStringMessage("Please click BACK again to exit");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
//super.onBackPressed();
}
}
Obviously, it didn't work.

You can try using getSupportFragmentManager() It has a method which returns array of all the fragments it is containing and you can put the check for its size as following
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getFragments().size() > 0 ){
getSupportFragmentManager().popBackStack();
} else {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
commonTasks.ShowStringMessage("Please click BACK again to exit");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
//super.onBackPressed();
}
}
P.S: you also need to change getSupportFragmentManager() while fragment transection.
Also reffer this link
Why FragmentManager's getBackStackEntryCount() return zero?

You can try something diff. Add Exit code in your Activity's onBackPressed Method, and whenever you get the onBackPressed trigger Just check that is your Gallery Fragment is Active? , if it is then Perform Exit code else Change the Fragment.
//define as field variable
private boolean doubleBackToExit = false;
MyGalleryFragment myFragment = (MyGalleryFragment)getFragmentManager().findFragmentByTag("MY_FRAGMENT");
if (myFragment != null && myFragment.isVisible()) {
if (doubleBackToExit) {
super.onBackPressed();
finishAffinity();
return;
}
this.doubleBackToExit = true;
toastMsg(getResources().getString(R.string.touch_again_to_exit));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExit = false;
}
}, 2000);
} else {
//Change Layout/Fragment
}
Just Dont forget to Add Tag in Fragment...
fragTrans.replace(android.R.id.content, myFragment, "MY_FRAGMENT");
Hope this will work..!

Try using
super.onBackPressed();
instead of
getFragmentManager().popBackStack();
and let us know about the result.

Related

I have one stack item, I want to exit the application by double clicking back pressed

if I have one stack item, I want to exit the application by double clicking back pressed, how will I know when I will have one item on stack?
My code in override method onBackPressed
if (getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
}
else if(getFragmentManager().getBackStackEntryCount()==1){
moveTaskToBack(false);
}
else {
getFragmentManager().popBackStack();
}
Here is my solution, you can follow what I comment in the code.
private static final long DURATION_BETWEEN_BACK_PRESS = 1000;
private final Handler handler = new Handler();
private boolean isBackButtonPressed = false;
private final Runnable resetIsBackButtonPressed = new Runnable() {
#Override
public void run() {
isBackButtonPressed = false;
}
};
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getFragmentManager();
int backStackEntryCount = fragmentManager.getBackStackEntryCount();
if (backStackEntryCount == 0) {
// There is no item in back stack. This happens when you do not add any fragment to activity.
super.onBackPressed();
return;
}
if (backStackEntryCount > 1) {
// The back stack has more than one item, just pop top item from the stack.
fragmentManager.popBackStackImmediate();
return;
}
// The back stack has only one item left.
if (!isBackButtonPressed) {
// The first time back button pressed.
isBackButtonPressed = true;
// If users do not press back key second time in a given duration, then just reset back pressed status.
handler.postDelayed(resetIsBackButtonPressed, DURATION_BETWEEN_BACK_PRESS);
} else {
// The second time back button pressed.
handler.removeCallbacks(resetIsBackButtonPressed);
finish();
}
}

press back again to exit in android studio

how to implement press back again to exit in android studio, Pls. see My coding here. i'd checked all discussions here regarding this, but not working with my code. i've to make sure On back pressed, always go to home fragment before closing.
Thank you very much in advance!
/**
* On back pressed, always go to home fragment before closing
*/
#Override
public void onBackPressed() {
//if stack has items left
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
//get current fragment
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.mainFragment);
//only close if in CategoryFragment else go to CategoryFragment
if (fragment instanceof SearchFragment) {
finish();
} else {
changeFragment(new SearchFragment());
}
} else {
super.onBackPressed();
}
}
OnBackPress
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish()
If you wanna make onBackPressed again to exit activity you can use this
public void onBackPressed() {
count++;
if (count > 1) {
moveTaskToBack(true);
} else {
showToast("Press back again to Leave!");
// resetting the counter in 2s
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
count = 0;
}
}, 2000);
}
}

I want to close the app but do not go back to the previous Activity

I used an activity and several pieces in my app
sometimes when I'm on the first page (activity) and back pressed not going out of app and returns to the fragment or the same page
When this happens I've done a lot of work in the program
I used this code to fix this problem but
it also applied to the fragments
#Override
public void onBackPressed() {
this.finish();
}
Why returns to the fragment or the same page
How this problem is solved
I'm using this now
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else if (!doubleBackToExitPressedOnce) {
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Click to exit again", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
} else {
super.onBackPressed();
return;
}
}
Way is going to be a fragment
TabirFragment tabirFragment = new TabirFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
bundle.putString("name", name);
tabirFragment.setArguments(bundle);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction().addToBackStack(null);
transaction.replace(R.id.main_activity, tabirFragment).commit();
If you have multiple activities on the stack, then:
finish() - finishes the activity where it is called from and you see
the previous activity.
There is also system.exit but that would not work in your case:
System.exit(0) - restarts the app with one fewer activity on the
stack. So, if you called ActivityB from ActivityA, and System.exit(0)
is called in ActivityB, then the application will be killed and
started immediately with only one activity ActivityA
I recommend you use finishAffinity(). It will finish the current activity as well as all activities immediately below it. I remind you that it is supported by only API level 16+
several pieces what? fragments, getting trouble to understand, anyway if you want to manage frag and onBackPress, use this
private void setUpBackStackListener() {
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.am_frameLayout);
if (currentFragment != null) {
int myCount = getFragmentManager().getBackStackEntryCount();
if (LOG_DEBUG) Log.e(TAG, "backStackCount : " + myCount);
String currentFragName = currentFragment.getClass().getSimpleName();
if (currentFragName.equalsIgnoreCase(FragOne.class.getSimpleName())) {
shouldExit = true;
} else if (currentFragName.equalsIgnoreCase(FragTwo.class.getSimpleName())) {
shouldExit = false;
}
}
}
}
});
}
#Override
public void onBackPressed() {
if (shouldExit == true) {
if (LOG_DEBUG)
Log.e(TAG, " Yeah exit douche:" + shouldExit + " isLastEntry : Testing :" + isLastEntry);
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}
,if this not you seeking, you might want to clear what you want in a bit subtle way
When you used multiple fragment and activity When you switch activity by using method startActivity(), always use method finish(); when you back pressed then you will never get multiple activity and fragment and use onBackPressed method on main activity.
boolean doubleBackToExitPressedOnce=false;
#Override
public void onBackPressed() {
//Checking for fragment count on backstack
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else if (!doubleBackToExitPressedOnce) {
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this,"Please click back again to exit.", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
} else {
super.onBackPressed();
return;
}
}
The easiest solution i can give you is to keep no-history for the activity in the manifest file. and then override the back method for each activity.
<activity
android:name=".example"
android:noHistory="true">
</activity>

Onbackpressed redirect to particular fragment

In my app i have navigation drawer,So i have one MainActivity and rest are fragments. My app is working fine. Whenever i press back button it redirect to previous fragment.it works fine.but what i want is after successful payment i am displaying Successful payment page,on this page when user press back button i want to redirect to HomeFragment,but right now it goes to Placeorder fragment.
#Override
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
}
else {
getFragmentManager().popBackStack();
}
}
Override your onBackPress method:
#Override
public void onBackPressed() {
if (fragment != null && fragment.getChildFragmentManager().getBackStackEntryCount() > 0){
fragment.getChildFragmentManager().popBackStack();
}else {
super.onBackPressed();
}
}
One way would be saving previous fragment (previousFragment) variable while opening new fragment and making it null when you are in first or placeholder fragment .... then check value of previousFragment inside onBackPressed method , if null perform exit operation else replace fragment with previousFragment by which you will get back to previous fragment on back press.
You should simulate function as below in abstract class fragment
/**
* Handle "Back" key pressed.
* #return TRUE if the "Back" key pressed was handled. FALSE indicate it's not handled and parent class can handle it.
*/
public abstract boolean onBackPressed()
And in MainActivity, you will handle this function
#Override
public void onBackPressed() {
if (mSelectedFragment != null && mSelectedFragment.onBackPressed()) {
return;
} else {
super.onBackPressed
}
}
inside your onBackPressed() do like this:
#Override
public void onBackPressed() {
if(getSupportFragmentManger.findFragmentByTag("paymentFragment") != null){
//add homeFragment;
}
else{
if(getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
}
else {
getFragmentManager().popBackStack();
}
}
}
you can set some global variable (true when payment is success else false) in Application class and in onbackpressed of your activity just check that variable is true or not.Then in backpressed of your activity call this function.
public void clearBackStack() {
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0) {
FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
Use:
fragmentTransaction.replace(R.id.fragment_container, mFeedFragment);
fragmentTransaction.commit();
Don't do this:
fragmentTransaction.addToBackStack(null);
Follow this simple method
declare an integer as
public int count;
initialise this count as count=0 in your main page
now include this in your main activity
#Override
public void onBackPressed() {
if (count == 1) {
if (exit) {
super.onBackPressed();
return;
} 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;
}
}, 2000);
}
}else {
toolbar.setTitle("Home");
mDrawerLayout.closeDrawers();
count=1;
display(0);
}
}

Back press in a fragment

In a fragment on ViewPager I have ListView and GridView. Initially I hide ListView and show GridView. When I click an item in GridView, I hide GridView and show ListView. Now I want to return to the previous state when I click again: hide the ListView and show the GridView. How do I do this? I tried with method onBackPressessed in activity:
public void onBackPressed() {
int count = viewPager.getCurrentItem();
if (count == 3) {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
super.onBackPressed();
} else {
// Toast.makeText(this, "BACK",
// Toast.LENGTH_SHORT).show();
if (!flag) {
Toast.makeText(this, "Nhấn Back một lần nữa để thoát",
Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
#Override
public void run() {
flag = true;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = false;
}
}).start();
} else {
super.onBackPressed();
}
}
} else....
But I do not know how to call it in fragment. Please help me.
You can call onBackPressed with the hosting activity. Try this in your fragment:
getActivity().onBackPressed();
That will call the activity's onBackPressed() method, which will do what you want.

Categories

Resources