Login     Sign Up
Tugadar (@admin)
15 days ago
9 Views

To ensure that your applications remain responsive, it’s good practice to move all slow, time-consuming operations off the main application thread and onto a child thread.

All Android application components — including Activities, Services, and Broadcast Receivers — run on the main application thread. As a result, time-consuming processing in any component will block all other components including Services and the visible Activity.

Using background threads is vital to avoid the “Application Unresponsive” Dialog box described in Chapter 2. Unresponsiveness is defined in Android as Activities that don’t respond to an input event (such as a key press) within 5 seconds and Broadcast Receivers that don’t complete their onReceive handlers within 10 seconds.

Not only do you want to avoid this scenario, you don’t want to even get close. Use background threads for all time-consuming processing, including file operations, network lookups, database transactions, and complex calculations.

Creating New Threads

You can create and manage child threads using Android’s Handler class and the threading classes available within java.lang.Thread. The following skeleton code shows how to move processing onto a child thread:

This method is called on the main GUI thread.

private void mainProcessing() {

This moves the time consuming operation to a child thread.

Thread thread = new Thread(null, doBackgroundThreadProcessing, “Background”); thread.start();

}

Runnable that executes the background processing method.

private Runnable doBackgroundThreadProcessing = new Runnable() {

public void run() { backgroundThreadProcessing();

}

};

Method which does some processing in the background.

private void backgroundThreadProcessing() {

[ ... Time consuming operations ... ]

}