I have an application that uses fragments. On app launch I do this:
FragmentManager man = getFragmentManager();
FragmentTransaction trans = man.beginTransaction();
trans.replace(R.id.master_container, master);
trans.commit();
As you can see I don't add it to the Backstack because I don't want users to be caught in an empty activity with no fragment. However that doesn't work. Because when I press the backbutton in the master
screen it will close the fragment and leave me in a black activity.
Now I override the onBackPressed()
method to help me:
@Override
public void onBackPressed() {
// 'master' is the Mainscreen Fragment
if (master.isVisible()) {
if (!second) {
Toast.makeText(getApplication(), "Press back again to close application", Toast.LENGTH_SHORT).show();
second = true;
} else {
second = false;
CreamyActivity.this.finish();
}
} else {
super.onBackPressed();
bar.show();
}
}
But whenever CreamyActivity.this.finish();
it again just closes the fragment and drops into the blank activity (as if it was just following the backstack) (This is all in the Activity btw!)
I was wondering if you could help me. Usually apps shouldn't close themselves but I would really appreciate a workaround here. Or am I doing something wrong with the backstack? Does it automatically add it anyways?
Thanks in advance <3
Okay as CommonsWare (Thanks to you!) pointed out there WAS something else interfering with the workings of the application. It's structured like this:
App Launch --> LaunchActivity if(API > 14) --> CreamyActivty
else --> CrunchyActivity
When calling finish() in CreamyActivity it made the App go back to the LaunchActivity which didn't have anything else in it's onCreate() other than the if-else statement. Now I've done this:
To my LaunchActivity I added:
private IntentFilter filter;
filter = new IntentFilter(Util.BACKSTACK_INTENT);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
LaunchActivity.this.finish();
unregisterReceiver(this);
}
}, filter);
And into the onBackPressed() method from the Creamy/Crunchy Activities I added this:
CreamyActivity.this.finish();
Intent kill = new Intent();
kill.setAction(Util.BACKSTACK_INTENT);
this.sendBroadcast(kill);
Like this every time the user wants to go out of the application it will send an intent back to the LaunchActivity and terminate that one as well.
Again. Thanks a lot to CommonsWare for pointing out the flaw in the previous design :P Hope this helps somebody.