更新CameraX至v1.2.1

This commit is contained in:
Jenly
2023-03-04 20:54:37 +08:00
parent b2fa6aaec0
commit a85d793149
53 changed files with 1566 additions and 884 deletions

View File

@@ -1,5 +1,6 @@
package com.king.zxing;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
@@ -27,6 +28,7 @@ import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraInfo;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.FocusMeteringAction;
import androidx.camera.core.ImageAnalysis;
@@ -43,6 +45,18 @@ import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
/**
* 相机扫描基类;{@link DefaultCameraScan} 为 {@link CameraScan} 的默认实现
* <p>
* 快速实现扫描识别主要有以下几种方式:
* <p>
* 1、通过继承 {@link CaptureActivity}或者{@link CaptureFragment}或其子类,可快速实现扫描识别。
* 适用于大多数场景自定义布局时需覆写getLayoutId方法
* <p>
* 2、在你项目的Activity或者Fragment中实例化一个{@link DefaultCameraScan}。(适用于想在扫码界面写交互逻辑,又因为项目
* 架构或其它原因,无法直接或间接继承{@link CaptureActivity}或{@link CaptureFragment}时使用)
* <p>
* 3、继承{@link CameraScan}自己实现一个,可参照默认实现类{@link DefaultCameraScan}其他步骤同方式2。高级用法谨慎使用
*
* @author <a href="mailto:jenly1314@gmail.com">Jenly</a>
*/
public class DefaultCameraScan extends CameraScan {
@@ -61,6 +75,11 @@ public class DefaultCameraScan extends CameraScan {
*/
private static final int HOVER_TAP_SLOP = 20;
/**
* 每次缩放改变的步长
*/
private static final float ZOOM_STEP_SIZE = 0.1F;
private FragmentActivity mFragmentActivity;
private Context mContext;
private LifecycleOwner mLifecycleOwner;
@@ -92,15 +111,15 @@ public class DefaultCameraScan extends CameraScan {
private AmbientLightManager mAmbientLightManager;
private int mOrientation;
private int mScreenWidth;
private int mScreenHeight;
private int mImageWidth;
private int mImageHeight;
private long mLastAutoZoomTime;
private long mLastHoveTapTime;
private boolean isClickTap;
private float mDownX;
private float mDownY;
public DefaultCameraScan(@NonNull FragmentActivity activity,@NonNull PreviewView previewView){
public DefaultCameraScan(@NonNull FragmentActivity activity, @NonNull PreviewView previewView) {
this.mFragmentActivity = activity;
this.mLifecycleOwner = activity;
this.mContext = activity;
@@ -108,7 +127,7 @@ public class DefaultCameraScan extends CameraScan {
initData();
}
public DefaultCameraScan(@NonNull Fragment fragment,@NonNull PreviewView previewView){
public DefaultCameraScan(@NonNull Fragment fragment, @NonNull PreviewView previewView) {
this.mFragmentActivity = fragment.getActivity();
this.mLifecycleOwner = fragment;
this.mContext = fragment.getContext();
@@ -116,25 +135,34 @@ public class DefaultCameraScan extends CameraScan {
initData();
}
private ScaleGestureDetector.OnScaleGestureListener mOnScaleGestureListener = new ScaleGestureDetector.SimpleOnScaleGestureListener(){
/**
* 缩放手势检测
*/
private ScaleGestureDetector.OnScaleGestureListener mOnScaleGestureListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scale = detector.getScaleFactor();
if(mCamera != null){
if (mCamera != null) {
float ratio = mCamera.getCameraInfo().getZoomState().getValue().getZoomRatio();
// 根据缩放的手势和当前比例进行缩放
zoomTo(ratio * scale);
return true;
}
return true;
return false;
}
};
private void initData(){
/**
* 初始化
*/
@SuppressLint("ClickableViewAccessibility")
private void initData() {
mResultLiveData = new MutableLiveData<>();
mResultLiveData.observe(mLifecycleOwner, result -> {
if(result != null){
if (result != null) {
handleAnalyzeResult(result);
}else if(mOnScanResultCallback != null){
} else if (mOnScanResultCallback != null) {
mOnScanResultCallback.onScanResultFailure();
}
});
@@ -144,42 +172,38 @@ public class DefaultCameraScan extends CameraScan {
ScaleGestureDetector scaleGestureDetector = new ScaleGestureDetector(mContext, mOnScaleGestureListener);
mPreviewView.setOnTouchListener((v, event) -> {
handlePreviewViewClickTap(event);
if(isNeedTouchZoom()){
if (isNeedTouchZoom()) {
return scaleGestureDetector.onTouchEvent(event);
}
return false;
});
DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
mScreenWidth = displayMetrics.widthPixels;
mScreenHeight = displayMetrics.heightPixels;
LogUtils.d(String.format("displayMetrics:%dx%d",mScreenWidth,mScreenHeight));
mBeepManager = new BeepManager(mContext);
mAmbientLightManager = new AmbientLightManager(mContext);
if(mAmbientLightManager != null){
mAmbientLightManager.register();
mAmbientLightManager.setOnLightSensorEventListener((dark, lightLux) -> {
if(flashlightView != null){
if(dark){
if(flashlightView.getVisibility() != View.VISIBLE){
flashlightView.setVisibility(View.VISIBLE);
flashlightView.setSelected(isTorchEnabled());
}
}else if(flashlightView.getVisibility() == View.VISIBLE && !isTorchEnabled()){
flashlightView.setVisibility(View.INVISIBLE);
flashlightView.setSelected(false);
mAmbientLightManager.register();
mAmbientLightManager.setOnLightSensorEventListener((dark, lightLux) -> {
if (flashlightView != null) {
if (dark) {
if (flashlightView.getVisibility() != View.VISIBLE) {
flashlightView.setVisibility(View.VISIBLE);
flashlightView.setSelected(isTorchEnabled());
}
} else if (flashlightView.getVisibility() == View.VISIBLE && !isTorchEnabled()) {
flashlightView.setVisibility(View.INVISIBLE);
flashlightView.setSelected(false);
}
});
}
}
});
}
private void handlePreviewViewClickTap(MotionEvent event){
if(event.getPointerCount() == 1){
switch (event.getAction()){
/**
* 处理预览视图点击事件;如果触发的点击事件被判定对焦操作,则开始自动对焦
*
* @param event
*/
private void handlePreviewViewClickTap(MotionEvent event) {
if (event.getPointerCount() == 1) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isClickTap = true;
mDownX = event.getX();
@@ -187,35 +211,43 @@ public class DefaultCameraScan extends CameraScan {
mLastHoveTapTime = System.currentTimeMillis();
break;
case MotionEvent.ACTION_MOVE:
isClickTap = MathUtils.distance(mDownX,mDownY,event.getX(),event.getY()) < HOVER_TAP_SLOP;
isClickTap = MathUtils.distance(mDownX, mDownY, event.getX(), event.getY()) < HOVER_TAP_SLOP;
break;
case MotionEvent.ACTION_UP:
if(isClickTap && mLastHoveTapTime + HOVER_TAP_TIMEOUT > System.currentTimeMillis()){
startFocusAndMetering(event.getX(),event.getY());
if (isClickTap && mLastHoveTapTime + HOVER_TAP_TIMEOUT > System.currentTimeMillis()) {
// 开始对焦和测光
startFocusAndMetering(event.getX(), event.getY());
}
break;
}
}
}
private void startFocusAndMetering(float x, float y){
if(mCamera != null){
MeteringPoint point = mPreviewView.getMeteringPointFactory().createPoint(x,y);
/**
* 开始对焦和测光
*
* @param x
* @param y
*/
private void startFocusAndMetering(float x, float y) {
if (mCamera != null) {
MeteringPoint point = mPreviewView.getMeteringPointFactory().createPoint(x, y);
FocusMeteringAction focusMeteringAction = new FocusMeteringAction.Builder(point).build();
if(mCamera.getCameraInfo().isFocusMeteringSupported(focusMeteringAction)){
if (mCamera.getCameraInfo().isFocusMeteringSupported(focusMeteringAction)) {
mCamera.getCameraControl().startFocusAndMetering(focusMeteringAction);
LogUtils.d("startFocusAndMetering:" + x + "," + y);
}
}
}
private void initConfig(){
if(mCameraConfig == null){
/**
* 初始化配置
*/
private void initConfig() {
if (mCameraConfig == null) {
mCameraConfig = new CameraConfig();
}
if(mAnalyzer == null){
if (mAnalyzer == null) {
mAnalyzer = new MultiFormatAnalyzer();
}
}
@@ -223,19 +255,19 @@ public class DefaultCameraScan extends CameraScan {
@Override
public CameraScan setCameraConfig(CameraConfig cameraConfig) {
if(cameraConfig != null){
if (cameraConfig != null) {
this.mCameraConfig = cameraConfig;
}
return this;
}
@Override
public void startCamera(){
public void startCamera() {
initConfig();
mCameraProviderFuture = ProcessCameraProvider.getInstance(mContext);
mCameraProviderFuture.addListener(() -> {
try{
try {
Preview preview = mCameraConfig.options(new Preview.Builder());
//相机选择器
@@ -248,49 +280,52 @@ public class DefaultCameraScan extends CameraScan {
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST));
imageAnalysis.setAnalyzer(Executors.newSingleThreadExecutor(), image -> {
if(isAnalyze && !isAnalyzeResult && mAnalyzer != null){
Result result = mAnalyzer.analyze(image,mOrientation);
mImageWidth = image.getWidth();
mImageHeight = image.getHeight();
if (isAnalyze && !isAnalyzeResult && mAnalyzer != null) {
Result result = mAnalyzer.analyze(image, mOrientation);
mResultLiveData.postValue(result);
}
image.close();
});
if(mCamera != null){
if (mCamera != null) {
mCameraProviderFuture.get().unbindAll();
}
//绑定到生命周期
// 绑定到生命周期
mCamera = mCameraProviderFuture.get().bindToLifecycle(mLifecycleOwner, cameraSelector, preview, imageAnalysis);
}catch (Exception e){
} catch (Exception e) {
LogUtils.e(e);
}
},ContextCompat.getMainExecutor(mContext));
}, ContextCompat.getMainExecutor(mContext));
}
/**
* 处理分析结果
*
* @param result
*/
private synchronized void handleAnalyzeResult(Result result){
private synchronized void handleAnalyzeResult(Result result) {
if(isAnalyzeResult || !isAnalyze){
if (isAnalyzeResult || !isAnalyze) {
return;
}
isAnalyzeResult = true;
if(mBeepManager != null){
if (mBeepManager != null) {
mBeepManager.playBeepSoundAndVibrate();
}
if(result.getBarcodeFormat() == BarcodeFormat.QR_CODE && isNeedAutoZoom() && mLastAutoZoomTime + 100 < System.currentTimeMillis()){
if (result.getBarcodeFormat() == BarcodeFormat.QR_CODE && isNeedAutoZoom() && mLastAutoZoomTime + 100 < System.currentTimeMillis()) {
ResultPoint[] points = result.getResultPoints();
if(points != null && points.length >= 2){
float distance1 = ResultPoint.distance(points[0],points[1]);
if (points != null && points.length >= 2) {
float distance1 = ResultPoint.distance(points[0], points[1]);
float maxDistance = distance1;
if(points.length >= 3){
float distance2 = ResultPoint.distance(points[1],points[2]);
float distance3 = ResultPoint.distance(points[0],points[2]);
maxDistance = Math.max(Math.max(distance1,distance2),distance3);
if (points.length >= 3) {
float distance2 = ResultPoint.distance(points[1], points[2]);
float distance3 = ResultPoint.distance(points[0], points[2]);
maxDistance = Math.max(Math.max(distance1, distance2), distance3);
}
if(handleAutoZoom((int)maxDistance,result)){
if (handleAutoZoom((int) maxDistance, result)) {
return;
}
}
@@ -299,9 +334,15 @@ public class DefaultCameraScan extends CameraScan {
scanResultCallback(result);
}
private boolean handleAutoZoom(int distance,Result result){
int size = Math.min(mScreenWidth,mScreenHeight);
if(distance * 4 < size){
/**
* 处理自动缩放
* @param distance
* @param result
* @return
*/
private boolean handleAutoZoom(int distance, Result result) {
int size = Math.min(mImageWidth, mImageHeight);
if (distance * 4 < size) {
mLastAutoZoomTime = System.currentTimeMillis();
zoomIn();
scanResultCallback(result);
@@ -310,8 +351,12 @@ public class DefaultCameraScan extends CameraScan {
return false;
}
private void scanResultCallback(Result result){
if(mOnScanResultCallback != null && mOnScanResultCallback.onScanResultCallback(result)){
/**
* 扫描结果回调
* @param result
*/
private void scanResultCallback(Result result) {
if (mOnScanResultCallback != null && mOnScanResultCallback.onScanResultCallback(result)) {
/*
* 如果拦截了结果则重置分析结果状态并当isAnalyze为true时默认会继续分析图像也就是连扫
* 如果只是想拦截扫码结果回调,并不想继续分析图像(不想连扫),请在拦截扫码逻辑处通过调用
@@ -321,21 +366,20 @@ public class DefaultCameraScan extends CameraScan {
return;
}
if(mFragmentActivity != null){
if (mFragmentActivity != null) {
Intent intent = new Intent();
intent.putExtra(SCAN_RESULT,result.getText());
mFragmentActivity.setResult(Activity.RESULT_OK,intent);
intent.putExtra(SCAN_RESULT, result.getText());
mFragmentActivity.setResult(Activity.RESULT_OK, intent);
mFragmentActivity.finish();
}
}
@Override
public void stopCamera(){
if(mCameraProviderFuture != null){
public void stopCamera() {
if (mCameraProviderFuture != null) {
try {
mCameraProviderFuture.get().unbindAll();
}catch (Exception e){
} catch (Exception e) {
LogUtils.e(e);
}
}
@@ -353,45 +397,45 @@ public class DefaultCameraScan extends CameraScan {
return this;
}
@Override
public void zoomIn(){
if(mCamera != null){
float ratio = mCamera.getCameraInfo().getZoomState().getValue().getZoomRatio() + 0.1f;
float maxRatio = mCamera.getCameraInfo().getZoomState().getValue().getMaxZoomRatio();
if(ratio <= maxRatio){
public void zoomIn() {
if (mCamera != null) {
float ratio = getCameraInfo().getZoomState().getValue().getZoomRatio() + ZOOM_STEP_SIZE;
float maxRatio = getCameraInfo().getZoomState().getValue().getMaxZoomRatio();
if (ratio <= maxRatio) {
mCamera.getCameraControl().setZoomRatio(ratio);
}
}
}
@Override
public void zoomOut(){
if(mCamera != null){
float ratio = mCamera.getCameraInfo().getZoomState().getValue().getZoomRatio() - 0.1f;
float minRatio = mCamera.getCameraInfo().getZoomState().getValue().getMinZoomRatio();
if(ratio >= minRatio){
public void zoomOut() {
if (mCamera != null) {
float ratio = getCameraInfo().getZoomState().getValue().getZoomRatio() - ZOOM_STEP_SIZE;
float minRatio = getCameraInfo().getZoomState().getValue().getMinZoomRatio();
if (ratio >= minRatio) {
mCamera.getCameraControl().setZoomRatio(ratio);
}
}
}
@Override
public void zoomTo(float ratio) {
if(mCamera != null){
ZoomState zoomState = mCamera.getCameraInfo().getZoomState().getValue();
if (mCamera != null) {
ZoomState zoomState = getCameraInfo().getZoomState().getValue();
float maxRatio = zoomState.getMaxZoomRatio();
float minRatio = zoomState.getMinZoomRatio();
float zoom = Math.max(Math.min(ratio,maxRatio),minRatio);
float zoom = Math.max(Math.min(ratio, maxRatio), minRatio);
mCamera.getCameraControl().setZoomRatio(zoom);
}
}
@Override
public void lineZoomIn() {
if(mCamera != null){
float zoom = mCamera.getCameraInfo().getZoomState().getValue().getLinearZoom() + 0.1f;
if(zoom <= 1f){
if (mCamera != null) {
float zoom = getCameraInfo().getZoomState().getValue().getLinearZoom() + ZOOM_STEP_SIZE;
if (zoom <= 1f) {
mCamera.getCameraControl().setLinearZoom(zoom);
}
}
@@ -399,31 +443,31 @@ public class DefaultCameraScan extends CameraScan {
@Override
public void lineZoomOut() {
if(mCamera != null){
float zoom = mCamera.getCameraInfo().getZoomState().getValue().getLinearZoom() - 0.1f;
if(zoom >= 0f){
if (mCamera != null) {
float zoom = getCameraInfo().getZoomState().getValue().getLinearZoom() - ZOOM_STEP_SIZE;
if (zoom >= 0f) {
mCamera.getCameraControl().setLinearZoom(zoom);
}
}
}
@Override
public void lineZoomTo(@FloatRange(from = 0.0,to = 1.0) float linearZoom) {
if(mCamera != null){
public void lineZoomTo(@FloatRange(from = 0.0, to = 1.0) float linearZoom) {
if (mCamera != null) {
mCamera.getCameraControl().setLinearZoom(linearZoom);
}
}
@Override
public void enableTorch(boolean torch) {
if(mCamera != null && hasFlashUnit()){
if (mCamera != null && hasFlashUnit()) {
mCamera.getCameraControl().enableTorch(torch);
}
}
@Override
public boolean isTorchEnabled() {
if(mCamera != null){
if (mCamera != null) {
return mCamera.getCameraInfo().getTorchState().getValue() == TorchState.ON;
}
return false;
@@ -431,11 +475,12 @@ public class DefaultCameraScan extends CameraScan {
/**
* 是否支持闪光灯
*
* @return
*/
@Override
public boolean hasFlashUnit(){
if(mCamera != null){
public boolean hasFlashUnit() {
if (mCamera != null) {
return mCamera.getCameraInfo().hasFlashUnit();
}
return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
@@ -443,7 +488,7 @@ public class DefaultCameraScan extends CameraScan {
@Override
public CameraScan setVibrate(boolean vibrate) {
if(mBeepManager != null){
if (mBeepManager != null) {
mBeepManager.setVibrate(vibrate);
}
return this;
@@ -451,7 +496,7 @@ public class DefaultCameraScan extends CameraScan {
@Override
public CameraScan setPlayBeep(boolean playBeep) {
if(mBeepManager != null){
if (mBeepManager != null) {
mBeepManager.setPlayBeep(playBeep);
}
return this;
@@ -465,19 +510,27 @@ public class DefaultCameraScan extends CameraScan {
@Nullable
@Override
public Camera getCamera(){
public Camera getCamera() {
return mCamera;
}
/**
* CameraInfo
*
* @return {@link CameraInfo}
*/
private CameraInfo getCameraInfo() {
return mCamera.getCameraInfo();
}
@Override
public void release() {
isAnalyze = false;
flashlightView = null;
if(mAmbientLightManager != null){
if (mAmbientLightManager != null) {
mAmbientLightManager.unregister();
}
if(mBeepManager != null){
if (mBeepManager != null) {
mBeepManager.close();
}
stopCamera();
@@ -486,23 +539,23 @@ public class DefaultCameraScan extends CameraScan {
@Override
public CameraScan bindFlashlightView(@Nullable View v) {
flashlightView = v;
if(mAmbientLightManager != null){
if (mAmbientLightManager != null) {
mAmbientLightManager.setLightSensorEnabled(v != null);
}
return this;
}
@Override
public CameraScan setDarkLightLux(float lightLux){
if(mAmbientLightManager != null){
public CameraScan setDarkLightLux(float lightLux) {
if (mAmbientLightManager != null) {
mAmbientLightManager.setDarkLightLux(lightLux);
}
return this;
}
@Override
public CameraScan setBrightLightLux(float lightLux){
if(mAmbientLightManager != null){
public CameraScan setBrightLightLux(float lightLux) {
if (mAmbientLightManager != null) {
mAmbientLightManager.setBrightLightLux(lightLux);
}
return this;