欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现基于ZXing快速集成二维码扫描功能

程序员文章站 2022-07-02 11:59:08
二维码扫描现在是一直比较多的应用场景,android的开源项目zxing提供了完整、成熟的解决方案,如果仅仅是出于快速开发的目的,可以根据自己的项目需要,把zxing官方提...

二维码扫描现在是一直比较多的应用场景,android的开源项目zxing提供了完整、成熟的解决方案,如果仅仅是出于快速开发的目的,可以根据自己的项目需要,把zxing官方提供的项目稍加裁剪,就可以快速的集成到自己的项目中。下面详细演示和介绍如何实现基于zxing官方提供的源码,快速集成二维码扫描功能到自己项目中的解决方案。 

(第1步):到zxing官方主页下载最新的项目代码包,zxing在github的官方主页:,下载后解压。解压后根目录下有若干项目目录,其中的:android就是我们需要的项目,把它导入到eclispse中。 

(第2步):zxing的android项目需要引用两个关键的库文件:android-core-x.x.x.jarcore-x.x.x.jar,其中x.x.x表示版本号。截止发表本博文时候,版本已经是3.2.0了。这两个关键的android-core-x.x.x.jar 和 core-x.x.x.jar 文件,实际上都可以从第一步下载得到的源代码中自己编译生成,网上也有编译的具体方案,但简单期间,也可以从zxing的官方直接下载已经编译好的文件,其中android-core的下载链接是:,另外一个zxing的core下载链接是: ,选择最新版本的库文件或者自己需要的版本号,下载后,和其他android项目中导入库文件类似,导入到android项目中的libs目录下,如果没有libs,新建一个名为libs的目录,把两个库文件放进去即可。 

(第3步):这一步作为演示,我们自己新建一个mainactiviy,作为项目的启动器activity,app将启动我们自己的mainactivity。观察zxing官方提供的androidmanifest.xml文件: 

<?xml version="1.0" encoding="utf-8"?>
<!--
 copyright (c) 2008 zxing authors

 licensed under the apache license, version 2.0 (the "license");
 you may not use this file except in compliance with the license.
 you may obtain a copy of the license at

  http://www.apache.org/licenses/license-2.0

 unless required by applicable law or agreed to in writing, software
 distributed under the license is distributed on an "as is" basis,
 without warranties or conditions of any kind, either express or implied.
 see the license for the specific language governing permissions and
 limitations under the license.
 -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.google.zxing.client.android"
   android:versionname="4.7.3"
   android:versioncode="103"
   android:installlocation="auto">

 <uses-permission android:name="android.permission.camera"/>
 <uses-permission android:name="android.permission.internet"/>
 <uses-permission android:name="android.permission.vibrate"/>
 <uses-permission android:name="android.permission.flashlight"/>
 <uses-permission android:name="android.permission.read_contacts"/>
 <uses-permission android:name="com.android.browser.permission.read_history_bookmarks"/>
 <uses-permission android:name="android.permission.write_external_storage"/>
 <uses-permission android:name="android.permission.change_wifi_state"/>
 <uses-permission android:name="android.permission.access_wifi_state"/>

 <uses-sdk android:minsdkversion="15" android:targetsdkversion="21"/>

 <!-- don't require camera, as this requires a rear camera. this allows it to work on the nexus 7 -->
 <uses-feature android:name="android.hardware.camera" android:required="false"/>
 <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
 <!-- todo replace above two with next line after android 4.2 -->
 <!-- <uses-feature android:name="android.hardware.camera.any"/> -->
 <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
 <uses-feature android:name="android.hardware.camera.flash" android:required="false"/>
 <uses-feature android:name="android.hardware.screen.landscape"/>
 <uses-feature android:name="android.hardware.wifi" android:required="false"/>
 <!-- this excludes google tv, which is unfortunately included by virtue of not requiring a camera -->
 <uses-feature android:name="android.hardware.touchscreen"/>
 <!-- todo make this not required again after android.hardware.camera.any is available -->

 <supports-screens android:xlargescreens="true"
     android:largescreens="true"
     android:normalscreens="true"
     android:smallscreens="true"
     android:anydensity="true"/>

 <application android:icon="@drawable/launcher_icon"
    android:logo="@drawable/launcher_icon"
    android:label="@string/app_name"
    android:allowbackup="true">
 <activity android:name=".captureactivity"
    android:screenorientation="sensorlandscape"
    android:cleartaskonlaunch="true"
    android:statenotneeded="true"
    android:theme="@style/capturetheme"
    android:windowsoftinputmode="statealwayshidden">
  <intent-filter>
  <action android:name="android.intent.action.main"/>
  <category android:name="android.intent.category.launcher"/>
  </intent-filter>
  <intent-filter>
  <action android:name="com.google.zxing.client.android.scan"/>
  <category android:name="android.intent.category.default"/>
  </intent-filter>
  <!-- allow web apps to launch barcode scanner by linking to http://zxing.appspot.com/scan. -->
  <intent-filter>
  <action android:name="android.intent.action.view"/>
  <category android:name="android.intent.category.default"/>
  <category android:name="android.intent.category.browsable"/>
  <data android:scheme="http" android:host="zxing.appspot.com" android:path="/scan"/>
  </intent-filter>
  <!-- we also support a google product search url. -->
  <intent-filter>
  <action android:name="android.intent.action.view"/>
  <category android:name="android.intent.category.default"/>
  <category android:name="android.intent.category.browsable"/>
  <data android:scheme="http" android:host="www.google.com" android:path="/m/products/scan"/>
  </intent-filter>
  <!-- and the uk version. -->
  <intent-filter>
  <action android:name="android.intent.action.view"/>
  <category android:name="android.intent.category.default"/>
  <category android:name="android.intent.category.browsable"/>
  <data android:scheme="http" android:host="www.google.co.uk" android:path="/m/products/scan"/>
  </intent-filter>
  <!-- support zxing://scan/?... like iphone app -->
  <intent-filter>
  <action android:name="android.intent.action.view"/>
  <category android:name="android.intent.category.default"/>
  <category android:name="android.intent.category.browsable"/>
  <data android:scheme="zxing" android:host="scan" android:path="/"/>
  </intent-filter>
 </activity>
 <activity android:name=".preferencesactivity"
    android:label="@string/preferences_name"
    android:statenotneeded="true"/>
 <activity android:name=".encode.encodeactivity"
    android:statenotneeded="true">
  <intent-filter>
  <action android:name="com.google.zxing.client.android.encode"/>
  <category android:name="android.intent.category.default"/>
  </intent-filter>
  <!-- this allows us to handle the share button in contacts. -->
  <intent-filter>
  <action android:name="android.intent.action.send"/>
  <category android:name="android.intent.category.default"/>
  <data android:mimetype="text/x-vcard"/>
  </intent-filter>
  <!-- this allows us to handle sharing any plain text . -->
  <intent-filter>
  <action android:name="android.intent.action.send"/>
  <category android:name="android.intent.category.default"/>
  <data android:mimetype="text/plain"/>
  </intent-filter>
 </activity>
 <activity android:name=".book.searchbookcontentsactivity"
    android:label="@string/sbc_name"
    android:statenotneeded="true"
    android:screenorientation="sensorlandscape">
  <intent-filter>
  <action android:name="com.google.zxing.client.android.search_book_contents"/>
  <category android:name="android.intent.category.default"/>
  </intent-filter>
 </activity>
 <activity android:name=".share.shareactivity"
    android:statenotneeded="true"
    android:screenorientation="user">
  <intent-filter>
  <action android:name="com.google.zxing.client.android.share"/>
  <category android:name="android.intent.category.default"/>
  </intent-filter>
 </activity>
 <activity android:name=".history.historyactivity"
    android:label="@string/history_title"
    android:statenotneeded="true"/>
 <activity android:name=".share.bookmarkpickeractivity"
    android:label="@string/bookmark_picker_name"
    android:statenotneeded="true"/>
 <activity android:name=".share.apppickeractivity"
    android:label="@string/app_picker_name"
    android:statenotneeded="true"/>
 <activity android:name=".helpactivity"
    android:label="@string/menu_help"
    android:screenorientation="user"
    android:statenotneeded="true"/>
 </application>

</manifest>

其实zxing官方的项目已经作为为第三方提供集成的代码了,比如其中的关键activity:.\src\com\google\zxing\client\android\captureactivity.java,在声明中已经提供好了从各种入口访问的intent的action。所以在我们自己新建的mainactivity中,直接隐式指定一个intent的action,启动之即可: 

package com.google.zxing.client.android;

import android.app.activity;
import android.content.intent;
import android.os.bundle;
import android.widget.toast;

public class mainactivity extends activity {

 private final int request_code = 0xa1;

 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);

 intent intent = new intent();
 //隐式指定
 intent.setaction("com.google.zxing.client.android.scan");
 
 //启动zxing已经写好、且我们做小量修改后的captureactivity。
 startactivityforresult(intent, request_code);
 }

 @override
 protected void onactivityresult(int requestcode, int resultcode, intent data) {
 super.onactivityresult(requestcode, resultcode, data);

 //我们需要的结果返回
 if (requestcode == request_code && resultcode == activity.result_ok) {

 //result就是二维码扫描的结果。
 string result = data.getstringextra("result");

 toast.maketext(getapplicationcontext(), result, toast.length_short)
  .show();
 }
 }
}

因为我们启动zxing的captureactivity不是目的,真正的目的是启动zxing的captureactivity获得二维码扫描结果,因此以startactivityforresult()的方式启动。相应的,我们需要重写:protected void onactivityresult(int requestcode, int resultcode, intent data),以回调等待传回结果。

(第4步):这一步是重点。在.\src\com\google\zxing\client\android\目录下的captureactivity.java中的方法: public void handledecode(result rawresult, bitmap barcode, float scalefactor);此方法是一个回调函数。zxing项目中写好的扫描模块扫描后返回回调此方法,zxing官方的原始 public void handledecode(result rawresult, bitmap barcode, float scalefactor)方法是这样的: 

/**
 * a valid barcode has been found, so give an indication of success and show the results.
 *
 * @param rawresult the contents of the barcode.
 * @param scalefactor amount by which thumbnail was scaled
 * @param barcode a greyscale bitmap of the camera data which was decoded.
 */
 public void handledecode(result rawresult, bitmap barcode, float scalefactor) {
 inactivitytimer.onactivity();
 lastresult = rawresult;
 resulthandler resulthandler = resulthandlerfactory.makeresulthandler(this, rawresult);

 boolean fromlivescan = barcode != null;
 if (fromlivescan) {
  historymanager.addhistoryitem(rawresult, resulthandler);
  // then not from history, so beep/vibrate and we have an image to draw on
  beepmanager.playbeepsoundandvibrate();
  drawresultpoints(barcode, scalefactor, rawresult);
 }

 switch (source) {
  case native_app_intent:
  case product_search_link:
  handledecodeexternally(rawresult, resulthandler, barcode);
  break;
  case zxing_link:
  if (scanfromwebpagemanager == null || !scanfromwebpagemanager.isscanfromwebpage()) {
   handledecodeinternally(rawresult, resulthandler, barcode);
  } else {
   handledecodeexternally(rawresult, resulthandler, barcode);
  }
  break;
  case none:
  sharedpreferences prefs = preferencemanager.getdefaultsharedpreferences(this);
  if (fromlivescan && prefs.getboolean(preferencesactivity.key_bulk_mode, false)) {
   toast.maketext(getapplicationcontext(),
       getresources().getstring(r.string.msg_bulk_mode_scanned) + " (" + rawresult.gettext() + ')',
       toast.length_short).show();
   // wait a moment or else it will scan the same barcode continuously about 3 times
   restartpreviewafterdelay(bulk_mode_scan_delay_ms);
  } else {
   handledecodeinternally(rawresult, resulthandler, barcode);
  }
  break;
 }
 }

 我们将精简此方法,定制自己所需要的内容,为满足我们自己项目中的需求,把此方法修改后的代码为:

 public void handledecode(result rawresult, bitmap barcode, float scalefactor) {
 inactivitytimer.onactivity();
 lastresult = rawresult;
 resulthandler resulthandler = resulthandlerfactory.makeresulthandler(this, rawresult);

 boolean fromlivescan = barcode != null;
 if (fromlivescan) {
  historymanager.addhistoryitem(rawresult, resulthandler);
  // then not from history, so beep/vibrate and we have an image to draw on
  beepmanager.playbeepsoundandvibrate();
  drawresultpoints(barcode, scalefactor, rawresult);
 }
 
 
 //在这里增加我们的代码,目的是:做最小量的修改,仅仅把zxing提供的captureactivity作为一个中间使用的activity集成到我们自己的项目。
 //启动实现二维码扫描,返回一个结果就可以了。
 //然后结束这个activity。
 intent intent=new intent();
 //<key,value>形式存储二维码结果。
 //rawresult.gettext()即为二维码结果。
 intent.putextra("result", rawresult.gettext());
 this.setresult(activity.result_ok, intent);
 this.finish();
 
 
 /**
 以下是zxing提供的源码,根据项目需要可以删减使用。
 简单期间,我们只需要二维码扫描后返回一个扫描的字符串结果。
 所以在次暂时注释掉。
 
 switch (source) {
  case native_app_intent:
  case product_search_link:
  handledecodeexternally(rawresult, resulthandler, barcode);
  break;
  case zxing_link:
  if (scanfromwebpagemanager == null || !scanfromwebpagemanager.isscanfromwebpage()) {
   handledecodeinternally(rawresult, resulthandler, barcode);
  } else {
   handledecodeexternally(rawresult, resulthandler, barcode);
  }
  break;
  case none:
  sharedpreferences prefs = preferencemanager.getdefaultsharedpreferences(this);
  if (fromlivescan && prefs.getboolean(preferencesactivity.key_bulk_mode, false)) {
   toast.maketext(getapplicationcontext(),
       getresources().getstring(r.string.msg_bulk_mode_scanned) + " (" + rawresult.gettext() + ')',
       toast.length_short).show();
   // wait a moment or else it will scan the same barcode continuously about 3 times
   restartpreviewafterdelay(bulk_mode_scan_delay_ms);
  } else {
   handledecodeinternally(rawresult, resulthandler, barcode);
  }
  break;
 }
 
 **/
 }

 (第5步):这一步比较简单,是剩余的收尾工作,修改androidmanifest.xml文件,把我们的mainactivity作为主activity启动。把zxing的captureactivity作为一个普通的activity。 

修改后的androidmanifest.xml文件:

 <?xml version="1.0" encoding="utf-8"?>
<!--
 copyright (c) 2008 zxing authors

 licensed under the apache license, version 2.0 (the "license");
 you may not use this file except in compliance with the license.
 you may obtain a copy of the license at

  http://www.apache.org/licenses/license-2.0

 unless required by applicable law or agreed to in writing, software
 distributed under the license is distributed on an "as is" basis,
 without warranties or conditions of any kind, either express or implied.
 see the license for the specific language governing permissions and
 limitations under the license.
 -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.google.zxing.client.android"
   android:versionname="4.7.3"
   android:versioncode="103"
   android:installlocation="auto">

 <uses-permission android:name="android.permission.camera"/>
 <uses-permission android:name="android.permission.internet"/>
 <uses-permission android:name="android.permission.vibrate"/>
 <uses-permission android:name="android.permission.flashlight"/>
 <uses-permission android:name="android.permission.read_contacts"/>
 <uses-permission android:name="com.android.browser.permission.read_history_bookmarks"/>
 <uses-permission android:name="android.permission.write_external_storage"/>
 <uses-permission android:name="android.permission.change_wifi_state"/>
 <uses-permission android:name="android.permission.access_wifi_state"/>

 <uses-sdk android:minsdkversion="15" android:targetsdkversion="21"/>

 <!-- don't require camera, as this requires a rear camera. this allows it to work on the nexus 7 -->
 <uses-feature android:name="android.hardware.camera" android:required="false"/>
 <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
 <!-- todo replace above two with next line after android 4.2 -->
 <!-- <uses-feature android:name="android.hardware.camera.any"/> -->
 <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
 <uses-feature android:name="android.hardware.camera.flash" android:required="false"/>
 <uses-feature android:name="android.hardware.screen.landscape"/>
 <uses-feature android:name="android.hardware.wifi" android:required="false"/>
 <!-- this excludes google tv, which is unfortunately included by virtue of not requiring a camera -->
 <uses-feature android:name="android.hardware.touchscreen"/>
 <!-- todo make this not required again after android.hardware.camera.any is available -->

 <supports-screens android:xlargescreens="true"
     android:largescreens="true"
     android:normalscreens="true"
     android:smallscreens="true"
     android:anydensity="true"/>

 <application android:icon="@drawable/launcher_icon"
    android:logo="@drawable/launcher_icon"
    android:label="@string/app_name"
    android:allowbackup="true">
  
  
 <!-- 新增的我们自己的mainactiviy作为启动activity -->
 <activity
   android:name=".mainactivity"
   android:label="@string/app_name" >
   <intent-filter>
    <action android:name="android.intent.action.main" />
    <category android:name="android.intent.category.launcher" />
   </intent-filter>
 </activity>
  
  
 <activity android:name=".captureactivity"
    android:screenorientation="sensorlandscape"
    android:cleartaskonlaunch="true"
    android:statenotneeded="true"
    android:theme="@style/capturetheme"
    android:windowsoftinputmode="statealwayshidden">
  
  <!-- 
  把zxing官方提供的作为 main activity启动的captureactivity作为一个普通activiy。
  
  <intent-filter>
  <action android:name="android.intent.action.main"/>
  <category android:name="android.intent.category.launcher"/>
  </intent-filter>
  
  --> 
  
  
  <intent-filter>
  <action android:name="com.google.zxing.client.android.scan"/>
  <category android:name="android.intent.category.default"/>
  </intent-filter>
  <!-- allow web apps to launch barcode scanner by linking to http://zxing.appspot.com/scan. -->
  <intent-filter>
  <action android:name="android.intent.action.view"/>
  <category android:name="android.intent.category.default"/>
  <category android:name="android.intent.category.browsable"/>
  <data android:scheme="http" android:host="zxing.appspot.com" android:path="/scan"/>
  </intent-filter>
  <!-- we also support a google product search url. -->
  <intent-filter>
  <action android:name="android.intent.action.view"/>
  <category android:name="android.intent.category.default"/>
  <category android:name="android.intent.category.browsable"/>
  <data android:scheme="http" android:host="www.google.com" android:path="/m/products/scan"/>
  </intent-filter>
  <!-- and the uk version. -->
  <intent-filter>
  <action android:name="android.intent.action.view"/>
  <category android:name="android.intent.category.default"/>
  <category android:name="android.intent.category.browsable"/>
  <data android:scheme="http" android:host="www.google.co.uk" android:path="/m/products/scan"/>
  </intent-filter>
  <!-- support zxing://scan/?... like iphone app -->
  <intent-filter>
  <action android:name="android.intent.action.view"/>
  <category android:name="android.intent.category.default"/>
  <category android:name="android.intent.category.browsable"/>
  <data android:scheme="zxing" android:host="scan" android:path="/"/>
  </intent-filter>
 </activity>
 <activity android:name=".preferencesactivity"
    android:label="@string/preferences_name"
    android:statenotneeded="true"/>
 <activity android:name=".encode.encodeactivity"
    android:statenotneeded="true">
  <intent-filter>
  <action android:name="com.google.zxing.client.android.encode"/>
  <category android:name="android.intent.category.default"/>
  </intent-filter>
  <!-- this allows us to handle the share button in contacts. -->
  <intent-filter>
  <action android:name="android.intent.action.send"/>
  <category android:name="android.intent.category.default"/>
  <data android:mimetype="text/x-vcard"/>
  </intent-filter>
  <!-- this allows us to handle sharing any plain text . -->
  <intent-filter>
  <action android:name="android.intent.action.send"/>
  <category android:name="android.intent.category.default"/>
  <data android:mimetype="text/plain"/>
  </intent-filter>
 </activity>
 <activity android:name=".book.searchbookcontentsactivity"
    android:label="@string/sbc_name"
    android:statenotneeded="true"
    android:screenorientation="sensorlandscape">
  <intent-filter>
  <action android:name="com.google.zxing.client.android.search_book_contents"/>
  <category android:name="android.intent.category.default"/>
  </intent-filter>
 </activity>
 <activity android:name=".share.shareactivity"
    android:statenotneeded="true"
    android:screenorientation="user">
  <intent-filter>
  <action android:name="com.google.zxing.client.android.share"/>
  <category android:name="android.intent.category.default"/>
  </intent-filter>
 </activity>
 <activity android:name=".history.historyactivity"
    android:label="@string/history_title"
    android:statenotneeded="true"/>
 <activity android:name=".share.bookmarkpickeractivity"
    android:label="@string/bookmark_picker_name"
    android:statenotneeded="true"/>
 <activity android:name=".share.apppickeractivity"
    android:label="@string/app_picker_name"
    android:statenotneeded="true"/>
 <activity android:name=".helpactivity"
    android:label="@string/menu_help"
    android:screenorientation="user"
    android:statenotneeded="true"/>
 </application>

</manifest>

备注:此文仅仅是最简单的一个示例,演示了如何在自己的项目中在zxing官方项目已提供的完整代码基础上,做最小量的改动,将二维码扫描功能快速集成到自己的项目中为我所用,若需要更多的细节调整,则需要深入定制和改编源代码。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。