In an android service I have created thread(s) for doing some background task.
I have a situation where a thread needs to post certain task on main thread\'s message
HandlerThread is better option to normal java Threads in Android .
requestHandlerpost a Runnable task on requestHandlerCommunication with UI Thread from HandlerThread
Handler with Looper for main thread : responseHandler and override handleMessage methodRunnable task of other Thread ( HandlerThread in this case), call sendMessage on responseHandlersendMessage result invocation of handleMessage in responseHandler.Message and process it, update UIExample: Update TextView with data received from a web service. Since web service should be invoked on non-UI thread, created HandlerThread for Network Operation. Once you get the content from the web service, send message to your main thread (UI Thread) handler and that Handler will handle the message and update UI.
Sample code:
HandlerThread handlerThread = new HandlerThread("NetworkOperation");
handlerThread.start();
Handler requestHandler = new Handler(handlerThread.getLooper());
final Handler responseHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
txtView.setText((String) msg.obj);
}
};
Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
Log.d("Runnable", "Before IO call");
URL page = new URL("http://www.your_web_site.com/fetchData.jsp");
StringBuffer text = new StringBuffer();
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
String line;
while ((line = buff.readLine()) != null) {
text.append(line + "\n");
}
Log.d("Runnable", "After IO call:"+ text.toString());
Message msg = new Message();
msg.obj = text.toString();
responseHandler.sendMessage(msg);
} catch (Exception err) {
err.printStackTrace();
}
}
};
requestHandler.post(myRunnable);
Useful articles:
handlerthreads-and-why-you-should-be-using-them-in-your-android-apps
android-looper-handler-handlerthread-i