简体   繁体   中英

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.

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.

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 ie I would think there's a better way.

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