Handle Android AsyncTask Configuration Change Using Fragment

AsyncTask is much preferred way for background processing of some task with easy use of UI thread. It powers you to peform background work and publish results to UI thread without manipulating Threads or Handlers. General usage of AsyncTask includes performing short network or intensive data operations.

We can use IntentService in conjunction with ResultReceiver also for acheiving same result. If interested, you can check our detailed tutorial. Android IntentService: Working and Advantages

With these bundled benefits of AsyncTask, it provides hard time to handle it over configuration change. During configuration change if not handled, it may lead to following problems.

1. Memory Leak : Problem with AsyncTask is that it has an implicit reference of enclosing activity. In case of configuration change if not handled properly, enclosing activity instance will be destroyed but it will not be garbage collected until AsyncTask is running. In case of multiple async tasks running, it may lead to memory leakage. While using AsyncTask you should try that enclosing destroyed activity is freed from memory.

2. Lost Progress and Result: If AsyncTask is used with intention to publish progress and results to Activity UI, they will be discarded as previous activity instance is destroyed. It’s good practice to utilize previous results and progress to current enclosing instance of activity UI update rather than performing same task again.

We will encounter above two problem using Headless Fragments. Fragment which do not have UI are referred as Headless Fragment as they are not part of user interaction. Headless fragments are meant for data encapsulation and can be used for data processing sharing. We will make most out of  fragment’s retaining property which can be set using Fragment.setRetainInstance(boolean). If true, fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack.

You can check out our tutorial on Fragments for their detailed benefits and usage.
Android Fragments: Building dynamic UI, Why to use Fragments?

Sample Android Application





1. Create new android application project with package name “com.androidsrc.headlessfragment” and application name as “HeadlessFragment”.

2. Preparing Application Manifest File

We will have only one activity in our application for Handling Android AsyncTask Configuration Change. No permission is required to mention. Final AndroidManifest.xml will be as below.

3. Preparing Layout File

Our main activity layout /res/layout/activity_main.xml will have ProgressBar and TextView to show progress of AsyncTask running in Fragment. We will have two Button views for starting and cancelling task and one Button view for recreating current activity as in case of configuration change.

4. Create a new class HeadlessFragment which will extend Fragment class. Define an interface TaskStatusCallback inside this class which will be used as callback for notifying AsyncTask status back to Activity.

Override onAttach(), onCreate() and onDetach() to control current active instance for your callback. In onCreate() make sure to make fragment retainable.

Define a private local class BackgroundTask which will extend to AsyncTak and will run the task request from activity in background. We will use callback to update it’s status or progress back to Activity.

Define helper functions to start, cancel and updating status of AsyncTask.
Final code for HeadlessFragment.java will be as below.

5. In your application launcher activity, MainActivity.java implement View.OnClickListener for listening to view onclick events and TaskStatusCallback which we defined in HeadlessFragment.java to listen AsyncTask status. Override all the methods, Final code for MainActivity.java with basic handling of Button view click and UI update on callback from AsyncTask will be as below.

6. Build and run your android application project, Observe that it has resolved both of the problems stated earlier for Android AsyncTask Configuration Change.

You may also like...