开发者

Various ways to handle timing in Android

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 s开发者_StackOverflow中文版ay 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.


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();


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