PhoneGap中文网

 找回密码
 立即注册
查看: 24399|回复: 5

phonegap 二维码扫描插件for android

[复制链接]

493

主题

2035

帖子

6894

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
6894
发表于 2013-11-16 11:39:09 | 显示全部楼层 |阅读模式

  在phonegap中通过二维码实现也是通过扩展phonegap的插件实现。

项目结构如下:

实现如下:

二维码扫码实现的插件类:


Java代码
  1. package com.easyway.barcode;



  2. import org.json.JSONArray;
  3. import org.json.JSONException;

  4. import android.app.Activity;
  5. import android.app.AlertDialog;
  6. import android.content.ActivityNotFoundException;
  7. import android.content.DialogInterface;
  8. import android.content.Intent;
  9. import android.net.Uri;

  10. import com.phonegap.api.PhonegapActivity;
  11. import com.phonegap.api.Plugin;
  12. import com.phonegap.api.PluginResult;

  13. /**
  14. * 扩展二维码扫描的phonegap类实现
  15. * 实现原理如下:
  16. *    1.使用phonegap的js类库实现通过插件调用相关的Plugin java类。
  17. *    2.plugin调用zxing相关的二维码扫码的方法实现。
  18. *    3.如果调用zxing没有安装,到google下载相关的zxing apk安装,并调用对应的intent实现。
  19. *
  20. * This calls out to the ZXing barcode reader and returns the result.
  21. */
  22. public class BarcodeScanner extends Plugin {
  23.         public static final int REQUEST_CODE = 0x0ba7c0de;


  24.         public static final String defaultInstallTitle = "Install Barcode Scanner?";
  25.         public static final String defaultInstallMessage = "This requires the free Barcode Scanner app. Would you like to install it now?";
  26.         public static final String defaultYesString = "Yes";
  27.         public static final String defaultNoString = "No";

  28.         public String callback;

  29.     /**
  30.      * Constructor.
  31.      */
  32.         public BarcodeScanner() {
  33.         }

  34.         /**
  35.          *
  36.          * 用于plugin相关的方法,用于暴露相关的方法使用。
  37.          *
  38.          * Executes the request and returns PluginResult.
  39.          *
  40.          * @param action                 The action to execute.
  41.          * @param args                         JSONArray of arguments for the plugin.
  42.          * @param callbackId        The callback id used when calling back into JavaScript.
  43.          * @return                                 A PluginResult object with a status and message.
  44.          */
  45.         public PluginResult execute(String action, JSONArray args, String callbackId) {
  46.                 this.callback = callbackId;

  47.                 try {
  48.                         if (action.equals("encode")) {
  49.                                 String type = null;
  50.                                 if(args.length() > 0) {
  51.                                         type = args.getString(0);
  52.                                 }

  53.                                 String data = null;
  54.                                 if(args.length() > 1) {
  55.                                         data = args.getString(1);
  56.                                 }

  57.                                 String installTitle = defaultInstallTitle;
  58.                                 if(args.length() > 2) {
  59.                                         installTitle = args.getString(2);
  60.                                 }

  61.                                 String installMessage = defaultInstallMessage;
  62.                                 if(args.length() > 3) {
  63.                                         installMessage = args.getString(3);
  64.                                 }

  65.                                 String yesString = defaultYesString;
  66.                                 if(args.length() > 4) {
  67.                                         yesString = args.getString(4);
  68.                                 }

  69.                                 String noString = defaultNoString;
  70.                                 if(args.length() > 5) {
  71.                                         noString = args.getString(5);
  72.                                 }

  73.                                 // if data.TypeOf() == Bundle, then call
  74.                                 // encode(type, Bundle)
  75.                                 // else
  76.                                 // encode(type, String)
  77.                                 this.encode(type, data, installTitle, installMessage, yesString, noString);
  78.                         }
  79.                         else if (action.equals("scan")) {
  80.                                 String barcodeTypes = null;
  81.                                 if(args.length() > 0) {
  82.                                         barcodeTypes = args.getString(0);
  83.                                 }

  84.                                 String installTitle = defaultInstallTitle;
  85.                                 if(args.length() > 1) {
  86.                                         installTitle = args.getString(1);
  87.                                 }

  88.                                 String installMessage = defaultInstallMessage;
  89.                                 if(args.length() > 2) {
  90.                                         installMessage = args.getString(2);
  91.                                 }

  92.                                 String yesString = defaultYesString;
  93.                                 if(args.length() > 3) {
  94.                                         yesString = args.getString(3);
  95.                                 }

  96.                                 String noString = defaultNoString;
  97.                                 if(args.length() > 4) {
  98.                                         noString = args.getString(4);
  99.                                 }

  100.                                 scan(barcodeTypes, installTitle, installMessage, yesString, noString);
  101.                         } else {
  102.                     return new PluginResult(PluginResult.Status.INVALID_ACTION);
  103.                         }
  104.                         PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
  105.                         r.setKeepCallback(true);
  106.                         return r;
  107.                 } catch (JSONException e) {
  108.                         e.printStackTrace();
  109.                         return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
  110.                 }
  111.         }


  112.         /**
  113.          * 扫描二维码的方法
  114.          *    备注:在扫描二维码的类型最好不好设置,在前期的zxing可能需要,在后期的版本中不需要,
  115.          *    zxing会自动检索二维码的类型,并识别相关二维码。
  116.          *   
  117.          * Initiates a barcode scan. If the ZXing scanner isn't installed, the user
  118.          * will be prompted to install it.
  119.          * @param types        The barcode types to accept
  120.          * @param installTitle The title for the dialog box that prompts the user to install the scanner
  121.          * @param installMessage The message prompting the user to install the barcode scanner
  122.          * @param yesString The string "Yes" or localised equivalent
  123.          * @param noString The string "No" or localised version
  124.          */
  125.         public void scan(String barcodeFormats, String installTitle, String installMessage, String yesString, String noString ) {
  126.             Intent intentScan = new Intent("com.google.zxing.client.android.SCAN");
  127.            // intentScan.addCategory(Intent.CATEGORY_DEFAULT);

  128.             //设置扫描特定类型的二维码
  129.             //if (barcodeFormats != null) {
  130.             //      Tell the scanner what types we're after
  131.             //                        intentScan.putExtra("SCAN_FORMATS", barcodeFormats);
  132.             // }
  133.             try {
  134.                         this.ctx.startActivityForResult((Plugin) this, intentScan, REQUEST_CODE);
  135.             } catch (ActivityNotFoundException e) {
  136.                     showDownloadDialog(installTitle, installMessage, yesString, noString);
  137.             }
  138.         }

  139.     /**
  140.      * 用于获取二维码扫描之后获取相关的二维码相关的信息
  141.      * Called when the barcode scanner exits
  142.      *
  143.      * @param requestCode                The request code originally supplied to startActivityForResult(),
  144.      *                                                         allowing you to identify who this result came from.
  145.      * @param resultCode                The integer result code returned by the child activity through its setResult().
  146.      * @param intent                        An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
  147.      */
  148.         public void onActivityResult(int requestCode, int resultCode, Intent intent) {
  149.                 if (requestCode == REQUEST_CODE) {
  150.                         if (resultCode == Activity.RESULT_OK) {
  151.                                 String contents = intent.getStringExtra("SCAN_RESULT");
  152.                                 String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
  153.                                 this.success(new PluginResult(PluginResult.Status.OK, " 条形码为:"+contents+" 条码类型为: "+format), this.callback);
  154.                         } else {
  155.                                 this.error(new PluginResult(PluginResult.Status.ERROR), this.callback);
  156.                         }
  157.                 }
  158.         }

  159.         /**
  160.          * 创建相关的对话框,在通过没有安装相关的zxing开源组件时候,调用远程的intent或者下载相关执行类实现相关的
  161.          * 功能
  162.          * @param title
  163.          * @param message
  164.          * @param yesString
  165.          * @param noString
  166.          */
  167.         private void showDownloadDialog(final String title, final String message, final String yesString, final String noString) {
  168.                 final PhonegapActivity context = this.ctx;
  169.                 Runnable runnable = new Runnable() {
  170.                         public void run() {

  171.                                 AlertDialog.Builder dialog = new AlertDialog.Builder(context);
  172.                                 dialog.setTitle(title);
  173.                                 dialog.setMessage(message);
  174.                                 dialog.setPositiveButton(yesString, new DialogInterface.OnClickListener() {
  175.                                         public void onClick(DialogInterface dlg, int i) {
  176.                                                 dlg.dismiss();
  177.                                                 Intent intent = new Intent(Intent.ACTION_VIEW,
  178.                                                                                                    Uri.parse("market://search?q=pname:com.google.zxing.client.android")
  179.                                                                                                    );
  180.                                                 try {
  181.                                                         context.startActivity(intent);
  182.                                                 } catch (ActivityNotFoundException e) {
  183.                                                         //        We don't have the market app installed, so download it directly.
  184.                                                         Intent in = new Intent(Intent.ACTION_VIEW);
  185.                                                         in.setData(Uri.parse("http://zxing.googlecode.com/files/BarcodeScanner4.1.apk"));
  186.                                                         context.startActivity(in);

  187.                                                 }

  188.                                         }
  189.                                 });
  190.                                 dialog.setNegativeButton(noString, new DialogInterface.OnClickListener() {
  191.                                         public void onClick(DialogInterface dlg, int i) {
  192.                                                 dlg.dismiss();
  193.                                         }
  194.                                 });
  195.                                 dialog.create();
  196.                                 dialog.show();
  197.                         }
  198.                 };
  199.                 context.runOnUiThread(runnable);
  200.         }

  201.         /**
  202.          *
  203.          *
  204.          * Initiates a barcode encode. If the ZXing scanner isn't installed, the user
  205.          * will be prompted to install it.
  206.          * @param type  The barcode type to encode
  207.          * @param data  The data to encode in the bar code
  208.          * @param installTitle The title for the dialog box that prompts the user to install the scanner
  209.          * @param installMessage The message prompting the user to install the barcode scanner
  210.          * @param yesString The string "Yes" or localised equivalent
  211.          * @param noString The string "No" or localised version
  212.          */
  213.         public void encode(String type, String data, String installTitle, String installMessage, String yesString, String noString) {
  214.                 Intent intentEncode = new Intent("com.google.zxing.client.android.ENCODE");
  215.                 intentEncode.putExtra("ENCODE_TYPE", type);
  216.                 intentEncode.putExtra("ENCODE_DATA", data);

  217.                 try {
  218.                         this.ctx.startActivity(intentEncode);
  219.                 } catch (ActivityNotFoundException e) {
  220.                         showDownloadDialog(installTitle, installMessage, yesString, noString);
  221.                 }
  222.         }
  223. }
