我正在制作app手电筒.....但我想要停止闪烁的led手电筒......这是我的代码,但我无法阻止我闪烁的手电筒..
String myString = "010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101011";
long blinkDelay = 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
}
else {
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
}
Thread.sleep(blinkDelay);
}
}catch (Exception e) {
}
答案 0 :(得分:1)
您需要考虑线程安全性,因为运行此循环的代码应位于单独的线程上。将boolean
设置为安全停止至少需要AtomicBoolean
,但更容易使用不同的技术,AsyncTask
已经可以取消,并且不需要您创建和直接管理新线程:
package com.stackoverflow.blinker;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.AsyncTask;
public final class Blinker extends AsyncTask<Void, Void, Void> {
private final long blinkDelay = 50;
private final Camera cam;
private boolean on;
public Blinker(Camera cam) {
this.cam = cam;
}
@Override
protected Void doInBackground(Void... params) {
while (!isCancelled()) {
toggleLight();
try {
wait(getBlinkDelay());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
setFinalLightState();
return null;
}
private void setFinalLightState() {
// optionally turn off at the end
setOn(false);
}
private long getBlinkDelay() {
// want to have light on for a different time to it is off? do this:
// return isOn() ? blinkDelayOn : blinkDelayOff;
return blinkDelay;
}
private void toggleLight() {
setOn(!isOn());
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
Camera.Parameters p = cam.getParameters();
if (on) {
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
} else {
p.setFlashMode(Parameters.FLASH_MODE_OFF);
}
cam.setParameters(p);
}
}
用法:
//create
Blinker b = new Blinker(Camera.open());
//start
b.execute();
//stop
b.cancel(false);
答案 1 :(得分:0)
在你的for循环中创造一个条件。
例如,创建一个类的私有变量:
boolean stop = false;
在循环中检查:
for (int i = 0; (i < myString.length()) && !stop; i++) {
....
}
代码中的某处:
stop = true;