Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 295
Misha Avatar asked May 01 '13 11:05

Misha


1 Answers

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.

like image 50
Jatin Avatar answered Nov 15 '22 17:11

Jatin