我不知道如何从循环中走出去

时间:2012-12-28 12:21:13

标签: android android-camera

当我按下此按钮时:

case R.id.btlento:
    Timer timers = new Timer();
    timers.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        cameraOn();
    },deloy1,poriod1);
        Timer timers2 = new Timer();
        timers2.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            cameraOff();
        }
    },deloy,poriod);

cameraOn和cameraOff的方法是:

private void cameraOff() {
    // TODO Auto-generated method stub
    parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
    camera.setParameters(parameters);
    camera.release();
    camera = null;
}

private void cameraOn() {
    // TODO Auto-generated method stub
    camera = Camera.open();
    parameters = camera.getParameters();
    parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
    camera.setParameters(parameters);
}

,变量是:

int deloy = 2000;
int poriod = 2000;
int deloy1 = 1000;
int poriod1 = 2000;

所有这一切都是为了让相机闪烁,但我不知道如何打破循环,因为永远不会停止。

如何停止循环?

3 个答案:

答案 0 :(得分:0)

使用标志

// member variables

private boolean cameraIsFlashing = false;
private Timer onTimer;
private Timer offTimer;

// constructor & other stuff

// button click method
case R.id.btlento:
     toggleCameraFlash();
   break;

private void toggleCameraFlash(){
    if(cameraIsFlashing){
        stopFlashing();
    } else {
        startFlashing();
    }
}

private void startFlashing(){
  cameraIsFlashing = true;
  // Start your timers
  onTimer = new Timer();
  onTimer.scheduleAtFixedRate(new TimerTask() {

  @Override
  public void run() {
      cameraOn();
  },deloy1,poriod1);
}

private void stopFlashing(){
  cameraIsFlashing = false;
  // Cancel / Stop your timers
  onTimer.cancel;
}

答案 1 :(得分:0)

在线程计时器上调用cancel()和purge()来停止线程 如下图所示。

private void cameraOff() {
// TODO Auto-generated method stub
if(timer != null){
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;

timer.cancel();// cancel and releases
timer.purge();
}
} 

答案 2 :(得分:0)

为计时器任务创建变量,而不是使用匿名类。首先取消计时器任务然后取消计时器。