Step 1. Isolate your network calls with a thread call.
Its assumed at this point that you already have an Android app that is making network calls. So first go through your code and surround all of them with a block of code that looks like this. Essentially change thismakeNetworkCall();
new Thread(new Runnable() { @Override public void run() { makeNetworkCall(); } }).start();
Step 2. The Handler
Behind the scenes is a Java class call the Handler. This little class can be used build a sort of callback in your main UI Thread so the new threads will have some way to notify it when they are done. To use it add this bit of code to your Activity class.private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { updateTheUI(); //This method is for whatever needs to happen after the network call is complete } };
handler.sendEmptyMessage(0);
Step 3. Smarter Messages
If you want to send a better message than just update, you need to figure out how many types of messages you want and what they should be. They have to be integer values so it would make the most sense to create a bunch of constants in the class to represent these calls. For instance…private static final int REDRAW = 42;
private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if(msg.what == REDRAW) { updateTheUI(); //This method is for whatever needs to happen after the network call is } } };
handler.sendEmptyMessage(REDRAW);
In conclusion
Use a handler when you want to spin off new threads too keep the UI Experience responsive. If you have lots of threads going, then create some custom callback messages. This will make all of your apps feel instantly responsive.Posted in: Android, Java, Mobile Development