How to enable FlashLight in Lollipop programmatically Android

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

The above dose does not work on Lollipop because the camera is out of date in Lollipop. I cannot find any other way to programmatically enable Flash in Lollipop. How can i achieve this. Thank you in advance.

+6
source share
3 answers
 mCam = Camera.open(); Camera.Parameters p = mCam.getParameters(); p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); mCam.setParameters(p); mPreviewTexture = new SurfaceTexture(0); try { mCam.setPreviewTexture(mPreviewTexture); } catch (IOException ex) { // Ignore } mCam.startPreview(); 

It works for me on Android 5.0.x. And don't forget to add permission to the manifest to use the camera.

 <uses-permission android:name="android.permission.CAMERA" /> 
+4
source

The camera class is now out of date.

For LOLLIPOP above you need to use camera2 Api

so nickkadrov doesent solution works for 6.0 and above devices, the best way to turn on / off the flash is to try the 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 a static boolean of the class whose default value is false

 static boolean toggle=false; 
+4
source

Your code should work. Check if you added the permission to use the camera correctly:

 <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.FLASHLIGHT"/> 

This should be added to your AndroidManifest above your other specifications.

In addition, there is an interesting discussion of various devices and an example that should work on each device here: Flashlight in Android

If you do not want to use the deprecated API, you can check:

Camera2 Package Summary

Camera device specification on new api

Unfortunately, I cannot give an example of using the new API, because I have not used it yet.

+1
source

Source: https://habr.com/ru/post/982840/


All Articles