解决IllegalStateException:Task already scheduled or cancelled
用定时器完成循环操作遇到的问题,解决方法如下
我这里列举了三种方法
timer = new Timer();
task = new TimerTask() {
public void run() {
handler.sendEmptyMessage(1);
}
};
/***************1.解决IllegalStateException:Task already scheduled or cancelled.*****************/
Field field = null;
try {
field = TimerTask.class.getDeclaredField("state");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
field.setAccessible(true);
try {
field.set(task, 0);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
timer.schedule(task,1000,1000);
/***************1.解决IllegalStateException:Task already scheduled or cancelled.*****************/
/***************2.解决IllegalStateException:Task already scheduled or cancelled.*****************/
// timer.scheduleAtFixedRate(task, 1000 , 1000);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// task.cancel();
//
// task = new TimerTask() {
// public void run() {
// Message message = new Message();
// message.what = 1;
// handler.sendMessage(message);
// }
// };
// timer.scheduleAtFixedRate(task, 1000 , 1000);
/***************2.解决IllegalStateException:Task already scheduled or cancelled.*****************/
/***************3.解决IllegalStateException:Task already scheduled or cancelled.*****************/
// timer.scheduleAtFixedRate(task, 1000 , 1000);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// timer.cancel();
// timer.purge();
// timer = new Timer();
// task = new TimerTask() {
// @Override
// public void run() {
// Message message = new Message();
// message.what = 1;
// handler.sendMessage(message);
// }
// };
// timer.scheduleAtFixedRate(task, 1000 , 1000);
/***************3.解决IllegalStateException:Task already scheduled or cancelled.*****************/
不要忘记,不用的时候
if (timer!=null){
timer.cancel();
timer=null;
}
if (task!=null){
task.cancel();
task=null;
}