简体   繁体   中英

Best way to execute a thread after a period of time in android

I am having a service in my application that puts a runnable (in another java file) in a thread and starts it. That is working fine for once, but i want it to be repetitive due to a certain period. I need a good way to handle that. Reason why I didn't use the answers to other questions is that I don't want it to repeat infinity nor I know how many times it'll repeat the task. It'll simply stop due to a button click in the UI.

I was thinking of using a loop with a sleep and if statement. But I think that's really bad design for my application. Is there a standard way for doing such thing?

Thanks...

You can use a handler that somehow acts like a timer but I think it is better for your situation.

You initialize it like this:

Handler delayhandler = new Handler();

Set the time it fires like this (in ms):

delayhandler.postDelayed(mUpdateTimeTask, 500);

And it calls this:

private Runnable mUpdateTimeTask = new Runnable()
{   public void run()
    {   // Todo

        // This line is necessary for the next call
        delayhandler.postDelayed(this, 100);
    }
}

You can also remove the next call with:

delayhandler.removeCallbacks(mUpdateTimeTask);

Use a TimerTask and have it execute your thread/method.

http://android.okhelp.cz/timer-simple-timertask-java-android-example/

http://developer.android.com/reference/java/util/TimerTask.html - You can use the Cancel() method to stop the TimerTask from executing.

使用计时器,它将在给定的时间段后运行线程,而要停止时,只需停止计时器或将其设置为无限时间段即可。

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