Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn on FlashLight in Lollipop programmatically Android

Tags:

android

Camera cam = Camera.open();     
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();

The above dose not work on Lollipop, Because Camera is deprecated in Lollipop. I cant able to find any other way to turn on flash programmatically in Lollipop. How can I achieve this. Thanks in advance.

like image 953
Sai Avatar asked Feb 22 '15 08:02

Sai


1 Answers

Camera class is now deprecated.

For LOLLIPOP above you need to use camera2 Api

so nickkadrov's solution doesent work for 6.0 & above device,best way to on/off flash light is try code below

public static void toggleFlashLight(){
    toggle=!toggle;
               try {
            CameraManager cameraManager = (CameraManager) getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                for (String id : cameraManager.getCameraIdList()) {

                    // Turn on the flash if camera has one
                    if (cameraManager.getCameraCharacteristics(id).get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            cameraManager.setTorchMode(id, true);
                        }
                    }
                }
            }
        } catch (Exception e2) {
            Toast.makeText(getApplicationContext(), "Torch Failed: " + e2.getMessage(), Toast.LENGTH_SHORT).show();
        }


}

where toggle is class level static Boolean variable whose default value is false

static boolean toggle=false;
like image 138
The Black Horse Avatar answered Oct 10 '22 20:10

The Black Horse