简体   繁体   中英

background thread how to update UI periodically

How to run background thread correctly or run timer to update UI every 1 second? I mean when a activity is paused thread should be paused, when activity resumed thread or timer should be resumed and every second data must be updated on UI.

You can use HandlerThread class to create the thread, like below:

HandlerThread handlerThread = new HandlerThread("MyHandler");
handlerThread.start();
Looper looper = handlerThread.getLooper();
Handler handler = new Handler(looper);

After that, launch your runnable this way:

  handler.postDelayed(() -> {
            // runnable code here

            // call again thread after 1000 millis
            handler.postDelayed(this, 1000);
        }, 1000);

HandlerThread class, as every class in java, inherits from Object class that has wait() method. If you check the documentation, it says "Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object." You should pause the thread by calling handlerThread.wait() according to your activity lifecyle, for example inside onPause() method. Remember to call notify() on the same thread instance when your activity is resumed, typically inside onResume() method. Call handler.removeCallbacks when you're done :)

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