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
So most handy is to do sort of:
import android.os.AsyncTask
import android.os.Handler
import android.os.Looper
object Dispatch {
fun asyncOnBackground(call: ()->Unit) {
AsyncTask.execute {
call()
}
}
fun asyncOnMain(call: ()->Unit) {
Handler(Looper.getMainLooper()).post {
call()
}
}
}
And after:
Dispatch.asyncOnBackground {
val value = ...// super processing
Dispatch.asyncOnMain { completion(value)}
}
A condensed code block is as follows:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// things to do on the main thread
}
});
This does not involve passing down the Activity reference or the Application reference.
Kotlin Equivalent:
Handler(Looper.getMainLooper()).post(Runnable {
// things to do on the main thread
})
With Kotlin, it is just like this inside any function:
runOnUiThread {
// Do work..
}
More precise Kotlin code using handler :
Handler(Looper.getMainLooper()).post {
// your codes here run on main Thread
}
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);
}
public void mainWork() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//Add Your Code Here
}
});
}
This can also work in a service class with no issue.