Say I have an Activity showing some content on screen. I need to execute some method (asyncMethod) asynchronously and when it is done, I need to update data on screen. What is the most correct and simple way to do this?
Currently the most simple way I know is using thread:
new Thread(new Runnable() {
public void run() {
asyncMethod();
}
}).start();
I'm familiar with AsyncTask, but it is more complex than using thread and for each method i need to run asynchronously there is a need to create new AsyncTask while this is greatly increases code size.
I thought about some generic AsincTask which gets method as a parameter and than executes it, but as far as i know it is impossible in Java to pass methods as parameters.
In other words I'm looking for most compact(but correct) way to execute methods asynchronously.
Handler
and Looper
.
Most of the times, keep the Handler to the Looper
of UI thread and then use it to post Runnable
. For example:
Handler h = new Handler();
//later to update UI
h.post(new Runnable(//whatever);
PS: Handler
and Looper
are awesome. So much that I remade them for Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With