今天公司有需求,有个扫描二维码的需求,刚开始以为很简单,就直接开始干,添加zxing依赖:
compile 'com.journeyapps:zxing-android-embedded:3.5.0' compile 'com.google.zxing:core:3.3.0'
然后就是干:
IntentIntegrator integrator = new IntentIntegrator(mCtx); // 设置要扫描的条码类型,ONE_D_CODE_TYPES:一维码,QR_CODE_TYPES-二维码 integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES); integrator.setCaptureActivity(ScanActivity.class); integrator.setPrompt("将二维码放到框内即可"); //底部的提示文字,设为""可以置空 integrator.setCameraId(0); //前置或者后置摄像头 integrator.setBeepEnabled(true); //扫描成功的「哔哔」声,默认开启 integrator.setBarcodeImageEnabled(true); integrator.initiateScan();
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode==AppConstants.PARK_NUM_QR_CODE){ if (data!=null){ parknum = data.getStringExtra("parkNum"); } }else{ LogUtils.e("什么鬼","扫描结果daowo le e "); IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); LogUtils.e("什么鬼","扫描结果"+intentResult); if (intentResult!=null){ if (intentResult.getContents()==null){ ToastUtils.showShortToast("扫码取消"); }else { ToastUtils.showShortToast(intentResult.getContents()+"扫描成功"); } } } }
在onactivityresult中接收扫描结果,但是问题出现了,可以到扫描界面,但是扫描结果死活不出来,没有toast...
然后打断点,发现在扫描完之后,没有到onactivityresult方法中来...百思不得其解,然后一顿搜索,在以为大哥的博客中发现一句:IntentIntegrator有两个方法是forFragment和forSupportFragment应该是用于支持Fragment和支持库版本的Fragment,然后想到我是用viewpager+tablayout+fragment的,并且在fragment中使用zxing....
就想试一试会不会是zxing在fragment中不是这样调用的,然后点击进去果然发现zxing中有这个方法:
/** * @param fragment {@link Fragment} invoking the integration. * {@link #startActivityForResult(Intent, int)} will be called on the {@link Fragment} instead * of an {@link Activity} */ public static IntentIntegrator forSupportFragment(android.support.v4.app.Fragment fragment) { IntentIntegrator integrator = new IntentIntegrator(fragment.getActivity()); integrator.supportFragment = fragment; return integrator; }
于是,就把以前的代码改为:
// IntentIntegrator integrator = new IntentIntegrator(mCtx); IntentIntegrator integrator = IntentIntegrator.forSupportFragment(this); // 设置要扫描的条码类型,ONE_D_CODE_TYPES:一维码,QR_CODE_TYPES-二维码 integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES); integrator.setCaptureActivity(ScanActivity.class); integrator.setPrompt("将二维码放到框内即可"); //底部的提示文字,设为""可以置空 integrator.setCameraId(0); //前置或者后置摄像头 integrator.setBeepEnabled(true); //扫描成功的「哔哔」声,默认开启 integrator.setBarcodeImageEnabled(true); integrator.initiateScan();
其他的不变,运行...果然,扫描结果就toast出来了...
也没费多大功夫,哈哈,记录一下,作为心得....