Handler-Looper implementation in Android

前端 未结 2 1044
礼貌的吻别
礼貌的吻别 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: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();
            });
        }
    }
    

提交回复
热议问题