0% found this document useful (0 votes)
175 views21 pages

AsyncTask and Loaders

Async Loaders

Uploaded by

Alvaro Medina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
175 views21 pages

AsyncTask and Loaders

Async Loaders

Uploaded by

Alvaro Medina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

AsyncTask and Loaders -

Tutorial
Lars Vogel (c) 2014, 2016 vogella GmbHVersion 3.4,27.06.2016
Table of Contents
• 1. Background processing in Android
o 1.1. Why using concurrency?
o 1.2. Main thread
o 1.3. Threading in Android
o 1.4. Providing feedback to a long running operation
• 2. Handler
o 2.1. Purpose of the Handler class
o 2.2. Creating and reusing instances of Handlers
o 2.3. Example
• 3. AsyncTask
o 3.1. Purpose of the AsyncTask class
o 3.2. Using the AsyncTask class
o 3.3. Parallel execution of several AsyncTasks
o 3.4. Example: AsyncTask
• 4. Background processing and lifecycle handling
o 4.1. Retaining state during configuration changes
o 4.2. Using the application object to store objects
• 5. Fragments and background processing
o 5.1. Retain instance during configuration changes
o 5.2. Headless fragments
• 6. Loader
o 6.1. Purpose of the Loader class
o 6.2. Implementing a Loader
o 6.3. SQLite database and CursorLoader
• 7. Exercise: Custom loader for preferences
o 7.1. Implementation
o 7.2. Test
• 8. Usage of services
• 9. Exercise: activity lifecycle and threads
• 10. About this website
• 11. Links and Literature
o 11.1. Concurrency Resources
o 11.2. Android Resources
o 11.3. vogella GmbH training and consulting support
• Appendix A: Copyright and License
Android Threads, Handlers AsyncTask. This tutorial describes the usage of asynchronous
processing in Android applications. It also covers how to handle the application life cycle
together with threads. It is based on Android Studio.

1. Background processing in Android


1.1. Why using concurrency?
By default, application code runs in the main thread. Every statement is therefore executed in
sequence. If you perform a long lasting operation, the application blocks until the corresponding
operation has finished.

To provide a good user experience all potentially slow running operations in an Android
application should run asynchronously. This can be archived via concurrency constructs of the
Java language or of the Android framework. Potentially slow operations are for example network,
file and database access and complex calculations.

Android enforces a worst case reaction time of applications. If an activity does not react within 5 sec
system displays an Application not responding (ANR) dialog. From this dialog the user can choose t

1.2. Main thread


Android modifies the user interface and handles input events from one single thread, called
the main thread. Android collects all events in this thread in a queue and processes this queue with
an instance of the Looper class.

1.3. Threading in Android


Android supports the usage of the Thread class to perform asynchronous processing. Android
also supplies [Link] package to perform something in the background.
For example, by using the ThreadPools andExecutor classes.

If you need to update the user interface from a new Thread, you need to synchronize with the
main thread. Because of this restrictions, Android developer typically use Android specific code
constructs.

Android provides additional constructs to handle concurrently in comparison with standard Java.

You can use the [Link] class or the AsyncTasks classes. More sophisticated
approaches are based on theLoader class, retained fragments and services.

1.4. Providing feedback to a long running operation


If you are performing a long running operation it is good practice to provide feedback to the user
about the running operation.

You can provide progress feedback via the action bar for example via an action view.
Alternatively you can use aProgressBar in your layout which you set to visible and update it
during a long running operation. Non blocking feedback is preferred so that the user can continue
to interact with the applicatoin.

Avoid using the blocking ProgressBar dialog or similar approaches if possible. Prefer providing
interface stays responsive.

2. Handler
2.1. Purpose of the Handler class
A Handler object registers itself with the thread in which it is created. It provides a channel to
send data to this thread. For example, if you create a new Handler instance in
the onCreate() method of your activity, it can be used to post data to the main thread. The data
which can be posted via the Handler class can be an instance of the Message or
theRunnable class. A Handler is particular useful if you have want to post multiple times data to
the main thread.

2.2. Creating and reusing instances of Handlers


To implement a handler subclass it and override the handleMessage() method to process
messages. You can post messages to it via the sendMessage(Message) or via
the sendEmptyMessage() method. Use the post() method to send a Runnable to it.

To avoid object creation, you can also reuse the existing Handler object of your activity.

// Reuse existing handler if you don't


// have to override the message processing
handler = getWindow().getDecorView().getHandler();

The View class allows you to post objects of type Runnable via the post() method.

