zxing二维码扫描
2020-12-25 本文已影响0人
Amy木婉清
生成二维码的网站:草料二维码
网址:https://cli.im/?fromTopNav=1
实现效果,点击扫一扫,读取扫描二维码的内容,效果图如下:
如何实现
首先添加依赖:
build添加依赖:
//zxing二维码扫描
implementation 'cn.yipianfengye.android:zxing-library:2.2'
//rxPermissons
implementation 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.3@aar'
//网络请求
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.7.0'
同时在清单文件里进行声明权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
其次在activity中动态申请权限:
// 动态申请权限
private void checkCameraPermission() {
RxPermissions rxPermission = new RxPermissions(this);
rxPermission.request(Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Exception {
if (aBoolean) {
//多个权限全部允许
startScanActivity();
} else {
//只要有一个权限禁止,返回false,
//下一次申请只申请没通过申请的权限
Toast.makeText(MainActivity.this,"该操作需要允许权限",Toast.LENGTH_SHORT).show();
}
}
});
}
在二维码Activity中实现的部分代码逻辑:
/**
* 二维码解析回调函数
*/
CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
@Override
public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
analysisCode(result);
}
@Override
public void onAnalyzeFailed() {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
bundle.putString(CodeUtils.RESULT_STRING, "");
resultIntent.putExtras(bundle);
ScanActivity.this.setResult(RESULT_OK, resultIntent);
ScanActivity.this.finish();
}
};
/**
* 识别二维码
*
* @param result
*/
private void analysisCode(String result) {
if (isEmpty(result)) {
Toast.makeText(ScanActivity.this,"请检查二维码信息是否正确",Toast.LENGTH_SHORT).show();
return;
}
Log.e("QRINFO", "sn:" + result);
}