Android二维码扫码器重复跳转页面问题求助(附代码)
解决二维码扫码器持续跳转多页面的问题
这个问题我之前也碰到过!核心原因是receiveDetections方法会随着摄像头的每一帧画面持续触发,只要二维码还在镜头范围内,就会不断执行跳转逻辑,导致打开一堆相同页面。给你两个简单有效的解决办法:
方法一:添加扫码完成标志位
先在你的Activity类里定义一个布尔变量,用来标记是否已经完成扫码:
private boolean isScanned = false;
然后修改receiveDetections方法,只有当未扫码时才执行跳转逻辑,处理完成后标记为已扫码:
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() { @Override public void release() { } @Override public void receiveDetections(Detector.Detections<Barcode> detections) { final SparseArray<Barcode> qrcodes = detections.getDetectedItems(); // 增加标志位判断,仅未扫码时处理 if(qrcodes.size() != 0 && !isScanned) { isScanned = true; // 标记已完成扫码 txtResult.post(new Runnable() { @Override public void run() { // 震动反馈 Vibrator vibrator = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(1000); txtResult.setText(qrcodes.valueAt(0).displayValue); // 跳转页面 Intent intent = new Intent(User.this,Menu.class); startActivity(intent); // 可选:如果不想用户返回扫码页面,直接关闭当前页 // finish(); } }); } } });
补充说明:如果用户返回扫码页面后需要重新扫码,记得在onResume方法里把isScanned重置为false:
@Override protected void onResume() { super.onResume(); isScanned = false; }
方法二:扫码成功后停止Detector检测
这种方法更彻底,在扫码成功后直接让Detector停止处理后续帧,避免重复触发:
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() { @Override public void release() { } @Override public void receiveDetections(Detector.Detections<Barcode> detections) { final SparseArray<Barcode> qrcodes = detections.getDetectedItems(); if(qrcodes.size() != 0) { // 先停止Detector的处理器,阻止后续检测回调 barcodeDetector.setProcessor(null); txtResult.post(new Runnable() { @Override public void run() { Vibrator vibrator = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(1000); txtResult.setText(qrcodes.valueAt(0).displayValue); Intent intent = new Intent(User.this,Menu.class); startActivity(intent); } }); } } });
补充说明:如果需要重新启用扫码功能,同样要在onResume里重新设置Detector的Processor。
两种方法都能解决你的问题,第一种更灵活(适合需要重复扫码的场景),第二种更彻底(适合单次扫码的场景),你可以根据自己的需求选择~
内容的提问来源于stack exchange,提问作者Choy
相关产品推荐
相关产品推荐

