我的代码:
import java.util.Timer;
import java.util.TimerTask;
.
.
.
public void btn_slow(View view){
final Camera.Parameters p = camera.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
Timer timer = new Timer();
switch(flashon) {
case 1 : timer.cancel();
flashon = 0;
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
break;
case 0: timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
timer2.schedule(new TimerTask() {
public void run() {
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
}
}, 2*1000);
timer3.schedule(new TimerTask() {
public void run() {
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
}
}, 1*1000);
}
}, 1*1000, 2*1000);
flashon = 1;
break;
}
}
希望你能帮助我。
03-02 22:12:51.379 25515-25616/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: Timer-2
java.lang.IllegalStateException: Timer was canceled
at java.util.Timer.scheduleImpl(Timer.java:561)
at java.util.Timer.schedule(Timer.java:459)
at com.example.app.Flashlight$2.run(Flashlight.java:245)
at java.util.Timer$TimerImpl.run(Timer.java:284)
答案 0 :(得分:0)
即使计时器已停止timer2且timer3仍在运行且尚未取消。 添加此
timer2.cancel();
timer3.cancel();
哪里有
timer.cancel();
修改强>
我会选择一个像这样的计时器:
将此字段作为字段
private boolean running = false;
private Timer timer = new Timer();
然后在方法
中使用此代码 boolean on = false;
final Camera.Parameters p = camera.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
if(!running)
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if(on) {
on = false;
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
}
else {
on = true;
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
}
}
}, 1*1000, 2*1000);
}
else {
timer.cancel();
}