Reputation: 5380
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.
Upvotes: 10
Views: 15263
Reputation: 31744
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.
Upvotes: 8
Reputation: 8154
If you used the Command design pattern, and made a generic AsyncTask that could run your "command" objects, you would need only one class for each task and the one generic AsyncTask to execute them all. You could even go so far as to make a generic "command" that executed a method via reflections or some pre-defined interface method.
Upvotes: 0