我想在无限循环中打开/关闭闪光灯,所以当它打开时它应该等待5秒然后关闭然后等待5秒再次打开,依此类推...... 我怎么能这样做?
这是我的代码:
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// num = Integer.parseInt(n.getText().toString());
while(bl){
if(camera == null){
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
turnOn();
}
});
}
}).start();
}
else{
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
turnOff();
}
});
}
}).start();
}
}
}
});
答案 0 :(得分:1)
我建议不要使用Thread
来实现这一目标。为什么不使用Runnable
课程并通过Handler
延迟发布?例如:
Handler handler = new Handler(); // make this a member variable of your class
boolean isOn = false; // make this a member variable of your class
final Runnable flashRunnable = new Runnable() {
@Override
public void run() {
if (isOn) {
turnOff();
isOn = false;
} else {
turnOn();
isOn = true;
}
handler.postDelayed(flashRunnable, 5000);
}
};
handler.postDelayed(flashRunnable, 5000);
如果您需要在UI线程的Runnable
内运行代码,您甚至可以在postDelayed
上致电View
而不是创建Handler
答案 1 :(得分:0)
尝试使用Executors代替(丑陋)Thread.sleep():
boolean cameraOn = true
final Runnable runnable = new Runnable() {
@Override
public void run() {
// your logic here:
// if (cameraOn) ...
// else ...
// cameraOn = !cameraOn
}
};
Executors.newScheduledThreadPool(1).schedule(new Runnable() {
@Override
public void run() {
runnable.run();
}
}, 5, TimeUnit.SECONDS);