Best way to execute a method asynchronously in Android (compact and correct)

Let's say I have an activity showing some content on the screen. I need to execute some method (asyncMethod) asynchronously, and when this is done, I need to update the data on the screen. What is the most correct and easiest way to do this?

Currently, the easiest way I know is to use a stream:

new Thread(new Runnable() { public void run() { asyncMethod(); } }).start(); 

I am familiar with AsyncTask, but it is more complicated than using a thread, and for each method that I need to run asynchronously, I need to create a new AsyncTask, while this greatly increases the size of the code.

I thought of some kind of general AsincTask that receives a method as a parameter and how it executes it, but as far as I know, in Java it is impossible to pass methods as parameters.

In other words, I'm looking for the most compact (but correct) way to execute methods asynchronously.

+6
source share
2 answers

Handler and Looper .

In most cases, hold the handler in the Looper UI thread, and then use it to send the Runnable . For instance:

 Handler h = new Handler(); //later to update UI h.post(new Runnable(//whatever); 

PS: Handler and Looper are awesome. So much so that I redid them for Java.

+3
source

If you used the Command design template and created a generic AsyncTask that could run your "command" objects, you only need one class for each task and one generic AsyncTask to execute them. You can even go so far as to create a common β€œcommand” that executes a method using reflections or some predefined interface method.

0
source

Source: https://habr.com/ru/post/944032/


All Articles