编辑 build.gradle (App) 文件并添加以下依赖项:
compile 'com.journeyapps:zxing-android-embedded:3.4.0'
在 Activity 类中声明以下变量:
IntentIntegrator qrScan;
在 OnCreate 方法中编写以下代码:
qrScan = new IntentIntegrator(this);
qrScan.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
您的按钮功能如下:
public void startScan(View view) {
qrScan.initiateScan();
}
现在它将开始扫描,但它需要以下方法来读取结果:
因此,请像下面一样对同一 Activity 使用 OnActivityResult 方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "Result Not Found", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, result.getContents() ,Toast.LENGTH_LONG).show();
txt.setText(result.getContents());
qrScan.initiateScan();
}
}
}
请参阅下面的链接,它将以简单的形式为您提供更多想法。
https://www.simplifiedcoding.net/android-qr-code-scanner-tutorial/