Approaches to Multitasking in Android

Hello all on the interwebz, just want to share a few things regarding approaches to multitasking in Android. You should perform multitasking in order not to block the UI thread if you have an application that requires long asynchronous operations
The first way is to use the AsyncTask class provided by the Android API. Using this class is very straightforward, have a look at the Photostream sample application provided by Google.
The second way is to create your own message handler in a Thread, Handler instantiation is sandwiched between prepare and loop calls so that the handler will reference the looper. Here’s how to do it:

class MyThread extends Thread{
public Handler h ;
public void run() {
super.run();
Looper.prepare();  
//handler will reference this looper
h = new Handler(){
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
}
Looper.loop();
}           
};

You can queue a runnable in message queue of the handler:

MyThread mt0 = new MyThread();
mt0.h.postRunnable(new Runnable(){...});

Or you can send a message to be processed by the handler:

mt0.h.sendEmptyMessage(1234);

The third way is to broadcast an Intent from your activity and having a receiver on the ApplicationContext, note that BroadcastReceivers run on the main Thread so there is an extra work in spawning a separate thread in BroadcastReceivers, or you can call a message processing queue like in 2nd method:

MyThread mt = new MyThread();
public static final String INTENT_EAT_PIZZA = "org.mycompany.intent.action.eat_pizza";
class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Message m = mt.h.obtainMessage();
Bundle b = m.getData();
b.putString("ACTION", action);
m.sendToTarget();

}
public void selfRegister(Context ctx){
IntentFilter filter = new IntentFilter(INTENT_EAT_PIZZA);
ctx.registerReceiver(this, filter);
}
};

Looper.prepare()

Lastly, in some complex applications, the more preferable approach is to use either an IntentService and/or Service. I will post a tutorial on how to use IntentService and Service later on.


About this entry