简体   繁体   中英

Restarting a timer in the onResume() method?

Im using a Timer to continuously update a TextView , but I'm having trouble restarting the timer during the onResume() method. I use timer.cancel() in the onPause() and onDestroy() methods, but how do I restart the timer in onResume() ?

This is my timer code...

int delay = 1000; 
int period = 1000; 
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

public void run() {
        //I update the TextView here 
    }

}, delay, period);

An easier alternative is to use the Handler class. I wouldn't recommend the Timer class because it has no bearing on the life cycle of your Activity and you will have to worry about any potential threading problems yourself. The beauty of using the Handler is that all your callbacks will be on the main thread (so no threading issues to worry about). The following is a simple example on how to do this.

 @Override
protected void onCreate(Bundle savedInstanceState)
{
   ....
   mHandler = new Handler();
}

 @Override
protected void onResume() 
{
     mHandler.postDelayed(myRunnable, UPDATE_RATE);
}

 @Override
protected void onPause() 
{
     mHandler.removeCallbacks(myRunnable);
}

 private final Runnable myRunnable= new Runnable() {
    @Override
    public void run()
    { 
       //Do task
       mHandler.postDelayed(myRunnable, UPDATE_RATE);
    }
 }

You dont restart the timer. Instead use a new timer ie inside onResume() create a new timer. As you are no longer using the previous one, garbage collection will take care of it. So in onResume() use the following code:

timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

public void run() {

    //update the TextView here 

}

}, delay, period);

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