Search code examples
javaandroidandroid-intentonbackpresseddialogfragment

onBackPressed from Fragment Displays Activity Twice


I have an Application min SDK 21, target 25. Using : android.app.DialogFragment and android.support.v7.app.AppCompatActivity.

The initial Activity is a Launcher it can launch 1 of 3 Activities and 1 DialogFragment. The DialogFragment can in turn launch an Activity (which is one of the 3 Activities). The problem that I have is only with regard to the DialogFragment being loaded and that Fragment then loading an Application and then returning to the Launcher.

When the Fragment returns immediately to the Launcher (without loading the Activity), this works OK. I can detect that the Fragment was loaded via the launcher and onBackPress() handles it OK.

However, when the Fragment loads another Activity and then onBackPress()is used to return to the Fragment and then onBackPress()is used to return to the Launcher, I have a problem. The way this situation is currently handled is that the Fragment loads the Launcher via an Intent using the flags FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TOP (this appeared to be a solution to someone’s similar problem). I have tried other variations of these flags and also without these flags. I have also tried to use for this situation onBackPress()in the DialogFragment without loading the Activity using an Intent, and the Application terminates, and I need it to return to the Launcher.

In this case, using these flags, when I return to the Launcher, the Launcher displays and then clears and then redisplays (on another onBackPress(), the Application then terminates correctly). The problem is with the Launcher displaying twice. I presume that the Launcher that displays first is the original copy loaded and then it is replaced by a new copy. I have not found a way (in this scenario) in which to load the original copy of the Launcher (if that is in fact what is happening). As stated, this is a DialogFragment.

How can I solve this so that the Launcher Activity does not display twice in this situation?


Solution

  • Why you don't just finish the activity within the fragment to return to the launcher activity?

    If you really have to use a intent, try Intent.FLAG_ACTIVITY_REORDER_TO_FRONT