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

13,100

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.

Share:
13,100
Misha
Author by

Misha

Senior iOS developer @ Coolvision.

Updated on July 20, 2022

Comments

  • Misha
    Misha almost 2 years

    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.

  • Misha
    Misha about 11 years
    This still looks pretty much code for executing one method asynchronously. Need to create class which implements Command for each method?
  • Jatin
    Jatin about 11 years
    Internally, the UI thread keeps looping through its looper (i.e. it waits for Runnables added to its looper. If found one it takes it and then runs it. That is is how it runs your application for all mouse events, ui updates etc). So in your application, your normal thread does processing and only whatever has to be updated in UI, is sent to the looper of UI thread. Thus simplifying the whole process.
  • CodeChimp
    CodeChimp about 11 years
    You could use the pattern to create a "command" that executes an arbitrary method on any object via Reflections. Or you could create one that is specific to each particular object. Or, you could create an interface (or use something like Runnable) to and make a command that executes against that interface. There are probably other patterns you could use, but the point being you can get as fancy as you want, but there are trade offs for each.