使用 QRCodeReaderView(基于 Zxing)
QRCodeReaderView 实现了一个 Android 视图,该视图显示相机并在预览中有 QR 码时通知。
它使用 zxing 开源,多格式 1D / 2D 条码图像处理库。
将库添加到项目中
将 QRCodeReaderView 依赖项添加到 build.gradle
dependencies{
compile 'com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.0'
}
首次使用
- 添加到你的布局
QRCodeReaderView
<com.dlazaro66.qrcodereaderview.QRCodeReaderView
android:id="@+id/qrdecoderview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
- 创建一个实现
onQRCodeReadListener
的 Activity,并将其用作QrCodeReaderView
的监听器。 - 确保你具有相机权限才能使用该库。 ( https://developer.android.com/training/permissions/requesting.html)
然后在你的 Activity 中,你可以按如下方式使用它:
public class DecoderActivity extends Activity implements OnQRCodeReadListener {
private TextView resultTextView;
private QRCodeReaderView qrCodeReaderView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decoder);
qrCodeReaderView = (QRCodeReaderView) findViewById(R.id.qrdecoderview);
qrCodeReaderView.setOnQRCodeReadListener(this);
// Use this function to enable/disable decoding
qrCodeReaderView.setQRDecodingEnabled(true);
// Use this function to change the autofocus interval (default is 5 secs)
qrCodeReaderView.setAutofocusInterval(2000L);
// Use this function to enable/disable Torch
qrCodeReaderView.setTorchEnabled(true);
// Use this function to set front camera preview
qrCodeReaderView.setFrontCamera();
// Use this function to set back camera preview
qrCodeReaderView.setBackCamera();
}
// Called when a QR is decoded
// "text" : the text encoded in QR
// "points" : points where QR control points are placed in View
@Override
public void onQRCodeRead(String text, PointF[] points) {
resultTextView.setText(text);
}
@Override
protected void onResume() {
super.onResume();
qrCodeReaderView.startCamera();
}
@Override
protected void onPause() {
super.onPause();
qrCodeReaderView.stopCamera();
}
}