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
Follow this method. Using this way you can simply update the UI from a background thread. runOnUiThread work on the main(UI) thread . I think this code snippet is less complex and easy, especially for beginners.
AsyncTask.execute(new Runnable() {
@Override
public void run() {
//code you want to run on the background
someCode();
//the code you want to run on main thread
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
/*the code you want to run after the background operation otherwise they will executed earlier and give you an error*/
executeAfterOperation();
}
});
}
});
in the case of a service
create a handler in the oncreate
handler = new Handler();
then use it like this
private void runOnUiThread(Runnable runnable) {
handler.post(runnable);
}