Android手电筒、闪光灯、torch、flash

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

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;
        }
    }
 });

你可能感兴趣的:(android,java)