Analyse Fragment-Activity Lifecycle

Fragments are the most lovely pieces of app used by Android Developers and a deep understanding of it help developers to avoid many pitfalls & unexpected behavior in process

The first thing you should know about Fragments is that they are not a standalone components, instead that they are hosted by an Activity , so their lifecycle 

will be closely related to the the pattern of Activity lifecycle,at the same time they have their own lifecycle pattern , so the complexity comes when activity lifecycle is not well coupled with Fragment lifecycle and vice versa! As you can see in the following lifecycle diagram in which Fragment and activity lifecycle are compared , when a fragment instance is created the first method called is onInflate() , this is the place when we can retrieve some attributes values , but notice this method is now deprecated in API level 23 , and maybe not available anymore in latest version, so should avoid to use it.Then immediately after onInflate() ,system attach the fragment to Activity and onAttach() will be invoked on Fragment , this process then followed by invoking onAttachFragment on Activity , then Fragment onCreate is called notice at this this stage Fragment View is not still created it will be created just after Fragment’s onCreate by calling onCreateView but still not fully exposed , the View creation is completed by invoking onViewCreated.
during all this process on Fragment side , Activity on the other side is completing in parallel its lifecycle once Activity creation is done the next step for Fragment lifecycle is onActivityCreated() which will be called to indicate Fragment Activity is created , notice onActivityCreated() is only called in a start process not restart! if Fragment is already created and attached , when restarted onActivityCreated() is not called and this is the root cause of many issues developers face when they setup thier initialization here and get surprized when upon a restart onActivityCreated() is not called! the next step onViewStateResored() follows the same pattern and upon restart its not being called.


notice if you set setRetainInstance(true) , this has a big impact on Fragment lifecycle , in this case fragment instance remain undestroyed when detached from Activity , its maybe useful in the case you don’t keep your instance after change in configuration and you don’t want to go not into the whole process of Fragment recreation


Steps to activate a Fragment

  1. onInflate (Deprecated in API 23)
  2. onAttach (Fragment is attached to Activity
  3. onCreate (Fragment is being created)
  4. onCreateView (View is being created)
  5. onViewCreated (View is created)
  6. onActivityCreated (Activity created but not called upon restart!)
  7. onViewStateRestored (State restored but not called upon restart!)
  8. onStart (Fragment start)
  9. onResume (Fragment resume)
  10. onCreationOptionsMenu
  11. onPrepareOptionsMenu


Activity is going through its own lifecycle during the Fragment loading but some subtle communications is coordinated between Fragment and Activity in order to get informed about each step in Fragment creation there a brief explanation :


When onAttach is invoked on Fragment , before fallthrough next step onCreate , Activity is notified of attachment by invoking onAttachFragment on Activity , this operation is synchronous and Fragment onCreate is called after onAttachFragment has been invoked.

Notice in this cycle diagram , maybe a little bit different when using V4 library , for example  in V4 in addition to onResume we have onResumeFragment which is called in Activity each time  Fragment is loaded, 


[Figure taken from Steve Pomeroy with a little change]


onResume() should be used for normal Activity's and onResumeFragments() when using the v4 compat library , 

Setup a proper channel of communication 
between Fragments and Activity:

One of the most frequent question about Fragments is how Fragments communicate to each other? how we can build a factory mechanism for this communication in a proper way?

Well although there are many ways to achieve it such as Interface, broadcasting , even using statis variables , but the best solution still rely on using of Interface , you can setup many listeners to talk with other fragments the issue of many developers is not using Interface itself but rather where to implement in a trusted way? this cannot be done unless we have a deep understanding of Fragment/Activity lifecycle and thier interaction.

As the activity is hosting all fragments , we can declare an activity level Interface , which our Activity is conforming to it , This way we have a single place which all Fragments can access via getActivity and a simple casting to this interface , gives a unique channel of communication , ofcourse to do that we have to setup many checking process coordinated with Fragment Manager in order to make a trusted solution.

Let’s suppose this interface , 

interface activityListener{
void onUpdateInfo(CInfo info);

}

CInfo could be any DataModel processed by Fragments
Our Activity let’s call it CustomFragmentActivity adopt and implement the interface

class CustomFragmentActivity implements activityListener {


public void onUpdateInfo(CInfo info){

//Get Fragment through FragmentManager

Fragment fragmentB = getFragmentManager().FindFragment()

if(fragmentB.isAdded()
  getFragmentManager().FindFragment().setInfo(info)
//getFragmentManager() or getSupportFragmentManager()

}

}


class CustomFragmentA extends Fragment{


someMethod(CInfo info){

if getActivity() instanceof activityListener{

   (activityListener)getActivity().onUpdateInfo(info)

}

}


this way you can not only setup a two way channel of communication but also a factory centralize place to control everything.

[The codes above is just the code representing the main mechanism and not compiled codes.]








 © Xosrov 2016