Android basics: running code in the UI thread

后端 未结 7 533
悲&欢浪女
悲&欢浪女 2020-11-22 11:55

In the viewpoint of running code in the UI thread, is there any difference between:

MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
         


        
7条回答
  •  囚心锁ツ
    2020-11-22 12:23

    The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.

    TextViewUpdater textViewUpdater = new TextViewUpdater();
    Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
    private class TextViewUpdater implements Runnable{
        private String txt;
        @Override
        public void run() {
            searchResultTextView.setText(txt);
        }
        public void setText(String txt){
            this.txt = txt;
        }
    
    }
    

    It can be used from anywhere like this:

    textViewUpdater.setText("Hello");
            textViewUpdaterHandler.post(textViewUpdater);
    

提交回复
热议问题