Shreyash Mahajan
Shreyash Mahajan

Reputation: 23596

Android: how to use SystemClock.elapsedRealtime() to show second one by one?

I am using the SystemClock.elapsedRealtime() to display the time.

But now I want to show the seconds one-by-one to be increase based on the SystemClock.elapsedRealtime() time.
And yes I must use the thred.

So how to do it ?

I have tried it with this thread:

// Start lengthy operation in a background thread
progressThread = new Thread(new Runnable() {

    public void run() {
        while (mProgressStatus < 1000) {
            mProgressStatus = ((int) (SystemClock.elapsedRealtime() / 10));
            // Update the progress bar
            mHandler.post(new Runnable() {

                public void run() {   
                    // try {
                    //  // progressThread.sleep(1000);
                    // } catch (InterruptedException e) {
                    //  // TODO Auto-generated catch block
                    //  e.printStackTrace();
                    // }
                    // progressBar.setProgress(mProgressStatus);
                    System.out.println("SECOND is :" + mProgressStatus);
                }
            });
        }
    }
});

So what should I change in this thread to get seconds one by one to be increased ??

Please help me for this.

Thanks.

Upvotes: 0

Views: 7839

Answers (2)

hovanessyan
hovanessyan

Reputation: 31463

You can use the Chronometer class. You can bind it to SystemClock.elapsedRealtime() using setBase(). Another way could be if you use Handler inside an Activity and using the sendEmptyMessageDelayed() method with value 1000 to update your timer.

Upvotes: 1

D-Dᴙum
D-Dᴙum

Reputation: 7890

If you want to use a second thread to get the elapsed time (as you have done) then you MUST employ some method to notify your Activity's main thread that the canvas must be re-painted, as mentioned here and in here.

You could also employ a Handler which has been instantiated in your Activities Main thread. From your second thread (which gets the system time) you send a Message which contains the system time to the Handler. Because the Handler runs in the Main thread it is safe to alter Views from here. I would doubt that this is an accurate way of displaying system time on Android i.e. I would think there's a better way.

Upvotes: 1

Related Questions