Fragments Without User Interfaces

In most circumstances, Fragments are used to encapsulate modular components of the UI; however, you can also create a Fragment without a UI to provide background behavior that persists across

Activity restarts. This is particularly well suited to background tasks that regularly touch the UI or where it’s important to maintain state across Activity restarts caused by configuration changes.

You can choose to have an active Fragment retain its current instance when its parent Activity is recreated using the setRetainInstance method. After you call this method, the Fragment’s lifecycle will change.

Rather than being destroyed and re-created with its parent Activity, the same Fragment instance is retained when the Activity restarts. It will receive the onDetach event when the parent Activity is destroyed, followed by the onAttach, onCreateView, and onActivityCreated events as the new parent Activity is instantiated.

The following snippet shows the skeleton code for a Fragment without a UI:

public class NewItemFragment extends Fragment {
 @Override
 public void onAttach(Activity activity) {
 super.onAttach(activity);
 
 // Get a type-safe reference to the parent Activity.
 }
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 // Create background worker threads and tasks.
 }
 @Override
 public void onActivityCreated(Bundle savedInstanceState) {
 super.onActivityCreated(savedInstanceState);
 // Initiate worker threads and tasks. 
 } 
}

To add this Fragment to your Activity, create a new Fragment Transaction, specifying a tag to use to identify it. Because the Fragment has no UI, it should not be associated with a container View and generally shouldn’t be added to the back stack.

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
fragmentTransaction.add(workerFragment, MY_FRAGMENT_TAG);
fragmentTransaction.commit();

Leave a Comment