我正在使用一个线程来运行手电筒,我想在按下背部后停止该线程。
我使用以下代码启动线程:
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();
}
我可以做些什么来实现我的目标(按下后停止线程和手电筒)?