2.3. Example
The following code demonstrates the usage of an handler from a view. Assume your activity uses
the following layout.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="4dip" >
</ProgressBar>

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" >
</TextView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startProgress"
android:text="Start Progress" >
</Button>

</LinearLayout>

With the following code the ProgressBar get updated once the users presses the Button.

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class ProgressTestActivity extends Activity {


private ProgressBar progress;
private TextView text;

@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
progress = (ProgressBar)
findViewById([Link].progressBar1);
text = (TextView) findViewById([Link].textView1);

public void startProgress(View view) {


// do something long
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
doFakeWork();
[Link](new
Runnable() {
@Override
public void
run() {

[Link]("Updating");

[Link](value);
}
});
}
}
};
new Thread(runnable).start();
}

// Simulating something timeconsuming


private void doFakeWork() {
try {
[Link](2000);
} catch (InterruptedException e) {
[Link]();
}
}

3. AsyncTask
3.1. Purpose of the AsyncTask class
The AsyncTask class allows to run instructions in the background and to synchronize again with
the main thread. It also reporting progress of the running tasks. AsyncTasks should be used for
short background operations which need to update the user interface. .

3.2. Using the AsyncTask class


To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters
are the followingAsyncTask <TypeOfVarArgParams , ProgressValue ,
ResultValue>.

An AsyncTask is started via the execute() method. This execute() method calls
the doInBackground() and theonPostExecute() method.

TypeOfVarArgParams is passed into the doInBackground() method as input. ProgressValue is


used for progress information and ResultValue must be returned
from doInBackground() method. This parameter is passed toonPostExecute() as a
parameter.

The doInBackground() method contains the coding instruction which should be performed in
a background thread. This method runs automatically in a separate Thread.
The onPostExecute() method synchronizes itself again with the user interface thread and
allows it to be updated. This method is called by the framework once
the doInBackground() method finishes.

3.3. Parallel execution of several AsyncTasks


Android executes AsyncTask tasks before Android 1.6 and again as of Android 3.0 in sequence
by default. You can tell Android to run it in parallel with the usage of
the executeOnExecutor() method specifyingAsyncTask.THREAD_POOL_EXECUTOR as
first parameter.

The following code snippet demonstrates that.

// ImageLoader extends AsyncTask


ImageLoader imageLoader = new ImageLoader( imageView );

// Execute in parallel
[Link]( AsyncTask.THREAD_POOL_EXECUTOR,
"[Link] );

[NOTE}

The AsyncTask does not handle configuration changes automatically, i.e. if the activity is
recreated. The programmer has to handle that in his coding. A common solution to this is to
declare the AsyncTask in a retained headless fragment.

3.4. Example: AsyncTask


The following code demonstrates how to use the AsyncTask class to download the content of a
webpage.

Create a new Android project called [Link] with


an activity called ReadWebpageAsyncTask. Add
[Link] permission to your [Link] file.

Create the following layout.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:id="@+id/readWebpage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Load Webpage" >
</Button>

<TextView
android:id="@+id/TextView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Placeholder" >
</TextView>

</LinearLayout>

Change your activity to the following:

package [Link];

// imports cut out for brevity

public class ReadWebpageAsyncTask extends Activity {


private TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
textView = (TextView)
findViewById([Link].TextView01);
}

private class DownloadWebPageTask extends


AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls)
{
// we use the OkHttp library from
[Link]
OkHttpClient client = new
OkHttpClient();
Request request =
new [Link]()
.url(urls[0])
.build();
Response response =
[Link](request).execute();
if ([Link]()) {
return
[Link]().string();
}
}
return "Download failed";
}

@Override
protected void onPostExecute(String result) {
[Link](result);
}
}

