参考链接: 1. dsbridge使用说明 2. zxing使用说明
需求
在Android的APP中使用webview加载vue项目,项目中需要调用手机摄像头实现扫码并根据扫码的结果跳转到另一页面
步骤
1.添加 JitPack repository 到gradle脚本中
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
2.添加依赖
dependencies {
implementation 'com.github.wendux:DSBridge-Android:x5-3.0-SNAPSHOT'
}
3.Android中调用
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DWebView.setWebContentsDebuggingEnabled(true);
setContentView(R.layout.activity_main);
view = (DWebView) findViewById(R.id.mainView);
this.viewSettings(view);
view.addJavascriptObject(new QrCodeJsApi() {
@Override
@JavascriptInterface
public String readQrCode(Object msg) {
startQrCode();// 使用zxing扫码
return "";
}
}
}
// 开始扫码
private void startQrCode() {
Log.d(TAG, "开始扫码");
// 申请相机权限
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// 申请权限
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
return;
}
// 申请文件读写权限(部分朋友遇到相册选图需要读写权限的情况,这里一并写一下)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// 申请权限
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
return;
}
// 二维码扫码
Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent, Constant.REQ_QR_CODE);
}
4.Vue中调用
首先npm执行npm i dsbridge
安装dsbridge
<script>
var dsBridge = require("dsbridge");
export default {
created() {
dsBridge.register("setQrCode", (res) => {
this.scanResult(res);
return res;
});
},
methods: {
scanner() {
// 同步调用
var synRes = dsBridge.call("readQrCode", "readQrCode");
// 异步调用
// dsBridge.call("readQrCode", "readQrCode", (res) => {
// let result = res.resultStr;
// this.scanResult(result);
// console.log(res);
// });
},
// 扫码成功后的操作
scanResult(result) {
// result就是扫描的结果,在这边对扫码结果进行处理
// this.$axios
// .get(process.env.API_HOST + "qrCode/selectNodeByCode", {
// params: { qrCode: result },
// })
// .then((res) => {
// });
}
}
</script>