写一份完整的使用camera2扫描多张二维码并且每次扫描后打开闪光灯的代码
时间: 2024-03-12 20:45:48 浏览: 113
好的,以下是示例代码:
```
public class QRScannerActivity extends AppCompatActivity {
// Camera-related variables
private CameraManager cameraManager;
private String cameraId;
private CameraDevice cameraDevice;
private CameraCaptureSession cameraCaptureSession;
private CaptureRequest.Builder captureRequestBuilder;
private ImageReader imageReader;
// QR code-related variables
private BarcodeDetector barcodeDetector;
private boolean isScanning = false;
// UI-related variables
private TextureView textureView;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrscanner);
textureView = findViewById(R.id.texture_view);
textView = findViewById(R.id.text_view);
// Initialize barcode detector
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
if (!barcodeDetector.isOperational()) {
Toast.makeText(this, "Could not set up barcode detector", Toast.LENGTH_SHORT).show();
finish();
}
// Set up texture view
textureView.setSurfaceTextureListener(surfaceTextureListener);
// Set up camera manager
cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
cameraId = cameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private TextureView.SurfaceTextureListener surfaceTextureListener = new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
// Open camera when texture view is available
openCamera();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Do nothing
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
closeCamera();
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// Do nothing
}
};
private CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
cameraDevice = camera;
createCameraPreviewSession();
}
@Override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
cameraDevice = null;
}
@Override
public void onError(CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
private void openCamera() {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
return;
}
cameraManager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if (cameraCaptureSession != null) {
cameraCaptureSession.close();
cameraCaptureSession = null;
}
if (cameraDevice != null) {
cameraDevice.close();
cameraDevice = null;
}
if (imageReader != null) {
imageReader.close();
imageReader = null;
}
}
private void createCameraPreviewSession() {
SurfaceTexture texture = textureView.getSurfaceTexture();
texture.setDefaultBufferSize(textureView.getWidth(), textureView.getHeight());
Surface surface = new Surface(texture);
try {
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession session) {
cameraCaptureSession = session;
try {
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(CameraCaptureSession session) {
Toast.makeText(QRScannerActivity.this, "Failed to create camera capture session", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private ImageReader.OnImageAvailableListener onImageAvailableListener = new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireLatestImage();
if (image != null) {
detectQRCode(image);
image.close();
}
}
};
private void detectQRCode(Image image) {
// Convert image to bitmap
Bitmap bitmap = textureView.getBitmap(image.getWidth(), image.getHeight());
// Rotate bitmap to correct orientation
int rotation = getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
matrix.postRotate(getRotationAngle(rotation, image.getWidth(), image.getHeight()));
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
// Detect QR code in bitmap
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<Barcode> barcodes = barcodeDetector.detect(frame);
if (barcodes.size() > 0) {
String qrCode = barcodes.valueAt(0).rawValue;
textView.setText(qrCode);
}
}
private int getRotationAngle(int rotation, int width, int height) {
int angle;
switch (rotation) {
case Surface.ROTATION_0:
angle = 90;
break;
case Surface.ROTATION_90:
angle = 0;
break;
case Surface.ROTATION_180:
angle = 270;
break;
case Surface.ROTATION_270:
angle = 180;
break;
default:
angle = 0;
break;
}
return (angle + getCameraOrientation()) % 360;
}
private int getCameraOrientation() {
int orientation = 0;
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
} catch (CameraAccessException e) {
e.printStackTrace();
}
return orientation;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show();
finish();
}
}
}
@Override
protected void onResume() {
super.onResume();
if (textureView.isAvailable()) {
openCamera();
} else {
textureView.setSurfaceTextureListener(surfaceTextureListener);
}
}
@Override
protected void onPause() {
closeCamera();
super.onPause();
}
}
```
在这个示例代码中,我们使用了 Camera2 API 来打开摄像机,并且通过 TextureView 来显示摄像头捕获的图像。我们还使用了 Google 提供的 BarcodeDetector 来检测二维码。在检测到二维码后,我们将其文本值显示在 TextView 中。
对于每次扫描后打开闪光灯的功能,您可以在 detectQRCode 方法中添加以下代码:
```
if (barcodes.size() > 0) {
String qrCode = barcodes.valueAt(0).rawValue;
textView.setText(qrCode);
// Open flash
if (!isScanning) {
captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
try {
cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
isScanning = true;
}
}
```
在这个代码中,我们首先检查是否已经检测到了二维码。如果是,我们将文本显示在 TextView 中,并且检查是否已经开始了扫描。如果没有,我们将 captureRequestBuilder 中的 FLASH_MODE 设置为 FLASH_MODE_TORCH,并且使用 setRepeatingRequest 方法来打开闪光灯。最后,我们将 isScanning 设置为 true,表示已经开始了扫描。
注意,如果您希望在每次扫描后关闭闪光灯,您可以在 detectQRCode 方法中添加以下代码:
```
if (barcodes.size() > 0) {
String qrCode = barcodes.valueAt(0).rawValue;
textView.setText(qrCode);
// Toggle flash
if (!isScanning) {
captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
try {
cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
isScanning = true;
} else {
captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
try {
cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
isScanning = false;
}
}
```
在这个代码中,我们检查 isScanning 的值。如果是 false,我们将 FLASH_MODE 设置为 FLASH_MODE_TORCH 并且打开闪光灯。如果是 true,我们将 FLASH_MODE 设置为 FLASH_MODE_OFF 并且关闭闪光灯。最后,我们将 isScanning 的值取反,表示闪光灯的状态已经反转。
阅读全文