1、build.gradle中dependencies引用。
implementation 'com.journeyapps:zxing-android-embedded:3.5.0'
2、Activity、Fragment区别。
Activity调用:
IntentIntegrator integrator = new IntentIntegrator(this);
Fragment调用:
IntentIntegrator integrator = IntentIntegrator.forSupportFragment(FragTask.this);
//IntentIntegrator integrator = new IntentIntegrator(this); IntentIntegrator integrator = IntentIntegrator.forSupportFragment(FragTask.this); // 设置要扫描的条码类型 ONE_D_CODE_TYPES 一维码 QR_CODE_TYPES 二维码 integrator.setPrompt("请对准二维码"); // 设置提示语 integrator.setCameraId(0); // 选择摄像头,可使用前置或者后置 integrator.setBeepEnabled(true); // 是否开启声音,扫完码之后会"哔"的一声 integrator.setBarcodeImageEnabled(false); // 扫完码之后生成二维码的图片 integrator.initiateScan(); // 初始化扫码 // 扫完码之后会在onActivityResult方法中回调结果 @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null) { if (result.getContents() == null) { //Toast.makeText(this, "", Toast.LENGTH_LONG).show(); } else { //Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show(); Log.e("扫码", result.getContents()); } } else { super.onActivityResult(requestCode, resultCode, data); } }