public void onClick(View view) {


DownloadWebPageTask task = new
DownloadWebPageTask();
[Link](new String[] {
"[Link] });

}
}

Run your application and press the button. The defined webpage is read in the background. Once
this process is done your TextView is updated.

4. Background processing and


lifecycle handling
4.1. Retaining state during configuration changes
One challenge in using threads is to consider the lifecycle of the application. The Android system
may kill your activity or trigger a configuration change which will also restart your activity.

You also need to handle open dialogs, as dialogs are always connected to the activity which created
them. In case the activity gets restarted and you access an existing dialog you receive a View not
attached to window manager exception.

To save an object you can use the onRetainNonConfigurationInstance() method. This


method allows you to save one object if the activity will be soon restarted.
To retrieve this object you can use the getLastNonConfigurationInstance() method.
This way can you can save an object, e.g. a running thread, even if the activity is restarted.

getLastNonConfigurationInstance() returns null if the activity is started the first time


or if it has been finished via the finish() method.

onRetainNonConfigurationInstance() is deprecated as of API 13. It is recommended


that you use fragments and thesetRetainInstance() method to retain data over configuration
changes.

4.2. Using the application object to store objects


If more than one object should be stored across activities and configuration changes, you can
implement an Applicationclass for your Android application.

To use your application class assign the classname to the android:name attribute of your
application.

<application android:icon="@drawable/icon"
android:label="@string/app_name"
android:name="MyApplicationClass">
<activity android:name=".ThreadsLifecycleActivity"
android:label="@string/app_name">
<intent-filter>
<action
android:name="[Link]" />
<category
android:name="[Link]" />
</intent-filter>
</activity>
</application>

The application class is automatically created by the Android runtime and is available unless the
whole application process is terminated.

This class can be used to access objects which should be cross activities or available for the whole
application lifecycle. In the onCreate() method you can create objects and make them available
via public fields or getter methods.

The onTerminate() method in the application class is only used for testing. If Android
terminates the process in which your application is running all allocated resources are
automatically released.

You can access the Application via the getApplication() method in your activity.
5. Fragments and background
processing
5.1. Retain instance during configuration changes
You can use fragments without user interface and retain them between configuration changes via a
call to theirsetRetainInstance() method.

This way your Thread or AsyncTask is retained during configuration changes. This allows you
to perform background processing without explicitly considering the lifecycle of your activity .

5.2. Headless fragments


If you perform background processing you can dynamically attached a headless fragment to your
application and callsetRetainInstance() to true. This fragment is retained during
configuration changes and you can perform asynchronous processing in it.

6. Loader
6.1. Purpose of the Loader class
The Loader class allows you to load data asynchronously in an activity or fragment. They can
monitor the source of the data and deliver new results when the content changes. They also persist
data between configuration changes.

The data can be cached by the Loader and this caching can survive configuration changes.
Loaders have been introduced in Android 3.0 and are part of the compatibility layer for Android
versions as of 1.6.

6.2. Implementing a Loader


You can use the abstract AsyncTaskLoader class as the basis for your
custom Loader implementations.

The LoaderManager of an activity or fragment manages one or more Loader instances. The
creation of a Loader is done via the following method call.

# start a new loader or re-connect to existing one


getLoaderManager().initLoader(0, null, this);
The first parameter is a unique ID which can be used by the callback class to identify the Loader.
The second parameter is a bundle which can be given to the callback class for more information.

The third parameter of initLoader() is the class which is called once the initialization has been
started (callback class). This class must implement
the [Link] interface. It is common practice that an activity or
the fragment which uses a Loader implements
the [Link] interface.

The Loader is not directly created by the getLoaderManager().initLoader() method


call, but must be created by the callback class in the onCreateLoader() method.

Once the Loader has finished reading data asynchronously, the onLoadFinished() method of
the callback class is called. Here you can update your user interface.

6.3. SQLite database and CursorLoader


Android provides a Loader default implementation to handle SQlite database connections,
the CursorLoader class.

For a ContentProvider based on an SQLite database you would typically use


the CursorLoader class. This Loaderperforms the database query in a background thread so that
the application is not blocked.

The CursorLoader class is the replacement for Activity-managed cursors which are deprecated
now.

If the Cursor becomes invalid, the onLoaderReset() method is called on the callback class.

7. Exercise: Custom loader for


preferences
7.1. Implementation
In the following your create a custom loader implementation for managing preferences. On every
load the value of the preference is increased.

Create a project called [Link] with an activity


called MainActivity.

Create the following class as custom AsyncTaskLoader implementation for managing shared
preferences.
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class SharedPreferencesLoader extends


AsyncTaskLoader<SharedPreferences>
implements
[Link] {
private SharedPreferences prefs = null;

public static void persist(final


[Link] editor) {
[Link]();
}

public SharedPreferencesLoader(Context context) {


super(context);
}

// Load the data asynchronously


@Override
public SharedPreferences loadInBackground() {
prefs =
[Link](getContext());

[Link](this);
return (prefs);
}

@Override
public void onSharedPreferenceChanged(SharedPreferences
sharedPreferences,
String key) {
// notify loader that content has changed
onContentChanged();
}

/**
* starts the loading of the data
* once result is ready the onLoadFinished method is
called
* in the main thread. It loader was started earlier the
result
* is return directly
* method must be called from main thread.
*/
@Override
protected void onStartLoading() {
if (prefs != null) {
deliverResult(prefs);
}

if (takeContentChanged() || prefs == null) {


forceLoad();
}
}
}

The following example code demonstrates the usage of this loader in an activity.

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends Activity implements


[Link]<SharedPreferences>
{
private static final String KEY = "prefs";
private TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
textView = (TextView) findViewById([Link]);
getLoaderManager().initLoader(0, null, this);

@Override
public Loader<SharedPreferences> onCreateLoader(int id,
Bundle args) {
return (new SharedPreferencesLoader(this));
}
@SuppressLint("CommitPrefEdits")
@Override
public void onLoadFinished(Loader<SharedPreferences>
loader,
SharedPreferences prefs) {
int value = [Link](KEY, 0);
value += 1;
[Link]([Link](value));
// update value
[Link] editor = [Link]();
[Link](KEY, value);
[Link](editor);
}

@Override
public void onLoaderReset(Loader<SharedPreferences>
loader) {
// NOT used
}
}

7.2. Test
The LoaderManager call onLoadFinished() in your activity automatically after a
configuration change. Run the application and ensure that the value stored in the shared
preferences is increased at every configuration change.

8. Usage of services
You can also use Android services to perform background tasks.
See[Link] - Android service tutorial for
details.

9. Exercise: activity lifecycle and


threads
The following example will download an image from the Internet in a thread and displays a dialog
until the download is done. We will make sure that the thread is preserved even if the activity is
restarted and that the dialog is correctly displayed and closed.
For this example create a new Android project called [Link] with the
Activity calledThreadsLifecycleActivity . Also add the permission to use the Internet to
your [Link] file.

Your [Link] file should look like the following.

<?xml version="1.0" encoding="utf-8"?>


<manifest
xmlns:android="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<uses-permission android:name="[Link]"
>
</uses-permission>

<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".ThreadsLifecycleActivity"
android:label="@string/app_name" >
<intent-filter>
<action
android:name="[Link]" />

<category
android:name="[Link]" />
</intent-filter>
</activity>
</application>

</manifest>

Change the layout [Link] to the following.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="downloadPicture"
android:text="Click to start download" >
</Button>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="resetPicture"
android:text="Reset Picture" >
</Button>
</LinearLayout>

<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/icon" >
</ImageView>

</LinearLayout>

Now adjust your activity. In this activity the thread is saved and the dialog is closed if the activity
is destroyed.

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class ThreadsLifecycleActivity extends Activity {


// Static so that the thread access the latest attribute
private static ProgressDialog dialog;
private static Bitmap downloadBitmap;
private static Handler handler;
private ImageView imageView;
private Thread downloadThread;

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
// create a handler to update the UI
handler = new Handler() {
@Override
public void handleMessage(Message msg) {

[Link](downloadBitmap);
[Link]();
}

};
// get the latest imageView after restart of the
application
imageView = (ImageView)
findViewById([Link].imageView1);
Context context = [Link]();
[Link](context);
// Did we already download the image?
if (downloadBitmap != null) {

[Link](downloadBitmap);
}
// check if the thread is already running
downloadThread = (Thread)
getLastNonConfigurationInstance();
if (downloadThread != null &&
[Link]()) {
dialog = [Link](this,
"Download", "downloading");
}
}

public void resetPicture(View view) {


if (downloadBitmap != null) {
downloadBitmap = null;
}
[Link]([Link]);
}

public void downloadPicture(View view) {


dialog = [Link](this, "Download",
"downloading");
downloadThread = new MyThread();
[Link]();
}

// save the thread


@Override
public Object onRetainNonConfigurationInstance() {
return downloadThread;
}

// dismiss dialog if activity is destroyed


@Override
protected void onDestroy() {
if (dialog != null && [Link]()) {
[Link]();
dialog = null;
}
[Link]();
}

// Utiliy method to download image from the internet


static private Bitmap downloadBitmap(String url) throws
IOException {
HttpUriRequest request = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response =
[Link](request);

StatusLine statusLine =
[Link]();
int statusCode = [Link]();
if (statusCode == 200) {
HttpEntity entity =
[Link]();
byte[] bytes =
[Link](entity);

Bitmap bitmap =
[Link](bytes, 0,
[Link]);
return bitmap;
} else {
throw new IOException("Download failed,
HTTP response code "
+ statusCode + " - " +
[Link]());
}
}

static public class MyThread extends Thread {


@Override
public void run() {
try {
// Simulate a slow network
try {
new
Thread().sleep(5000);
} catch (InterruptedException e)
{
[Link]();
}
downloadBitmap =
downloadBitmap("[Link]
69/DV11");
// Updates the user interface
[Link](0);
} catch (IOException e) {
[Link]();
} finally {

}
}
}

}
Run your application and press the button to start a download. You can test the correct lifecycle
behavior by changing the orientation in the emulator via the Ctrl+F11 shortcut.

It is important to note that the Thread is a static inner class. It is important to use a static inner
class for your background process because otherwise the inner class will contain a reference to the
class in which is was created. As the thread is passed to the new instance of your activity this
would create a memory leak as the old activity would still be referred to by the Thread.

Common questions

Powered by AI

A Handler in Android is used for sending and processing Message and Runnable objects associated with a thread's MessageQueue. It is useful for scheduling messages to be executed on the thread that created the handler. It allows communication back to the main thread from background threads, facilitating UI updates. Unlike directly using Threads, which requires synchronization for UI updates, Handlers provide a simple way to post work to run on the main thread, simplifying the process of managing UI updates from background processes .

The Loader framework is optimal in scenarios where data persistence across configuration changes and efficient management of query results are needed. Loaders allow asynchronous loading of data and automatically reconnect to the last loader's cursor after configuration changes like rotation, without losing the current data. This persistence is managed by the LoaderManager, making it more effective for data loading in activities with frequent configuration changes compared to AsyncTask, which does not handle such changes automatically .

The AsyncTask class allows background operations by running instructions on a separate thread, and facilitates synchronization with the main thread using its doInBackground() and onPostExecute() methods. The doInBackground() method performs operations in the background thread, while the onPostExecute() method is used to update the UI once the background operation is complete. This ensures that UI updates occur on the main thread .

The Application class in Android can be used to retain data across the whole application lifecycle by implementing it to hold shared states or configurations. It is created when the first component of the application is started and destroyed when the system removes the process. By creating global objects within the Application class, they remain accessible throughout the app's lifecycle, overcoming activity and fragment lifecycle constraints. This approach ensures that objects needed across different activities and fragments are retained across configuration changes and app restarts .

The benefits of using AsyncTask for parallel execution of tasks include simplifying the management of background threads and interaction with the main thread, as it allows easy updates to the UI after background tasks are complete. Parallel execution can be achieved using executeOnExecutor(), making it possible to execute multiple tasks concurrently using the THREAD_POOL_EXECUTOR. However, limitations include handling configuration changes, as AsyncTask does not automatically manage these, requiring additional coding to ensure task continuity after activity recreation .

Fragments in Android can manage lifecycle challenges associated with background processing by using their setRetainInstance(true) feature, which retains the fragment instance across configuration changes. This allows retaining threads or AsyncTasks across Activity destruction and recreation cycles, ensuring background tasks continue uninterrupted. Retained fragments act as a headless fragment without a UI, maintaining background tasks or data that survive beyond activity lifecycle changes, thus offering a clean and efficient method for handling such challenges .

The Looper class in Android is used to run a message loop for a thread, where it processes messages from a queue. The Handler is used to place them in the Looper's message queue. Looper allows a thread to loop through messages and execute them. Together, they manage long-running operations by processing work scheduled on the message queue, facilitating asynchronous task execution while ensuring the thread can handle these operations without blocking the UI. This provides a mechanism to execute long-running tasks on background threads and update the UI by re-posting messages back to the main thread for UI updates .

One of the main challenges developers face when using threads in conjunction with the Android activity lifecycle is handling configuration changes, such as screen rotations, which can restart an activity. If a thread is not managed properly, it can lead to memory leaks or exceptions. Such changes can also cause open dialogs that are connected to the activity to throw a View not attached to a window manager exception. To mitigate these challenges, developers can use the onRetainNonConfigurationInstance() method to save state, although it's deprecated in API 13, and it is recommended to use retained fragments for saving state across these changes .

To improve responsiveness during network operations in an Android application, implement network operations in background threads using AsyncTask, Loader, or background services to avoid blocking the main thread. Make use of caching strategies to reduce redundant network calls and apply optimizations such as efficient data parsing and reducing payload size. Implementing a user feedback mechanism, such as ProgressDialog, can also enhance user experience. Proper error handling and retries can improve perceived responsiveness when network conditions are poor .

To maintain the progress of a Thread even if the activity is destroyed and recreated, developers can use retained fragments or the onRetainNonConfigurationInstance() method to persist the thread across activity lifecycle changes. Another strategy is to store the thread-related data in a static inner class or an Application class object, preventing the activity from holding a direct reference to it and reducing memory leaks by retaining thread state independent of the UI lifecycle. Implementing background services for longer tasks that need to persist outside UI lifecycles is also a viable option .

You might also like