Flashlight control in Marshmallow

前端 未结 4 1700
情话喂你
情话喂你 2021-02-07 18:45

I have a problem regarding the camera in the most recent Marshmallow build, more specifically the flashlight. On any pre-Marshmallow version all I need to do to turn the flash o

4条回答
  •  执笔经年
    2021-02-07 19:08

    As Saurabh7474 has responded, to check the version of Android and use setTorchMode API it's very correct.

    Although you can also use params.setFlashMode (...) in marshmallow using

    mCamera.setPreviewTexture (new SurfaceTexture (100))
    

    after Camera.open (...) and before calling mCamera.startPreview();

    try {
                    Log.i(TAG, "getCamera");
                    int requestedCameraId = getIdForRequestedCamera(mFacing);
                    if (requestedCameraId == -1) {
                        throw new RuntimeException("Could not find requested camera.");
                    }
                    mCamera = Camera.open(requestedCameraId);
                    mCamera.setPreviewTexture(new SurfaceTexture(DUMMY_TEXTURE_NAME));
                    params = mCamera.getParameters();
                } catch (RuntimeException e) {
                    Log.e("Failed to Open. Error:", e.getMessage());
                } catch (IOException e) {
                    Log.e("Failed to Open. can't setPreviewTexture:", e.getMessage());
                }
    

    then when you want, you can use

            mParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            camera.setParameters(mParams);
    

    My answer is based on CameraSource examples of Vision API that uses params.setFlashMode (...) and works in Api 23 and above. If you decide to inspect CameraSource, the key method that has solved the same problem is "start ()", in the line 312 ...

    https://github.com/googlesamples/android-vision/blob/master/visionSamples/barcode-reader/app/src/main/java/com/google/android/gms/samples/vision/barcodereader/ui/camera/CameraSource.java

    The reason you can find here https://stackoverflow.com/a/33333046/4114846

提交回复
热议问题