0

我正在尝试打开闪光灯 LED 一段时间,但我的代码没有按预期工作:

if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
         {
             Log.i("Flash Present", "Yes");
             //Camera Has Flash
             final Camera cam = Camera.open();     
             Parameters p = cam.getParameters();
             p.setFlashMode(Parameters.FLASH_MODE_TORCH);
             cam.setParameters(p);
             ExecutorService service = Executors.newSingleThreadExecutor();

             try {
                 Runnable r = new Runnable() {
                     @Override
                     public void run() {
                         Log.i("Starting Flash", "Now");
                         cam.startPreview();
                     }
                 };

                 Future<?> f = service.submit(r);

                 f.get(10, TimeUnit.SECONDS);     // attempt the task for two minutes
             }
             catch (final InterruptedException e) {
                 // The thread was interrupted during sleep, wait or join

             }
             catch (final TimeoutException e) {
                 // Took too long!
              cam.stopPreview();
              cam.release(); 
             }
             catch (final ExecutionException e) {
                 // An exception from within the Runnable task
             }
             finally {
                  cam.stopPreview();
                  cam.release(); 
                 service.shutdown();
             }

         }

LED 不会在 10 秒后关闭,并且当再次调用此函数时会引发异常,指出我的相机资源仍在使用中并且不是空闲的。

4

1 回答 1

0

好的,我自己想出了解决方案。这是我对我的代码所做的。

public void NotifyWithFlash(Context context){

    boolean ShouldIGlow = true;

    while(ShouldIGlow){
        flashON();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            ShouldIGlow = false;
            flashOFF();
        }

    }
}


public void flashON(){
    cam = Camera.open();     
    Parameters p = cam.getParameters();
    p.setFlashMode(Parameters.FLASH_MODE_TORCH);
    cam.setParameters(p);
    cam.startPreview();

}

public void flashOFF(){
    cam.stopPreview();
    cam.release(); 
}
于 2013-04-25T09:15:15.107 回答