我初始化了一个int变量i = 0
。我的代码有一个无限的while循环,在活动开始时立即检查。在这个循环中,我需要在一段时间间隔(例如3秒)之后执行某些任务。我的代码与此类似:
while(1){
if (System.currentTimeMillis() - learningTime > 3000) {
learningTime = System.currentTimeMillis();
i++;
}
}
由于System.currentTimeMillis() - learningTime > 3000
在我的程序执行开始时为真,i
将快速增加到1
,之后将每3秒增加一次。
如何在活动开始后3秒内强制i
从0
增加到1
?
答案 0 :(得分:2)
为LearningTime分配System.currentTimeMillis()值,使其为0> 3000
learningTime = System.currentTimeMillis()
而且,无论如何,你将使用此代码阻止主线程。
这可以是Handler的一个例子
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run()
{
handler.postDelayed(this, 3000);
}
};
handler.postDelayed(runnable, 3000);
Handler class
Runnable
Handler postDelayed
无论如何,您不再需要learningTime
和i
(?)
答案 1 :(得分:1)
您可以使用处理程序来解决此问题,以便您不会阻止主线程。 我不确定这是否是理想的实现方式:
private static final long INTERVAL = 3000;//3 seconds
private Handler handler;
protected void onCreate(Bundle b)
{
super(b);
handler = new Handler();
//post an action to execute after an INTERVAL has elapsed.
handler.postDelayed(new Runnable(){
public void run(){
//do your stuff
doYourStuff();
//post the event again until a stopCondition is met.
if(stopCondition==false){
handler.postDelayed(this,INTERVAL);
}
}
},INTERVAL);
}
答案 2 :(得分:0)
根据评论中的要求,下面是一个示例,说明如何使用Handler延迟运行某些代码,直到经过一定的时间。在“活动”中将处理程序定义为变量:
Handler handler = new Handler();
由于该处理程序是在UI线程上创建的,因此您发布到它的任何内容也将在同一个线程上运行。您可以安排代码立即运行或延迟运行。例如:
handler.postDelayed(new Runnable()
{
public void run()
{
//Your code here
}
}, 3000); //Code will be scheduled to run on the UI thread afer 3 seconds