需要注意的是安卓不同版本间会有一些变化,安卓7.0以上和7.0以下的版本有所区别
安卓 7.0 以上:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @TargetApi(Build.VERSION_CODES.N) @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void flashControl(boolean enable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { CameraManager cameraManager = (CameraManager) getApplicationContext().getSystemService(Context.CAMERA_SERVICE); String[] ids = cameraManager.getCameraIdList(); for (String id : ids) { CameraCharacteristics c = cameraManager.getCameraCharacteristics(id); 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) { cameraManager.setTorchMode(id, enable); } } } catch (CameraAccessException e) { e.printStackTrace(); } } }
|
安卓 7.0 以下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| Camrea camera = Camera.open(); Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); camera.setParameters(parameters);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); camera.setParameters(parameters);
@Override public void onDestroy() { super.onDestroy(); camera.release(); }
|