我试着让LED灯在我的背向相机上每隔N秒闪烁一次:
private void blink() {
for (int i = 0; i < 5; i++) {
turnOnLedLight();
try {
Thread.sleep(1000); // N = 1 second
}
catch (InterruptedException e) {
Log.e("Test", "Got interrupted.");
}
turnOffLedLight();
}
}
private static Camera camera = null;
private void turnOnLedLight() {
camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
}
private void turnOffLedLight() {
camera.stopPreview();
camera.release();
camera = null;
}上面的代码可以工作,但是除了让线程进入睡眠之外,还有更好的方法吗?blink方法在doInBackground方法中在AsyncTask中调用。
更新
我意识到上面的代码使得LED灯在N秒内保持亮着。我想知道是否有更好的方法让它保持N秒,保持N秒。
发布于 2014-03-18 03:56:16
我会通过alarmManager在闹钟里做这件事。你在拖延AsyncTask的线程。从3.0开始,异步任务都共享一个线程,并执行循环执行。这意味着在您有任何其他异步任务时,它将被阻塞。此外,如果手机进入睡眠状态,警报将唤醒它;如果手机在你的线程中进入睡眠状态,则线程将被暂停,并冻结在当前闪烁状态,直到用户将其唤醒。
我也只做一次Camera.open,当你第一次想要相机的时候,当你不再想要它的时候释放它,而不是在每个turnOnLedLight中请求它(导致你获得和释放相机5次)。现在,如果有人在你关机时换了应用程序,打开相机应用程序,你可能会被拒之门外(可能会崩溃)。
发布于 2014-03-18 03:50:05
如果您想使System.currentTimeMillis()更准确,可以使用它,例如:
long previousTimeMillis = System.currentTimeMillis();
int i = 0;
while(i < 5){
if(System.currentTimeMillis() - previousTimeMillis >= 1000){
turnOffLedLight();
previousTimeMillis = System.currentTimeMillis();
i++;
}else{
turnOnLedLight();
}
}下面是你能做些什么,让led在N秒钟内保持不间断:
long previousTimeMillis = Sustem.currentTimeMillis();
boolean shouldTurnOnLight = true;
int i = 0;
while(i < 5){
if(System.currentTimeMillis() - previousTimeMillis >= 1000){
if(shouldTurnOnLight){
turnOnLedLight();
shouldTurnOnLight = false;
}else{
turnOffLedLight();
shouldTurnOnLight = true;
}
previousTimeMillis = System.currentTimeMillis();
i++;
}
}发布于 2014-03-18 04:07:13
如果您的开/关周期是对称的,下面是另一种方法:
public Boolean ledOn = false;
...
// Change the LED state once a second for 5 minutes:
CountDownTimer cdt = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
ledOn = !ledOn;
if (ledOn)
turnOffLedLight();
else
turnOnLedLight();
}
public void onFinish() {
Log.d(TAG, "LED is on? "+ ledOn.toString());
}
};
...
cdt.start();
...
cdt.cancel();(编辑以更好地处理启动/停止。)
https://stackoverflow.com/questions/22469832
复制相似问题