Various ways to handle timing in Android

2020-04-14 08:54发布

问题:

I have a need for a very simplistic way to keep track of time. Basically I simply need to start a timer when a method is called, and a set amount of time after that (45-90 seconds) call another method.

From what I have read, Handlers are the most efficient way to handle keeping track of time. However, some say they require a second thread, while others say they don't. It's certainly not a huge deal, but I would prefer to keep things as minimalistic as possible. So, is there any way to do something like simply checking to see if System.getCurrentTimeMillis is a certain amount higher than it was when the user called the first method, without any further user interaction of course.

If not I will just read into Handlers more and work with those. Thank you for your help.

回答1:

After you call your first method you call the second method after 90 seconds with:

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            //here call the second method

            }   

}, 90000);

However, if the user clicks on return and leave the activity, this postdelayed runnable will restart the activity, hence you need to put an if statement in it to check if that activity is still running...

If you need to monitor how much time has passed every 1 second before the timer has ended then you can use this code

new CountDownTimer(90000, 1000) { 

    public void onTick(long millisUntilFinished) { 
        //call to my UI thread every one second 
    } 

    public void onFinish() { 
        //final call to my UI thread after 90 seconds
    } 
 }.start();


回答2:

I would use a TimerTask and the method postDelayed. For a good description see here:

http://android-developers.blogspot.com/2007/11/stitch-in-time.html