How does one retrieve the cameraID and use setTorchMode?

瘦欲@ 提交于 2019-12-01 23:13:26

You should use CameraManager "getCameraIdList" function which will retrieve you a list of strings where each represent an active camera.

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        try {
            for (String camID : mCameraManager.getCameraIdList()) {
                CameraCharacteristics cameraCharacteristics = mCameraManager.getCameraCharacteristics(camID);
                int lensFacing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);
                if (lensFacing == CameraCharacteristics.LENS_FACING_FRONT && cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
                    mCameraId = camID;
                    break;
                } else if (lensFacing == CameraCharacteristics.LENS_FACING_BACK && cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
                    mCameraId = camID;
                }
            }
            if (mCameraId != null) {
                mCameraManager.setTorchMode(mCameraId, true);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

mCameraId will turn on front camera flash if available or else back camera flash if available. If no flash is available then mCameraId will be null and setTorchMode will not be called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!