复制代码



Java代码
  1. package com.easyway.barcode;

  2. import com.phonegap.*;
  3. import android.os.Bundle;
  4. /**
  5. * phonegap实现相关的二维码的扫码功能
  6. *
  7. * @Title:
  8. * @Description: 实现phonegap实现相关的二维码的扫码功能
  9. * @Copyright:Copyright (c) 2011
  10. * @Company:易程科技股份有限公司
  11. * @Date:2012-5-10
  12. * @author  longgangbai
  13. * @version 1.0
  14. */
  15. public class PhonegapBarcodeActivity extends DroidGap {
  16.     /** Called when the activity is first created. */
  17.     @Override
  18.     public void onCreate(Bundle savedInstanceState) {
  19.         super.onCreate(savedInstanceState);
  20.         super.loadUrl("file:///android_asset/www/index.html");
  21.     }
  22. }
复制代码



二维码扫码实现的js:

  1. /**
  2. * Phonegap Barcode Scanner plugin
  3. * Copyright (c) Matt Kane 2010
  4. *
  5. */
  6. var BarcodeScanner = function() {

  7. }

  8. BarcodeScanner.Type = {
  9.         QR_CODE: "QR_CODE",
  10.         DATA_MATRIX: "DATA_MATRIX",
  11.         UPC_E: "UPC_E",
  12.         UPC_A: "UPC_A",
  13.         EAN_8: "EAN_8",
  14.         EAN_13: "EAN_13",
  15.         CODE_128: "CODE_128",
  16.         CODE_39: "CODE_39",
  17.         CODE_93: "CODE_93",
  18.         CODABAR: "CODABAR",
  19.         ITF: "ITF",
  20.         RSS14: "RSS14",
  21.         PDF417: "PDF417",
  22.         RSS_EXPANDED: "RSS_EXPANDED",
  23.         PRODUCT_CODE_TYPES: "UPC_A,UPC_E,EAN_8,EAN_13",
  24.         ONE_D_CODE_TYPES: "UPC_A,UPC_E,EAN_8,EAN_13,CODE_39,CODE_93,CODE_128",
  25.         QR_CODE_TYPES: "QR_CODE",
  26.         ALL_CODE_TYPES: null
  27. }

  28. BarcodeScanner.Encode = {
  29.                 TEXT_TYPE: "TEXT_TYPE",
  30.                 EMAIL_TYPE: "EMAIL_TYPE",
  31.                 PHONE_TYPE: "PHONE_TYPE",
  32.                 SMS_TYPE: "SMS_TYPE",
  33.                 //  CONTACT_TYPE: "CONTACT_TYPE",  // TODO:  not implemented, requires passing a Bundle class from Javascriopt to Java
  34.                 //  LOCATION_TYPE: "LOCATION_TYPE" // TODO:  not implemented, requires passing a Bundle class from Javascriopt to Java
  35.         }
  36. //二维码扫描的方法
  37. BarcodeScanner.prototype.scan = function(types, success, fail, options) {
  38.         
  39.         /* These are the strings used in the dialog that appears if ZXing isn't installed */
  40.         var installTitle = "Install Barcode Scanner?";
  41.         var installMessage = "This requires the free Barcode Scanner app. Would you like to install it now?";
  42.         var yesString = "Yes";
  43.         var noString = "No";
  44.         if (typeof options != 'undefined') {
  45.                 if(typeof options.installTitle != 'undefined') {
  46.                         installTitle = options.installTitle;
  47.                 }

  48.                 if(typeof options.installMessage != 'undefined') {
  49.                         installMessage = options.installMessage;
  50.                 }

  51.                 if(typeof options.yesString != 'undefined') {
  52.                         yesString = options.yesString;
  53.                 }

  54.                 if(typeof options.noString != 'undefined') {
  55.                         noString = options.noString;
  56.                 }
  57.         }
  58.         
  59.         
  60.     return PhoneGap.exec(function(args) {
  61.         success(args);
  62.     }, function(args) {
  63.         fail(args);
  64.     }, 'BarcodeScanner', 'scan', [types, installTitle, installMessage, yesString, noString]);
  65. };
  66. BarcodeScanner.prototype.encode = function(type, data, success, fail, options) {

  67.         /* These are the strings used in the dialog that appears if ZXing isn't installed */
  68.         var installTitle = "Install Barcode Scanner?";
  69.         var installMessage = "This requires the free Barcode Scanner app. Would you like to install it now?";
  70.         var yesString = "Yes";
  71.         var noString = "No";
  72.         if (typeof options != 'undefined') {
  73.                 if(typeof options.installTitle != 'undefined') {
  74.                         installTitle = options.installTitle;
  75.                 }

  76.                 if(typeof options.installMessage != 'undefined') {
  77.                         installMessage = options.installMessage;
  78.                 }

  79.                 if(typeof options.yesString != 'undefined') {
  80.                         yesString = options.yesString;
  81.                 }

  82.                 if(typeof options.noString != 'undefined') {
  83.                         noString = options.noString;
  84.                 }
  85.         }

  86.     return PhoneGap.exec(function(args) {
  87.         success(args);
  88.     }, function(args) {
  89.         fail(args);
  90.     }, 'BarcodeScanner', 'encode', [type, data, installTitle, installMessage, yesString, noString]);
  91. };

  92. PhoneGap.addConstructor(function() {
  93.   //如果不支持window.plugins,则创建并设置   
  94.     if(!window.plugins){   
  95.         window.plugins={};   
  96.     }   
  97.     window.plugins.barcodeScanner=new BarcodeScanner();
  98.         //PhoneGap.addPlugin('barcodeScanner', new BarcodeScanner());
  99.         PluginManager.addService("BarcodeScanner","com.easyway.barcode.BarcodeScanner");
  100. });
复制代码



二维码调用的页面如下:

Html代码
  1. <!DOCTYPE HTML>
  2. <html>
  3.   <head>
  4.     <meta name="viewport" content="width=320; user-scalable=no" />
  5.     <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  6.     <title>二维码扫描</title>

  7.      <!-- 加载phonegap -->  
  8.     <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>  
  9.     <!-- 加载jquery -->  
  10.     <script type="text/javascript" charset="utf-8" src="jquery.mobile/jquery-1.6.4.min"></script>  
  11.     <!-- 加载jquerymobile -->  
  12.     <script type="text/javascript" charset="utf-8" src="jquery.mobile/jquery.mobile-1.0.1.js"></script>  
  13.     <!-- 加载自定义插件 -->  
  14.     <script type="text/javascript" charset="utf-8" src="barcodescanner.js"></script>
  15.     <script type="text/javascript" charset="utf-8">  
  16.          
  17.      $(function(){   
  18.         $("#btnbarcode").click(function(){   
  19.                     window.plugins.barcodeScanner.scan(
  20.                             BarcodeScanner.Type.QR_CODE,
  21.                             function(result) {
  22.                                 $("#barcodediv").html(""+result);
  23.                             },
  24.                             function(error) {
  25.                                 $("#barcodediv").html("扫描失败:"+result);
  26.                                     },
  27.                                     {
  28.                                         installTitle: "安装提示",
  29.                                         installMessage:"是否安装开源免费的ZXing二维码扫描器",
  30.                                         yesString:"确定",
  31.                                         noString:"取消"
  32.                                     }
  33.                 );

  34.         });   
  35.      });   
  36. </script>     
  37.   

  38.   </head>
  39.   <body >
  40.     <h2>二维码扫描</h2>

  41.         <p>二维码信息:</p>
  42.         <div id="barcodediv"></div>
  43.         <input type="button" id="btnbarcode" value="扫描" />
  44.   </body>
  45. </html>
复制代码



备注附件中phonegap的apk,下载之后需要重新命名为PhonegapBarcode.apk即可使用。


PhonegapBarcode.apk.zip (271.77 KB, 下载次数: 254)
回复

使用道具 举报

1

主题

91

帖子

89

积分

注册会员

Rank: 2

积分
89
发表于 2013-11-16 11:39:53 | 显示全部楼层
找到好贴不容易,我顶你了,谢了
回复 支持 反对

使用道具 举报

3

主题

29

帖子

167

积分

注册会员

Rank: 2

积分
167
发表于 2014-5-31 05:50:44 | 显示全部楼层
问题这个是要 运行其他程序才可以
回复 支持 反对

使用道具 举报

0

主题

7

帖子

36

积分

新手上路

Rank: 1

积分
36
发表于 2014-8-12 10:17:11 | 显示全部楼层
项目运行不了
回复 支持 反对

使用道具 举报

0

主题

7

帖子

36

积分

新手上路

Rank: 1

积分
36
发表于 2014-8-12 10:50:10 | 显示全部楼层
apk文件可以扫描,也能将扫描后的结果返回,唯一不好的地方就是需要安装第三方软件【条码扫描器】
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐 上一条 /1 下一条

ionic4视频教程

Archiver|手机版|小黑屋| PhoneGap中文网 ( 京ICP备13027796号-1 )  

GMT+8, 2024-3-29 14:55 , Processed in 0.097368 second(s), 34 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表