thread

Interrupting/cancelling threads

SDK Version: 
M3

threadWhen you run a background operation using a Thread, or AsyncTask in most of the times it is needed to be able to interrupt it.
In lot of cases, when the user starts a sceen in our application, a thread is started in the background, to load its content. Hoever if the user leaves the screen before its loading is complete, the loading process should be interrupted. Even if the loading prosess can not be interrupted immediately, or it would be too mutch troube, it shold detect that the display of the result is no longer needed.

So how do you stop a thread exactly? You can see in the documentation that Thread class has a stop() method. This method offered an "easy" way to interrupt threads in older android versions, by killing the thread. It is deprecated now, do not use it, it may left things in inconstent state, among other problems, so this was an unelegant way.

How to run background jobs using threads

SDK Version: 
M3

Previously I wrote about, that slow operations must be runned in threads. Now I would like to present some example code, how to use threads in Android.

Under the android system an user interface element can only be accessed from the thread that created it (the main UI thread). Thats where handlers and messages come in.

The user interface defines a handler like below:

  1. Handler handler = new Handler() {
  2.   @Override
  3.   public void handleMessage(Message msg) {
  4.     int arg1=msg.arg1;
  5.     int arg2=msg.arg2;
  6.     MyClass myObject=(MyClass)msg.obj;
  7.     //do something in the user interface to display data from message
  8.   }
  9. }

Then the thread, which can not touch the user interface, sends a message to this handler instead.

The following example code, that implements file downloading from net, represents how I usually use the threads:

  1. public class Downloader {
  2.   Thread thread=null;
  3.   boolean interrupted=false;

Speeding up android applications

SDK Version: 
M3

First of all, define what do we mean under "speed": in one hand its the time that the code needs to execute, on the other hand its the time the user needs to wait for the user interface. The two things can greatly differ, of course you must optimize the code performance, but the most important is what the user sees from it. Don't make the user wait, unless its necessary.

Do not pull back the ui thread
The very basic principle is to never run slow operations on the user interface thread! If you do this the interface will freeze until the operation is executed, which is not a nice user experience. If the execution takes too long the android system will detect it and offer the opportunity to the user to force close the frozen application:

Using threads and ProgressDialog

SDK Version: 
M5

This example shows you how to properly use a thread to do work while displaying an indeterminate ProgressDialog.

Syndicate content