2

Scenario:

  1. An Android app has an Activity with a Fragment.
  2. The user sends the app to the background by pressing the home key.
  3. Two hours pass, the Android OS kills the process to free up resources.
  4. The user switches back to the app through the Recent Apps List.

The onCreate method of the Activity will now find the existing Fragment by using fragmentManager.findFragmentByTag()* as best practice cites. Yet, adding this old fragment to the activity will not make the fragment render. I'm unsure if I'm doing something wrong, or this is simply not a supported use case for reusing old fragments.

Must I implement special handling of this scenario (i.e. new up the Fragment instead of reusing the old)? If so, what is the best practice of detecting that the process has been killed and relaunched in onCreate?

edit 1: *) I am testing this by using DDMS to kill the process. This might not emulate the OS' way terminating a process correctly, as for instance onDestroy() is not called. Does anoyone know if the old fragments are disposed from the FragmentManager when onDestroy() is invoked by the OS? If this is the case, this question is moot.

Community
  • 1
  • 1
Nilzor
  • 18,082
  • 22
  • 100
  • 167

1 Answers1

0

No, You can't reuse a Fragment once the process is killed. Once the process is killed, you app no longer exists on Android main thread, hence a new instance of the activity has to be launched.

Your app starts with an your main activity as in Manifest file, and loads corresponding views and fragments. Please go through the Activity Lifecycle of the Android, to know more about it. This teaches you how to maintain your activity run in background and when not in use:http://developer.android.com/training/basics/activity-lifecycle/index.html

zIronManBox
  • 4,967
  • 6
  • 19
  • 35
  • I'm aware a new instance of the activity is launched. Yet the savedBundleInstance is *not* null, and the fragment *exists* when quering the fragment manager. I'm asking for how to properly implement workaround for the fact that I can't use this dead instance. Or detect that this instance is dead in the first place. – Nilzor May 28 '14 at 09:50
  • 1
    You could make use of `onDestroyView()` method in Fragment class, or use `onDestroy()` method of Activity to help your case. – zIronManBox May 28 '14 at 10:39
  • Good point. But see edit 1. I am currently waiting for the OS to terminate the process the regular way, in order to test this properly. Will be back in a couple of hours (sigh...) – Nilzor May 28 '14 at 11:02