how to access the flash of an android device with api less than 23

1

I'm programming on android and I need to access the camera flash on the device. I read that the class Camera android considers it obsolete so try to use the CameraManager class but I have a problem, in the following code

public void flashOn() {

    try {
        //aca esta el problema ya que la version que estoy trabajando (api 22) es menor que la api que necesita el metodo setTorchMode (api 23)
        //entonces el if siempre es false y nunca enciende la camara
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Toast.makeText(this,"acceso",Toast.LENGTH_LONG).show();
            mCameraManager.setTorchMode(mCameraId, true);
            rotate();
        }


    } catch (Exception e) {
        e.printStackTrace();

    }
}

The question is how do I activate the flash on devices with api less than 23, should I use the Camera class that Android considers obsolete?

    
asked by Lucho Juniors 15.12.2017 в 15:32
source

1 answer

1

An option using the class Camera since the method of CameraManager as :

camManager.setTorchMode(cameraId, true);

require a minimum of API 23.

First configure permissions in the AndroidManifest.xml file

<uses-permission android:name="android.permission.CAMERA"/>
<permission android:name="android.permission.FLASHLIGHT"
    android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
    android:protectionLevel="normal" />

To activate the flash, this is done as follows:

private Camera cam;

...
...
...

 if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
    cam = Camera.open();
    Camera.Parameters params = cam.getParameters();
    params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
    cam.setParameters(params);
    cam.startPreview();
}

to deactivate it simply:

        cam.stopPreview();
        cam.release();

This can work on devices with API less than 23, I just have a device with Android 5.0.1 and it works without problem.

    
answered by 15.12.2017 / 19:07
source