1. 仅开启手电筒
单纯的开启手电筒我们可以使用CameraManager的.setTorchMode()方法。
cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)获取该相机特征是否可获取闪光灯。
CameraManager cameraManager= (CameraManager) getSystemService(CAMERA_SERVICE);
String cameraIdList[]=cameraManager.getCameraIdList();
String cameraId = null;
for(int i=0;i<cameraIdList.length;i++){CameraCharacteristics cameraCharacteristics=cameraManager.getCameraCharacteristics(cameraIdList[i]);//可获取闪光灯&&朝向为后置if(cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)&&cameraCharacteristics.get(CameraCharacteristics.LENS_FACING)==CameraCharacteristics.LENS_FACING_BACK){cameraId=cameraIdList[i];break;}
}
//打开手电筒
cameraManager.setTorchMode(cameraId,true);
//关闭手电筒
cameraManager.setTorchMode(cameraId,false);
2. Camer2开启闪光灯
在Camera2中,我们一般在预览的捕获请求中设置开启或关闭闪光灯,然后向捕获通道设置新的捕获请求。
开启闪光灯:
captureRequestBuilder .set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
关闭闪光灯:
captureRequestBuilder .set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
Button torch = findViewById(R.id.torch);
torch.setOnClickListener(new View.OnClickListener() {int i = 0;public void onClick(View view) {if (i == 0) {CaptureRequest.Builder captureRequestBuilder_preview = myCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);//设置开启闪光灯captureRequestBuilder_preview.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);captureRequestBuilder_preview.addTarget(surface_surfaceView);//通道设置新循环捕获请求myCameraCaptureSession.setRepeatingRequest(captureRequestBuilder_preview.build(),null,null);i=1;} else if (i==1) {CaptureRequest.Builder captureRequestBuilder_preview= myCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);//设置关闭闪光灯captureRequestBuilder_preview.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);captureRequestBuilder_preview.addTarget(surface_surfaceView);//通道设置新循环捕获请求myCameraCaptureSession.setRepeatingRequest(captureRequestBuilder_preview.build(),null,null);i=0;}}
});
3. ZXing开启手电筒
扫码时经常需要使用手电筒,但是因为ZXing已经启动了一个相机所以无法使用CameraManager来开启手电筒有捕获通道所以也不能使用设置捕获请求开启手电筒。
但ZXing中的DecoratedBarcodeView控件类(即com.journeyapps.barcodescanner.DecoratedBarcodeView控件)提供了启动和关闭手电筒的方法。可以在自定义的Activity中通过DecoratedBarcodeView开关手电筒。
启动手电筒:.setTorchOn()
关闭手电筒:.setTorchOff()
可以在自定义Activity的onCreate()中使用这些方法。
Button torchButton=findViewById(R.id.torchButton);
torchButton.setOnClickListener(new View.OnClickListener() {int i=0;public void onClick(View view) {if(i==0){//启动手电筒barcodeScannerView.setTorchOn();i=1;} else if (i==1) {//关闭手电筒barcodeScannerView.setTorchOff();i=0;}}});