您的位置:首页 > 移动开发 > Android开发

Android 使用Zxing实现二维码的生成,扫描

2017-03-15 21:54 811 查看
在项目中要使用到二维码的相关内容,百度之后得知一半都是使用Google的开源库 Zxing,但是网上多半的使用教程都是比较早的,这里给出我总结的一些基础代码和使用规则:

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

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


1. 如何导入

如果是使用Android studio, 那么在gradle文件里添加以下:
compile 'com.google.zxing:core:3.2.1'

或者

compile group: 'com.google.zxing', name: 'core', version: '3.2.1'
1
2
3
4
5
1
2
3
4
5

给大家一个网址 在这个里面可以搜索到可以用的Maven库

导入 ZXing Android Embedded
repositories {
jcenter()
}

dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.3.0'
compile 'com.android.support:appcompat-v7:23.1.0'   // Version 23+ is required || 要求版本23以上
}

android {
buildToolsVersion '23.0.2' // Older versions may give compile errors || 更早的版本可能会报错
}
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12


如何生成一个二维码?

以下这个方法,传入一个字符串,生成一个二维码的Bitmap,可以用于显示
Bitmap encodeAsBitmap(String str){
Bitmap bitmap = null;
BitMatrix result = null;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 200, 200);
// 使用 ZXing Android Embedded 要写的代码
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
bitmap = barcodeEncoder.createBitmap(result);
} catch (WriterException e){
e.printStackTrace();
} catch (IllegalArgumentException iae){ // ?
return null;
}

// 如果不使用 ZXing Android Embedded 的话,要写的代码

//        int w = result.getWidth();
//        int h = result.getHeight();
//        int[] pixels = new int[w * h];
//        for (int y = 0; y < h; y++) {
//            int offset = y * w;
//            for (int x = 0; x < w; x++) {
//                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
//            }
//        }
//        bitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
//        bitmap.setPixels(pixels,0,100,0,0,w,h);

return bitmap;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

是不是使用ZXing Android Embedded的好处就很明显了?之后的扫描和生成功能,就不分开讨论了


如何扫描?

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

扫描的样式是完全 可以 自定义的

以下是相关代码:

MainActivity中:
// 你也可以使用简单的扫描功能,但是一般扫描的样式和行为都是可以自定义的,这里就写关于自定义的代码了
// 你可以把这个方法作为一个点击事件
public void customScan(){
new IntentIntegrator(this)
.setOrientationLocked(false)
.setCaptureActivity(CustomScanActivity.class) // 设置自定义的activity是CustomActivity
.initiateScan(); // 初始化扫描
}
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8
@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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

CustomScanActivity 添加了 打开闪光灯button,和两个做样子的button

对应的 layout 文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.zhaojun.zxingtest.CustomScanActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SwitchLight"
android:id="@+id/btn_switch"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hint_1"
android:id="@+id/btn_hint1"
android:layout_alignTop="@+id/btn_switch"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hint_2"
android:id="@+id/btn_hint2"
android:layout_alignTop="@+id/btn_hint1"
android:layout_alignParentEnd="true" />

<!-- 我这里只是在大局下修改了一些样式,不过其实 扫描框中的 各种激光条,边框都可以改变,有兴趣的同学可以自己去搜一下 -->
<!-- 这个控件就是扫描的窗口了 -->
<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"
android:layout_above="@+id/btn_switch"
android:layout_alignEnd="@+id/btn_hint2">
</com.journeyapps.barcodescanner.DecoratedBarcodeView>

</RelativeLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

Java文件 其中有使用 ButterKnife
public class CustomScanActivity extends AppCompatActivity implements DecoratedBarcodeView.TorchListener{ // 实现相关接口
// 添加一个按钮用来控制闪光灯,同时添加两个按钮表示其他功能,先用Toast表示

@BindView(R.id.btn_switch) Button swichLight;
@BindView(R.id.btn_hint1) Button hint1Show;
@BindView(R.id.btn_hint2) Button hint2Show;
@BindView(R.id.dbv_custom) DecoratedBarcodeView mDBV;

private CaptureManager captureManager;
private boolean isLightOn = false;

@Override
protected void onPause() {
super.onPause();
captureManager.onPause();
}

@Override
protected void onResume() {
super.onResume();
captureManager.onResume();
}

@Override
protected void onDestroy() {
super.onDestroy();
captureManager.onDestroy();
}

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
captureManager.onSaveInstanceState(outState);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return mDBV.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_scan);
ButterKnife.bind(this);

mDBV.setTorchListener(this);

// 如果没有闪光灯功能,就去掉相关按钮
if(!hasFlash()) {
swichLight.setVisibility(View.GONE);
}

//重要代码,初始化捕获
captureManager = new CaptureManager(this,mDBV);
captureManager.initializeFromIntent(getIntent(),savedInstanceState);
captureManager.decode();
}

// torch 手电筒
@Override
public void onTorchOn() {
Toast.makeText(this,"torch on",Toast.LENGTH_LONG).show();
isLightOn = true;
}

@Override
public void onTorchOff() {
Toast.makeText(this,"torch off",Toast.LENGTH_LONG).show();
isLightOn = false;
}

// 判断是否有闪光灯功能
private boolean hasFlash() {
return getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}

// 点击切换闪光灯
@OnClick(R.id.btn_switch)
public void swichLight(){
if(isLightOn){
mDBV.setTorchOff();
}else{
mDBV.setTorchOn();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

核心代码其实很少,比较容易掌握

转自:http://blog.csdn.net/qq_28057541/article/details/52034988 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