Handler-Looper implementation in Android

前端 未结 2 1043
礼貌的吻别
礼貌的吻别 2021-01-14 07:01
  1. I have Activity with Handler (UI thread)
  2. I start new Thread and make handler.post(new MyRunnable()) - (new work thread)

Android documentation s

相关标签:
2条回答
  • 2021-01-14 07:23

    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).

    0 讨论(0)
  • 2021-01-14 07:27

    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();
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题