简体   繁体   中英

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:

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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