1.简介:使用Google的开源库 Zxing,但是网上多半的使用教程都是比较早的,这里给出我总结的一些基础代码和使用规则:

首先要一定要先去官网看看:

​github-Zxing官方库的地址​​​
​​​github-zxing-android-embedded 一个非常好用的android工具​

 

2.导入

如果是使用android studio, 那么在gradle文件里添加以下:

compile 'com.google.zxing:core:3.2.1'

或者

compile group: 'com.google.zxing', name: 'core', version: '3.2.1'

 再导入 ZXing Android Embedded

compile 'com.journeyapps:zxing-android-embedded:3.3.0'


3.扫描:

使用扫描的时候,是用到系统的服务的,是从当前的 MainActivity 跳转到 CustomScanActivity

扫描样式可以自定义

MainActivity中:

// 你也可以使用简单的扫描功能,但是一般扫描的样式和行为都是可以自定义的,这里就写关于自定义的代码了
// 你可以把这个方法作为一个点击事件
public void customScan(){
new IntentIntegrator(this)
.setOrientationLocked(false)
.setCaptureActivity(CustomScanActivity.class) // 设置自定义的activity是CustomActivity
.initiateScan(); // 初始化扫描
}

CustomActivity扫描,如果不跳转,则不需要.setCaptureActivity(CustomScanActivity.class),直接在当前页面扫描

 

以下方法获取结果:

@Override
// 通过 onActivityResult的方法获取 扫描回来的 值
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(intentResult != null) {
if(intentResult.getContents() == null) {
Toast.makeText(this,"内容为空",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this,"扫描成功",Toast.LENGTH_LONG).show();
// ScanResult 为 获取到的字符串
String ScanResult = intentResult.getContents();
}
} else {
super.onActivityResult(requestCode,resultCode,data);
}
}

 

 

下面是xml样式:

<!-- 我这里只是在大局下修改了一些样式,不过其实 扫描框中的 各种激光条,边框都可以改变,有兴趣的同学可以自己去搜一下 -->
<!-- 这个控件就是扫描的窗口了 -->
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/dbv_custom"
app:zxing_framing_rect_width="200dp"
app:zxing_framing_rect_height="50dp"

app:zxing_preview_scaling_strategy="fitXY"
app:zxing_use_texture_view="true"
>
</com.journeyapps.barcodescanner.DecoratedBarcodeView>