2013-04-21 58 views
0

我想切换闪光灯一定的时间的LED上,但如预期我的代码是不工作:如何手电筒开关在Android一段时间

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没有按” t在10秒后关闭,当另一个电话打到这个功能时,抛出一个异常,说我的相机资源仍在使用中,而不是免费的

回答

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(); 
}