Bharath Kumar
Bharath Kumar

Reputation: 541

Running a timer in background and inform main(UI) thread when it completes in android app

Is it possible to run a timer in background and inform main thread (say a fragment) when it completes? In below code does onTick and onFinish run on main thread? If not then will AyncTask be helpful to inform to main thread upon completion of timer?

new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

Upvotes: 0

Views: 118

Answers (1)

Nicholas Ackerman
Nicholas Ackerman

Reputation: 401

There are many ways to run a timer in the background that informs the the main thread when the timer completes. Services, AsyncTask, and threads could all be used here. See this SO post for different strategies:

Difference between Service, Async Task & Thread?

Without knowing more about your use case, I'd recommend first looking into AsyncTask as it comes with predefined callbacks to ease communication back to the main thread.

This SO post outlines how to use an AsynTask:

AsyncTask Android example

Upvotes: 1

Related Questions