user1367713
user1367713

Reputation: 286

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.

Upvotes: 0

Views: 530

Answers (1)

Nicola Gallazzi
Nicola Gallazzi

Reputation: 8705

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

Upvotes: 1

Related Questions