【转载】Android7.0以前和7.0以后开启闪光灯的方式

  1. Android 7.0以后闪光灯是通过CameraManger来进行管理的
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    try {
        //obtain CameraManager
        CameraManager mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
        //obtain camera ID
        String[] ids  = mCameraManager.getCameraIdList();
        for (String id : ids) {
            CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);
            //whether contain flash light
            Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
            Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
            if (flashAvailable != null && flashAvailable
                && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
                //open or close flash light
                mCameraManager.setTorchMode(id, isChecked);
            }
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

  1. Android 7.0之前是通过Camera来管理
if (isChecked) {
    try {
        mCamera = Camera.open();
        mCamera.startPreview();
        mParameters = mCamera.getParameters();
        mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        mCamera.setParameters(mParameters);
        Toast.makeText(getContext(),"Flash On", Toast.LENGTH_SHORT).show();
    }catch (Exception e) {
        e.printStackTrace();
    }
    
}else {
    mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
    mCamera.setParameters(mParameters);
    mCamera.stopPreview();
    mCamera.release();
    Toast.makeText(getContext(),"Flash Off", Toast.LENGTH_SHORT).show();
}

链接:Android7.0以前和7.0以后开启闪光灯的方式

posted @ 2020-04-13 11:49  Lo3King  阅读(397)  评论(0编辑  收藏  举报