1添加插件
cordova plugin add cordova-plugin-qrscanner
2创建html
<!DOCTYPE html>
<html>
<head>
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<link rel="stylesheet" href="../css/ercode.css">
<title>二维码扫描</title>
<style>
button {
margin: .3rem;
}
</style>
</head>
<body>
<div class="app">
<div class="qrscanner">
<div class="qrscanner-area">
</div>
<div class="through-line"></div>
<div class="button-bottom">
<button id="btn1" class="btn btn-primary">
手电筒
</button>
<button id="btn2" class="btn btn-info">
切换摄像头
</button>
</div>
</div>
</div>
<script type="text/javascript" src="../cordova.js"></script>
<script type="text/javascript" src="../js/index.js"></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
var light = false;
var frontCamera = false;
function onDeviceReady() {
if (typeof (QRScanner) != 'undefined') {
//初始化检测,申请摄像头等权限
QRScanner.prepare(onDone); // show the prompt
} else {
alert('插件加载失败');
}
function onDone(err, status) {
if (err) {
console.error(err);
}
if (status.authorized) {
//绑定扫描监听
// `QRScanner.cancelScan()` is called.
QRScanner.scan(displayContents);
function displayContents(err, text) {
if (err) {
// an error occurred, or the scan was canceled (error code `6`)
alert('启动扫描出错:' + JSON.stringify(err));
} else {
// The scan completed, display the contents of the QR code:
alert(text);
QRScanner.scan(displayContents);//重复扫描
}
}
//开始扫描,需要将页面的背景设置成透明
QRScanner.show();
} else if (status.denied) {
alert('用户拒绝访问摄像头');
} else {
}
}
//切换开启手电筒
document.querySelector('#btn1').addEventListener('click', function () {
if (light) {
QRScanner.enableLight();
alert('enableLight');
} else {
QRScanner.disableLight();
}
light = !light;
});
//切换前后摄像头
document.querySelector('#btn2').addEventListener('click', function () {
if (frontCamera) {
QRScanner.useFrontCamera();
alert('useFrontCamera');
} else {
QRScanner.useBackCamera();
}
frontCamera = !frontCamera;
});
}
</script>
</body>
</html>
3编译项目(android)
此过程可能出错,不要着急根据提示信息一步步来,
我主要的问题有:
a编译版本问题
b摄像头权限声明重复
c依赖方式 compile 换成 implementation
d. js文件夹下index.js自动生成的代码报错了,receivedEvent方法中报null了判空处理以下就可以了