Handler threads
Handler threads are a powerful tool to complete task in android. Handler threads were introduced in android in api level 1.
A handler thread can be seen as the brother of async threads in android since they both share the same parent class threads. Handler threads and async threads are alike in that they both run in the background on their own threads hence their name.
Handler threads are commonly used for long running networking tasks the developer will need to execute as opposed to Async threads which are used for short term task the developer will need to execute.
Now what comprises a class that extends the Handler thread class ?
- A tag used to distinguish the thread from other threads.
- A looper that post messages on the threads message queue and pulls of messages of the threads message que.
- An implementation of the Handler thread method public void HandleMesage(Message msg). This is where networking task must be done in a class that extends HandlerThread.
So lets start with 1. A tag that is used to distinguish the thread from other threads:
first we must make a class as such:
public class ExampleThread Extends HandlerThread{
}
second we must add a constructor that takes in a string which will be used to distinguish the thread from other threads
public class ExampleThread Extends HandlerThread{
public ExampleThread(String tag){
super(tag);
}
}
Third we must add an instance of handler since each Handler thread has a handler that post messages on the threads message queue and handles them as well.
public class ExampleThread Extends HandlerThread{
private Handler handler; // Added this
public ExampleThread(String tag){
super(tag);
handler = new Handler(getLooper());
}
}
Remember each thread has its own looper that post messages on the threads message que and pulls them of to be handled as well. So each handler needs a looper so that it can receiver and post messages on the threads message queue so that is why when we assign the handler to a new instance we pass in the Handler threads Looper.
Next we much write our own implementation of the handlers handleMessage method:
public class ExampleThread Extends HandlerThread{
private Handler handler; // Added this
public ExampleThread(String tag){
super(tag);
handler = new Handler(getLooper()){
@override
public void handleMessage(Message msg)
{
//your own implementation will go here
}
}}
}
So that is how we write a thread that extends Handler thread. Now you are asking what do I mean by own implementation?
What I mean by that is that any networking code that retrieves information in whatever manner can go there or any other code you need to be handled in a separate thread that cant be executed in the main thread or do not want to execute in the main thread.
