mobiledev Alex
mobiledev Alex

Reputation: 2318

Handler-Looper implementation in Android

  1. I have Activity with Handler (UI thread)
  2. I start new Thread and make handler.post(new MyRunnable()) - (new work thread)

Android documentation said about post method: "Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached."

Handler attached to UI thread. How android can run runnable in the same UI thread without new thread creation?

Is new thread will be created using Runnable from handler.post()? Or it's only run() method will be called from Runnable subclass?

Upvotes: 3

Views: 3962

Answers (2)

Cephron
Cephron

Reputation: 1587

Here's a rough pseudroidcode example of how to use handlers - I hope it helps :)

class MyActivity extends Activity {

    private Handler mHandler = new Handler();

    private Runnable updateUI = new Runnable() {
        public void run() {
            //Do UI changes (or anything that requires UI thread) here
        }
    };

    Button doSomeWorkButton = findSomeView();

    public void onCreate() {
        doSomeWorkButton.addClickListener(new ClickListener() {
            //Someone just clicked the work button!
            //This is too much work for the UI thread, so we'll start a new thread.
            Thread doSomeWork = new Thread( new Runnable() {
                public void run() {
                    //Work goes here. Werk, werk.
                    //...
                    //...
                    //Job done! Time to update UI...but I'm not the UI thread! :(
                    //So, let's alert the UI thread:
                    mHandler.post(updateUI);
                    //UI thread will eventually call the run() method of the "updateUI" object.
                }
            });
            doSomeWork.start();
        });
    }
}

Upvotes: 5

CommonsWare
CommonsWare

Reputation: 1007554

Handler attached to UI thread.

Correct.

How android can run runnable in the same UI thread without new thread creation?

Any thread, including the main application ("UI") thread, can call post() on Handler (or on any View, for that matter).

Upvotes: 3

Related Questions