显示此错误的Timer
出现问题。我有一个Timer
来安排TimerTask
(关闭)。然后,在TimerTask
内我安排下一个TimerTask
,依此类推。根据我的理解,这应该可行,但是当我运行它时,应用程序出现“已停止工作”错误。
levelCreationTimer.schedule(close, 1000);
< =这是在OnCreate中调用的。
Timer levelCreationTimer = new Timer();
TimerTask close = new TimerTask() {
@Override
public void run() {
if (points < 10) {
switch (randNum.nextInt(2)) {
case 0:
locationBlimps[0][0] = 0;
locationBlimps[0][1] = 0;
locationBlimps[1][0] = -1;
break;
case 1:
locationBlimps[0][0] = 4;
locationBlimps[0][1] = 4;
locationBlimps[1][0] = -1;
break;
}
}
int i = 0;
while (locationBlimps[i][0] != -1) {
final int final_i = i;
runOnUiThread(new Runnable() {
public void run() {
sky[locationBlimps[final_i][1]][locationBlimps[final_i][0]].setBackgroundResource(R.drawable.scissors);
}
});
i++;
}
levelCreationTimer.schedule(far, 1000);
}
};
TimerTask far = new TimerTask() {
@Override
public void run() {
int j = 0;
while (locationBlimps[j][0] != -1) {
final int final_j = j;
runOnUiThread(new Runnable() {
public void run() {
sky[locationBlimps[final_j][1]][locationBlimps[final_j][0]].setBackgroundResource(R.drawable.scissors);
obstacles[locationBlimps[final_j][1]][locationBlimps[final_j][0]] = true;
}
});
j++;
}
levelCreationTimer.schedule(last, 1000);
}
};
TimerTask last = new TimerTask() {
@Override
public void run() {
int k = 0;
while (locationBlimps[k][0] != -1) {
final int final_k = k;
runOnUiThread(new Runnable() {
public void run() {
sky[locationBlimps[final_k][1]][locationBlimps[final_k][0]].setBackgroundResource(R.drawable.sky);
obstacles[locationBlimps[final_k][1]][locationBlimps[final_k][0]] = false;
}
});
k++;
}
levelCreationTimer.schedule(close, 10000);
}
};
我也尝试添加
levelCreationTimer.cancel();
levelCreationTimer = new Timer();
在每个schedule
之前按顺序删除计划,但它没有解决问题。
答案 0 :(得分:1)
我通过创建扩展TimerTask
的类来解决问题,然后我安排了类的实例。
class MyClass1 extends TimerTask {
@Override
public void run()
{
//my code
levelCreationTimer.schedule(new MyClass2(),1000);
//scheduling the next TimerTask ^
}
}
class MyClass2 extends TimerTask {
@Override
public void run()
{
//my code
levelCreationTimer.schedule(new MyClass1(),1000);
//scheduling the next TimerTask ^
}
}