You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio二维码扫描相机多次点击后无法回显结果求助

二维码扫描多次点击后结果不回显的解决方案

问题根源分析

  1. MainActivity参数传递错误:onActivityResult方法调用super时传入了错误参数,导致Activity结果处理逻辑异常。
  2. ScanActivity重复检测触发:扫描到二维码后未立即停止检测器,可能导致多次发送结果,同时资源释放顺序不合理,影响后续实例的正常运行。

具体修复步骤

1. 修正MainActivity的onActivityResult方法

错误代码中super.onActivityResult(resultCode,resultCode,data)将第一个参数(requestCode)错误替换为resultCode,导致系统无法正确识别请求对应的结果。

修改后的代码:

@Override
protected void onActivityResult(int requestCode, int resultCode,@Nullable Intent data){
    super.onActivityResult(requestCode, resultCode, data); // 修正参数顺序
    if(requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK && data != null){
        String barcode = data.getStringExtra("barcode");
        editText.setText(barcode);
    }
 }

2. 优化ScanActivity的扫描逻辑和资源管理

  • 扫描完成后立即停止检测:避免检测器重复触发finish操作,确保只返回一次结果。
  • 调整资源释放顺序:先停止相机再释放资源,避免资源泄漏。
  • 调整处理器设置时机:确保相机启动前已配置好检测器处理器。

修改后的ScanActivity关键代码:

调整receiveDetections方法
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
    SparseArray<Barcode> barcodes = detections.getDetectedItems();
    if (barcodes.size() > 0) {
        String barcodeValue = barcodes.valueAt(0).displayValue;
        // 立即停止检测,防止多次触发
        barcodeDetector.setProcessor(null);
        Intent intent = new Intent();
        intent.putExtra("barcode", barcodeValue);
        setResult(RESULT_OK, intent);
        finish();
     }
 }
修正onDestroy方法的资源释放顺序
@Override
protected void onDestroy() {
    stopCamera(); // 先停止相机
    barcodeDetector.release();
    cameraSource.release();
    super.onDestroy();
}
优化startCamera方法中处理器的设置时机
private void startCamera() {
    // 先设置处理器
    barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {

        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            SparseArray<Barcode> barcodes = detections.getDetectedItems();
            if (barcodes.size() > 0) {
                String barcodeValue = barcodes.valueAt(0).displayValue;
                barcodeDetector.setProcessor(null);
                Intent intent = new Intent();
                intent.putExtra("barcode", barcodeValue);
                setResult(RESULT_OK, intent);
                finish();
             }
         }
      });

    try {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != 
           PackageManager.PERMISSION_GRANTED) {
            return;
        }
        cameraSource.start(surfaceView.getHolder());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

额外说明

每次启动ScanActivity都是全新实例,确保每次扫描都使用未被释放的检测器和相机资源;当前权限请求逻辑无需修改,已覆盖相机权限的申请流程。

内容的提问来源于stack exchange,提问作者Habibur Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:57:21