按下后停止手电筒

时间:2012-09-01 10:44:49

标签: android multithreading android-camera

我正在使用一个线程来运行手电筒,我想在按下背面后停止该线程。

我使用以下代码启动线程:

progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Flashing...");
progressDialog.show();

thread = new Thread(MainActivity.this);
thread.start();

线程正在做:

public void run() {
    isOn = false;
    cam = Camera.open();
    p = cam.getParameters();
    try {
        for (int i = 0; i < pattern.length; i++) {
            if (isOn) {
                p.setFlashMode(Parameters.FLASH_MODE_OFF);
                cam.setParameters(p);
                Thread.sleep(pattern[i]);
                isOn = false;
            } else {
                p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                cam.setParameters(p);
                Thread.sleep(pattern[i]);
                isOn = true;
            }
        }
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
    cam.release();
    handlerFinish.sendEmptyMessage(0);
}

private Handler handlerFinish = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        progressDialog.dismiss();
    }
};

我试过这个停止,但只有进度对话框被解除但手电筒仍在工作:

@Override
public void onBackPressed() {
    super.onBackPressed();
    p.setFlashMode(Parameters.FLASH_MODE_OFF);
    cam.setParameters(p);
    isOn = false;
    thread.stop();
}

我可以做些什么来实现我的目标(按下后退停止线程和手电筒?)

1 个答案:

答案 0 :(得分:0)

尝试此循环以停止线程

 boolean retry = true;

  while (retry) {

 try {

  thread.join();

   retry = false;

  } catch (InterruptedException e) {

  // try again shutting down the thread

  }

  }