简体   繁体   中英

Performance - Updating UI from timer thread without blocking UI thread

I'm new to android and have been doing some reading about worker threads and not blocking the UI thread. I'm playing around with a simple timer app that starts a thread that updates a textview every second when the activity is created. So my question is, these days what is the best way to do this. Both of the two examples below work but is there a better (more efficient/ more Android) way?

    final Handler handler = new Handler();

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            seconds++;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                     secondsTextView.setText(seconds);
                }
            });
            handler.postDelayed(this, 1000);
        }
    }, 1000);

or

    new Thread(){
        @Override
        public void run(){
            try{
                while(!isInterrupted()){
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            seconds++;
                            secondsTextView.setText(seconds);
                        }
                    });
                }
            }catch(Exception e){
                Log.e("Activity1", e.toString());
            }
        }
    }.start();

The more efficient way is:

    timeOnTextView.postDelayed(new Runnable() {
      @Override
      public void run() {
        seconds++;
        timeOnTextView.postDelayed(this, 1000);
      }
    }, 1000);

The run() of the Runnable passed to postDelayed() is invoked on the main application thread, so you do not need to use runOnUiThread() .

Since postDelayed() is implemented on View , you do not need a Handler .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM