实现扫码功能
使用的是集成华为扫描的SDK,UI界面借鉴的是谷歌官方的Zxing项目中的自定义view,两者结合实现。
先上效果图:
- 先在项目根级别(build.gradle)当中配置HMS Core SDK的Maven仓地址。
// 配置HMS Core SDK的Maven仓地址。
maven {url 'https://developer.huawei.com/repo/'}`
2. 在对应module的build.gradle(Module:app)中添加依赖
dependencies {
implementation 'com.huawei.hms:scanplus:1.3.2.300'
}
- 在清单文件里面添加静态权限
<!-- 读文件权限 -->
<uses-feature android:name="android.hardware.camera.autofocus" /> <!-- 使用特性 -->
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- 相机权限 -->
<uses-permission android:name="android.permission.CAMERA" />
- 还需要在代码中申请相机的动态权限
public static final int DEFINED_CODE = 222;
public static final int DECODE = 1;
//跳转到扫描界面的监听中调用
requestPermission(DEFINED_CODE, DECODE);
private void requestPermission(int requestCode, int mode) {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
requestCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (permissions == null || grantResults == null) {
return;
}
if (grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
return;
}
//Customized View Mode 使用的是自定义扫码界面 所以这块权限请求成功后才跳转到扫码界面
if (requestCode == DEFINED_CODE) {
Intent intent = new Intent(this, CustomizedViewActivity.class);
this.startActivityForResult(intent, REQUEST_CODE_DEFINE);
}
}
//此处是扫描界面处理完成的扫描结果回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || data == null) {
return;
}
//Customized View
if (requestCode == REQUEST_CODE_DEFINE) {
HmsScan obj = data.getParcelableExtra(CustomizedViewActivity.SCAN_RESULT);
if (obj != null) {
//拿到扫描信息根据自己需求自行处理
Toast.makeText(this, obj.originalValue, Toast.LENGTH_SHORT).show();
}
}
}
5.**扫描界面 **
xml显示:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.CustomizedViewActivity">
<FrameLayout
android:id="@+id/rim"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:background="#FF000000"
android:alpha="0.1" />
<com.example.jianzhuapplication.view.ViewfinderView