Android 使用Zxing实现二维码的生成,扫描
2016-07-26 14:37
761 查看
在项目中要使用到二维码的相关内容,百度(原谅我还在用)之后得知一半都是使用Google的开源库 Zxing,但是网上多半的使用教程都是比较早的,这里给出我总结的一些基础代码和使用规则:
首先要一定要先去官网看看:
github-Zxing官方库的地址
github-zxing-android-embedded 一个非常好用的android工具
给大家一个网址 在这个里面可以搜索到可以用的Maven库
导入 ZXing Android Embedded
是不是使用ZXing Android Embedded的好处就很明显了?之后的扫描和生成功能,就不分开讨论了
扫描的样式是完全 可以 自定义的
以下是相关代码:
MainActivity中:
CustomScanActivity 添加了 打开闪光灯button,和两个做样子的button
对应的 layout 文件
java文件 其中有使用 ButterKnife
核心代码其实很少,比较容易掌握
首先要一定要先去官网看看:
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'
给大家一个网址 在这个里面可以搜索到可以用的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 || 更早的版本可能会报错 }
如何生成一个二维码?
以下这个方法,传入一个字符串,生成一个二维码的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; }
是不是使用ZXing Android Embedded的好处就很明显了?之后的扫描和生成功能,就不分开讨论了
如何扫描?
使用扫描的时候,是用到系统的服务的,是从当前的 MainActivity 跳转到 CustomScanActivity扫描的样式是完全 可以 自定义的
以下是相关代码:
MainActivity中:
// 你也可以使用简单的扫描功能,但是一般扫描的样式和行为都是可以自定义的,这里就写关于自定义的代码了 // 你可以把这个方法作为一个点击事件 public void customScan(){ new IntentIntegrator(this) .setOrientationLocked(false) .setCaptureActivity(CustomScanActivity.class) // 设置自定义的activity是CustomActivity .initiateScan(); // 初始化扫描 }
@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); } }
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>
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(); } } }
核心代码其实很少,比较容易掌握
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories