简体   繁体   English

如何在特定时间段内打开Android手电筒

[英]How to switch on the flashlight on Android for a certain period

I am trying to switch the flash LED on for a certain amount of time but my code is not working as expected: 我试图在一定时间内打开闪光灯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();
             }

         }

The LED doesn't switch off after 10 seconds and when another call is made to this function an exception is thrown saying that my camera resource is still in use and not free . 10秒钟后LED指示灯不会关闭,当再次调用该功能时,抛出异常,表明我的相机资源仍在使用中,并没有释放

Ok I figured out the solution myself. 好吧,我自己想出了解决方案。 Here is what I have done to my code. 这是我对代码所做的事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM