采用的是Android那里只在有限的时间运行任务的efficent方式?目前,我用onPostDelayed(处理程序),并检查每次运行,如果当前时间戳比我的predefined时间戳高。
Is there in Android an efficent way to run a task only for a limited time? Currently I use a Handler with onPostDelayed() and check each run if the current timestamp is higher than my predefined timestamp.
我在寻找像 CountdownTimer 但没有刻度的解决方案。我只希望定义一个开始和结束时间,我的任务应该在这个时期进行。
I'm searching for a solution like CountdownTimer but without ticks. I only want define a start and endtime and my task should perform in this period.
如果我想运行一个任务的具体时间为我节省启动时间变成了'长',像这样:
If I want to run a task for a specific time I save the time it starts into a 'long' like so:
long now = System.currentTimeMillis();
,然后简单地检查自启动任务(假设它是某种形式的循环),而它正在运行,所以如果我想运行的东西,持续5秒已经多久了:
And then simply check how long it has been since the task started (assuming it is a loop of some kind) while it is running so if I wanted to run something for 5 seconds:
long now = System.currentTimeMillis();
int runtime=5000;//in milliseconds
do
{
//enter your code here
}while (now+runtime<System.currentTimeMillis());