[
  {
    "path": ".classpath",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<classpath>\n\t<classpathentry kind=\"con\" path=\"com.android.ide.eclipse.adt.ANDROID_FRAMEWORK\"/>\n\t<classpathentry exported=\"true\" kind=\"con\" path=\"com.android.ide.eclipse.adt.LIBRARIES\"/>\n\t<classpathentry exported=\"true\" kind=\"con\" path=\"com.android.ide.eclipse.adt.DEPENDENCIES\"/>\n\t<classpathentry kind=\"src\" path=\"src\"/>\n\t<classpathentry kind=\"src\" path=\"gen\"/>\n\t<classpathentry kind=\"output\" path=\"bin/classes\"/>\n</classpath>\n"
  },
  {
    "path": ".gitignore",
    "content": "# Built application files\n*.apk\n*.ap_\n\n# Files for the Dalvik VM\n*.dex\n\n# Java class files\n*.class\n\n# Generated files\nbin/\ngen/\n\n# Gradle files\n.gradle/\nbuild/\n\n# Local configuration file (sdk path, etc)\nlocal.properties\n\n# Proguard folder generated by Eclipse\nproguard/\n"
  },
  {
    "path": ".project",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<projectDescription>\n\t<name>BarcodeScanner</name>\n\t<comment></comment>\n\t<projects>\n\t</projects>\n\t<buildSpec>\n\t\t<buildCommand>\n\t\t\t<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>\n\t\t\t<arguments>\n\t\t\t</arguments>\n\t\t</buildCommand>\n\t\t<buildCommand>\n\t\t\t<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>\n\t\t\t<arguments>\n\t\t\t</arguments>\n\t\t</buildCommand>\n\t\t<buildCommand>\n\t\t\t<name>org.eclipse.jdt.core.javabuilder</name>\n\t\t\t<arguments>\n\t\t\t</arguments>\n\t\t</buildCommand>\n\t\t<buildCommand>\n\t\t\t<name>com.android.ide.eclipse.adt.ApkBuilder</name>\n\t\t\t<arguments>\n\t\t\t</arguments>\n\t\t</buildCommand>\n\t</buildSpec>\n\t<natures>\n\t\t<nature>com.android.ide.eclipse.adt.AndroidNature</nature>\n\t\t<nature>org.eclipse.jdt.core.javanature</nature>\n\t</natures>\n</projectDescription>\n"
  },
  {
    "path": "AndroidManifest.xml",
    "content": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"cn.hugo.android.scanner\"\n    android:versionCode=\"1\"\n    android:versionName=\"1.0\" >\n\n    <uses-permission android:name=\"android.permission.CAMERA\" >\n    </uses-permission>\n    <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" >\n    </uses-permission>\n\n    <uses-feature android:name=\"android.hardware.camera\" />\n    <uses-feature android:name=\"android.hardware.camera.autofocus\" />\n\n    <uses-permission android:name=\"android.permission.VIBRATE\" />\n    <uses-permission android:name=\"android.permission.FLASHLIGHT\" />\n\n    <uses-sdk\n        android:minSdkVersion=\"8\"\n        android:targetSdkVersion=\"19\" />\n\n    <application\n        android:allowBackup=\"true\"\n        android:icon=\"@drawable/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:theme=\"@style/AppTheme\" >\n        <activity\n            android:name=\"cn.hugo.android.scanner.CaptureActivity\"\n            android:configChanges=\"orientation|keyboardHidden\"\n            android:screenOrientation=\"portrait\"\n            android:theme=\"@android:style/Theme.NoTitleBar.Fullscreen\"\n            android:windowSoftInputMode=\"stateAlwaysHidden\" >\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n    </application>\n\n</manifest>"
  },
  {
    "path": "LICENSE",
    "content": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "BarcodeScanner\n==============\n\nAndroid手机客户端关于二维码扫描的源码，使用了zxing 3.1.1代码并对其进行了精简，支持低版本的sdk，实现了二维码和一维码的扫描、从图片解析一维码和二维码，闪光灯、调焦。。。\n\n![](https://github.com/ThinWonton/BarcodeScanner/blob/master/img/234326egsid70udzdylgdi.png)\n\n![](https://github.com/ThinWonton/BarcodeScanner/blob/master/img/234723aa5c5cdqzqpqoioc.jpg)\n![](https://github.com/ThinWonton/BarcodeScanner/blob/master/img/234730m496gqi7464cbcgg.jpg)\n![](https://github.com/ThinWonton/BarcodeScanner/blob/master/img/234735ezr1qbj0rzk0bx66.jpg)\n"
  },
  {
    "path": "doc/readme.txt",
    "content": "参考文档\nhttp://my.oschina.net/madmatrix/blog/189031"
  },
  {
    "path": "lint.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<lint>\n</lint>"
  },
  {
    "path": "proguard-project.txt",
    "content": "# To enable ProGuard in your project, edit project.properties\n# to define the proguard.config property as described in that file.\n#\n# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in ${sdk.dir}/tools/proguard/proguard-android.txt\n# You can edit the include path and order by changing the ProGuard\n# include property in project.properties.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# Add any project specific keep options here:\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n"
  },
  {
    "path": "project.properties",
    "content": "# This file is automatically generated by Android Tools.\n# Do not modify this file -- YOUR CHANGES WILL BE ERASED!\n#\n# This file must be checked in Version Control Systems.\n#\n# To customize properties used by the Ant build system edit\n# \"ant.properties\", and override values to adapt the script to your\n# project structure.\n#\n# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):\n#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt\n\n# Project target.\ntarget=android-19\n"
  },
  {
    "path": "res/drawable/scan_flashlight.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <item android:drawable=\"@drawable/scan_flashlight_pressed\" android:state_pressed=\"true\"></item>\n    <item android:drawable=\"@drawable/scan_flashlight_normal\"></item>\n\n</selector>"
  },
  {
    "path": "res/drawable/scan_history.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <item android:drawable=\"@drawable/scan_history_pressed\" android:state_pressed=\"true\"/>\n    <item android:drawable=\"@drawable/scan_history_normal\"/>\n\n</selector>"
  },
  {
    "path": "res/drawable/scan_photo.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <item android:drawable=\"@drawable/scan_photo_pressed\" android:state_pressed=\"true\"/>\n    <item android:drawable=\"@drawable/scan_photo_normal\"/>\n\n</selector>"
  },
  {
    "path": "res/drawable/seekbar_bg.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n\n    <item android:id=\"@android:id/background\">\n        <shape>\n            <corners android:radius=\"10.0dip\" />\n\n            <gradient\n                android:angle=\"360.0\"\n                android:centerColor=\"#89898989\"\n                android:centerY=\"0.45\"\n                android:endColor=\"#89898989\"\n                android:startColor=\"#89898989\" />\n        </shape>\n    </item>\n\n</layer-list>"
  },
  {
    "path": "res/drawable/seekbar_style.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n\n    <item android:id=\"@android:id/background\">\n        <shape>\n            <corners android:radius=\"10.0dip\" />\n\n            <gradient\n                android:angle=\"270.0\"\n                android:centerColor=\"#ff606060\"\n                android:centerY=\"0.45\"\n                android:endColor=\"#ff808080\"\n                android:startColor=\"#ff808080\" />\n        </shape>\n    </item>\n    <item android:id=\"@android:id/progress\">\n        <clip>\n            <shape>\n                <corners android:radius=\"10.0dip\" />\n\n                <gradient\n                    android:angle=\"270.0\"\n                    android:centerColor=\"#ffe6e6e6\"\n                    android:centerY=\"0.45\"\n                    android:endColor=\"#fff6f6f6\"\n                    android:startColor=\"#fff6f6f6\" />\n            </shape>\n        </clip>\n    </item>\n\n</layer-list>"
  },
  {
    "path": "res/layout/capture.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/capture_frame\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\" >\n\n    <SurfaceView\n        android:id=\"@+id/capture_preview_view\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:layout_gravity=\"center\" />\n\n    <cn.hugo.android.scanner.view.ViewfinderView\n        android:id=\"@+id/capture_viewfinder_view\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:layout_gravity=\"center\"\n        android:background=\"@android:color/transparent\" />\n\n    <LinearLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"85.0dip\"\n        android:background=\"@color/capture_text_cover_bg\"\n        android:orientation=\"horizontal\"\n        android:weightSum=\"5.0\" >\n\n        <LinearLayout\n            android:layout_width=\"0.0dip\"\n            android:layout_height=\"fill_parent\"\n            android:layout_weight=\"1.0\"\n            android:gravity=\"center\"\n            android:orientation=\"horizontal\" >\n\n            <ImageView\n                android:id=\"@+id/capture_flashlight\"\n                android:layout_width=\"30.0dip\"\n                android:layout_height=\"30.0dip\"\n                android:layout_gravity=\"center_vertical\"\n                android:clickable=\"true\"\n                android:scaleType=\"fitCenter\"\n                android:src=\"@drawable/scan_flashlight\" />\n        </LinearLayout>\n\n        <TextView\n            android:id=\"@+id/capture_top_hint\"\n            android:layout_width=\"0.0dip\"\n            android:layout_height=\"85.0dip\"\n            android:layout_gravity=\"top|center\"\n            android:layout_weight=\"3.0\"\n            android:gravity=\"center\"\n            android:paddingLeft=\"20.0dip\"\n            android:text=\"@string/top_hint\"\n            android:textColor=\"#ffffffff\"\n            android:textSize=\"13.0sp\" />\n\n        <LinearLayout\n            android:layout_width=\"0.0dip\"\n            android:layout_height=\"fill_parent\"\n            android:layout_weight=\"1.0\"\n            android:gravity=\"center\"\n            android:orientation=\"horizontal\" >\n\n            <ImageView\n                android:id=\"@+id/capture_scan_photo\"\n                android:layout_width=\"30.0dip\"\n                android:layout_height=\"30.0dip\"\n                android:layout_gravity=\"center_vertical\"\n                android:clickable=\"true\"\n                android:scaleType=\"fitCenter\"\n                android:src=\"@drawable/scan_photo\" />\n        </LinearLayout>\n    </LinearLayout>\n\n    <LinearLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"95.0dip\"\n        android:layout_gravity=\"bottom|center\"\n        android:background=\"@color/capture_text_cover_bg\"\n        android:orientation=\"horizontal\" >\n\n        <Button\n            android:id=\"@+id/capture_button_cancel\"\n            android:layout_width=\"70.0dip\"\n            android:layout_height=\"40.0dip\"\n            android:layout_gravity=\"center_vertical\"\n            android:layout_marginLeft=\"20.0dip\"\n            android:text=\"@string/cancel\"\n            android:textSize=\"14.0sp\" />\n\n        <Button\n            android:id=\"@+id/capture_button_createcode\"\n            android:layout_width=\"70.0dip\"\n            android:layout_height=\"40.0dip\"\n            android:layout_gravity=\"center_vertical\"\n            android:layout_marginLeft=\"20.0dip\"\n            android:text=\"@string/create\"\n            android:textSize=\"14.0sp\"\n            android:visibility=\"gone\" />\n\n        <TextView\n            android:id=\"@+id/capture_bottom_hint\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"fill_parent\"\n            android:gravity=\"center_vertical\"\n            android:paddingLeft=\"20.0dip\"\n            android:paddingRight=\"20.0dip\"\n            android:text=\"@string/bottom_hint\"\n            android:textColor=\"#ffffffff\"\n            android:textSize=\"13.0sp\" />\n    </LinearLayout>\n\n</FrameLayout>"
  },
  {
    "path": "res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<resources>\n\n    <color name=\"contents_text\">#ff000000</color>\n    <color name=\"encode_view\">#ffffffff</color>\n    <color name=\"possible_result_points\">#c0ffbd21</color> <!-- Android standard ICS color -->\n    <color name=\"result_minor_text\">#ffc0c0c0</color>\n    <color name=\"result_points\">#c099cc00</color> <!-- Android standard ICS color -->\n    <color name=\"result_text\">#ffffffff</color>\n    <color name=\"result_view\">#b0000000</color>\n    <color name=\"status_text\">#ffffffff</color>\n    <color name=\"transparent\">#00000000</color>\n    <color name=\"viewfinder_laser\">#ffcc0000</color> <!-- Android standard ICS color -->\n    <color name=\"viewfinder_mask\">#00000000</color>\n    <color name=\"capture_text_cover_bg\">#99535353</color>\n    <color name=\"seek_bar_text\">#fff6f6f6</color>\n\n</resources>"
  },
  {
    "path": "res/values/ids.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n Copyright (C) 2008 ZXing authors\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n      http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n -->\n<resources>\n  <!-- Messages IDs -->\n  <item type=\"id\" name=\"auto_focus\"/>\n  <item type=\"id\" name=\"decode\"/>\n  <item type=\"id\" name=\"decode_failed\"/>\n  <item type=\"id\" name=\"decode_succeeded\"/>\n  <item type=\"id\" name=\"launch_product_query\"/>\n  <item type=\"id\" name=\"quit\"/>\n  <item type=\"id\" name=\"restart_preview\"/>\n  <item type=\"id\" name=\"return_scan_result\"/>\n  <item type=\"id\" name=\"search_book_contents_failed\"/>\n  <item type=\"id\" name=\"search_book_contents_succeeded\"/>\n</resources>\n"
  },
  {
    "path": "res/values/strings.xml",
    "content": "<resources>\n\n    <string name=\"app_name\">二维条形码扫描</string>\n    <string name=\"placeHolder\">placeHolder</string>\n    <string name=\"seekbar_add\">+</string>\n    <string name=\"seekbar_minus\">-</string>\n    <string name=\"create\">生成</string>\n    <string name=\"scan_failed\">扫描失败</string>\n    <string name=\"bottom_hint\">建议与镜头保持10CM距离，尽量避免逆光和阴影</string>\n    <string name=\"top_hint\">将条形码或二维码置于取景框内系统会自动扫描</string>\n    <string name=\"cancel\">取消</string>\n    <string name=\"msg_camera_framework_bug\">抱歉，Android相机出现问题。您可能需要重启设备。</string>\n    <string name=\"button_ok\">确定</string>\n\n</resources>"
  },
  {
    "path": "res/values/styles.xml",
    "content": "<resources>\n\n    <!--\n        Base application theme, dependent on API level. This theme is replaced\n        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\n    -->\n    <style name=\"AppBaseTheme\" parent=\"android:Theme.Light\">\n        <!--\n            Theme customizations available in newer API levels can go in\n            res/values-vXX/styles.xml, while customizations related to\n            backward-compatibility can go here.\n        -->\n    </style>\n\n    <!-- Application theme. -->\n    <style name=\"AppTheme\" parent=\"AppBaseTheme\">\n        <!-- All customizations that are NOT specific to a particular API-level can go here. -->\n    </style>\n\n</resources>\n"
  },
  {
    "path": "res/values-v11/styles.xml",
    "content": "<resources>\n\n    <!--\n        Base application theme for API 11+. This theme completely replaces\n        AppBaseTheme from res/values/styles.xml on API 11+ devices.\n    -->\n    <style name=\"AppBaseTheme\" parent=\"android:Theme.Holo.Light\">\n        <!-- API 11 theme customizations can go here. -->\n    </style>\n\n</resources>\n"
  },
  {
    "path": "res/values-v14/styles.xml",
    "content": "<resources>\n\n    <!--\n        Base application theme for API 14+. This theme completely replaces\n        AppBaseTheme from BOTH res/values/styles.xml and\n        res/values-v11/styles.xml on API 14+ devices.\n    -->\n    <style name=\"AppBaseTheme\" parent=\"android:Theme.Holo.Light.DarkActionBar\">\n        <!-- API 14 theme customizations can go here. -->\n    </style>\n\n</resources>\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/AmbientLightManager.java",
    "content": "/*\n * Copyright (C) 2012 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner;\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.hardware.Sensor;\nimport android.hardware.SensorEvent;\nimport android.hardware.SensorEventListener;\nimport android.hardware.SensorManager;\nimport android.preference.PreferenceManager;\nimport cn.hugo.android.scanner.camera.CameraManager;\nimport cn.hugo.android.scanner.camera.FrontLightMode;\n\n/**\n * Detects ambient light and switches on the front light when very dark, and off\n * again when sufficiently light.\n * \n * @author Sean Owen\n * @author Nikolaus Huber\n */\nfinal class AmbientLightManager implements SensorEventListener {\n\n\tprivate static final float TOO_DARK_LUX = 45.0f;\n\tprivate static final float BRIGHT_ENOUGH_LUX = 450.0f;\n\n\tprivate final Context context;\n\tprivate CameraManager cameraManager;\n\n\t/**\n\t * 光传感器\n\t */\n\tprivate Sensor lightSensor;\n\n\tAmbientLightManager(Context context) {\n\t\tthis.context = context;\n\t}\n\n\tvoid start(CameraManager cameraManager) {\n\t\tthis.cameraManager = cameraManager;\n\t\tSharedPreferences sharedPrefs = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(context);\n\t\tif (FrontLightMode.readPref(sharedPrefs) == FrontLightMode.AUTO) {\n\t\t\tSensorManager sensorManager = (SensorManager) context\n\t\t\t\t\t.getSystemService(Context.SENSOR_SERVICE);\n\t\t\tlightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);\n\t\t\tif (lightSensor != null) {\n\t\t\t\tsensorManager.registerListener(this, lightSensor,\n\t\t\t\t\t\tSensorManager.SENSOR_DELAY_NORMAL);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid stop() {\n\t\tif (lightSensor != null) {\n\t\t\tSensorManager sensorManager = (SensorManager) context\n\t\t\t\t\t.getSystemService(Context.SENSOR_SERVICE);\n\t\t\tsensorManager.unregisterListener(this);\n\t\t\tcameraManager = null;\n\t\t\tlightSensor = null;\n\t\t}\n\t}\n\n\t/**\n\t * 该方法会在周围环境改变后回调，然后根据设置好的临界值决定是否打开闪光灯\n\t */\n\t@Override\n\tpublic void onSensorChanged(SensorEvent sensorEvent) {\n\t\tfloat ambientLightLux = sensorEvent.values[0];\n\t\tif (cameraManager != null) {\n\t\t\tif (ambientLightLux <= TOO_DARK_LUX) {\n\t\t\t\tcameraManager.setTorch(true);\n\t\t\t}\n\t\t\telse if (ambientLightLux >= BRIGHT_ENOUGH_LUX) {\n\t\t\t\tcameraManager.setTorch(false);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onAccuracyChanged(Sensor sensor, int accuracy) {\n\t\t// do nothing\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/BeepManager.java",
    "content": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner;\n\nimport java.io.IOException;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.content.res.AssetFileDescriptor;\nimport android.media.AudioManager;\nimport android.media.MediaPlayer;\nimport android.os.Vibrator;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport cn.hugo.android.scanner.config.Config;\n\n/**\n * Manages beeps and vibrations for {@link CaptureActivity}.\n */\nfinal class BeepManager implements MediaPlayer.OnCompletionListener,\n\t\tMediaPlayer.OnErrorListener {\n\n\tprivate static final String TAG = BeepManager.class.getSimpleName();\n\n\tprivate static final float BEEP_VOLUME = 0.10f;\n\n\tprivate static final long VIBRATE_DURATION = 200L;\n\n\tprivate final Activity activity;\n\n\tprivate MediaPlayer mediaPlayer;\n\n\tprivate boolean playBeep;\n\n\tprivate boolean vibrate;\n\n\tBeepManager(Activity activity) {\n\t\tthis.activity = activity;\n\t\tthis.mediaPlayer = null;\n\t\tupdatePrefs();\n\t}\n\n\t/**\n\t * 扫描成功后可以播放提示音并震动，这两种功能都是用户自定义的 在Barcode Scanner中点击菜单键，点设置即可看到这两项的设置\n\t */\n\tsynchronized void updatePrefs() {\n\t\tSharedPreferences prefs = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(activity);\n\t\tplayBeep = shouldBeep(prefs, activity);\n\t\tvibrate = prefs.getBoolean(Config.KEY_VIBRATE, false);\n\t\tif (playBeep && mediaPlayer == null) {\n\t\t\t// The volume on STREAM_SYSTEM is not adjustable, and users found it\n\t\t\t// too loud,\n\t\t\t// so we now play on the music stream.\n\t\t\tactivity.setVolumeControlStream(AudioManager.STREAM_MUSIC);\n\t\t\tmediaPlayer = buildMediaPlayer(activity);\n\t\t}\n\t}\n\n\t/**\n\t * 根据配置播放提示音和震动\n\t */\n\tsynchronized void playBeepSoundAndVibrate() {\n\t\tif (playBeep && mediaPlayer != null) {\n\t\t\tmediaPlayer.start();\n\t\t}\n\t\tif (vibrate) {\n\t\t\tVibrator vibrator = (Vibrator) activity\n\t\t\t\t\t.getSystemService(Context.VIBRATOR_SERVICE);\n\t\t\tvibrator.vibrate(VIBRATE_DURATION);\n\t\t}\n\t}\n\n\tprivate static boolean shouldBeep(SharedPreferences prefs, Context activity) {\n\t\tboolean shouldPlayBeep = prefs.getBoolean(Config.KEY_PLAY_BEEP, true);\n\t\tif (shouldPlayBeep) {\n\t\t\t// See if sound settings overrides this\n\t\t\tAudioManager audioService = (AudioManager) activity\n\t\t\t\t\t.getSystemService(Context.AUDIO_SERVICE);\n\t\t\tif (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {\n\t\t\t\tshouldPlayBeep = false;\n\t\t\t}\n\t\t}\n\t\treturn shouldPlayBeep;\n\t}\n\n\tprivate MediaPlayer buildMediaPlayer(Context activity) {\n\t\tMediaPlayer mediaPlayer = new MediaPlayer();\n\t\tmediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);\n\t\tmediaPlayer.setOnCompletionListener(this);\n\t\tmediaPlayer.setOnErrorListener(this);\n\n\t\tAssetFileDescriptor file = activity.getResources().openRawResourceFd(\n\t\t\t\tR.raw.beep);\n\t\ttry {\n\t\t\tmediaPlayer.setDataSource(file.getFileDescriptor(),\n\t\t\t\t\tfile.getStartOffset(), file.getLength());\n\t\t\tfile.close();\n\t\t\tmediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);\n\t\t\tmediaPlayer.prepare();\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\tLog.w(TAG, ioe);\n\t\t\tmediaPlayer = null;\n\t\t}\n\t\treturn mediaPlayer;\n\t}\n\n\t@Override\n\tpublic void onCompletion(MediaPlayer mp) {\n\t\t// When the beep has finished playing, rewind to queue up another one.\n\t\tmp.seekTo(0);\n\t}\n\n\t@Override\n\tpublic synchronized boolean onError(MediaPlayer mp, int what, int extra) {\n\t\tif (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {\n\t\t\t// we are finished, so put up an appropriate error toast if required\n\t\t\t// and finish\n\t\t\tactivity.finish();\n\t\t}\n\t\telse {\n\t\t\t// possibly media player error, so release and recreate\n\t\t\tmp.release();\n\t\t\tmediaPlayer = null;\n\t\t\tupdatePrefs();\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * 新增\n\t * 关闭beep声音\n\t */\n\tpublic synchronized void close() {\n\t\tif (mediaPlayer != null) {\n\t\t\tmediaPlayer.release();\n\t\t\tmediaPlayer = null;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/CaptureActivity.java",
    "content": "package cn.hugo.android.scanner;\n\nimport java.io.IOException;\nimport java.lang.ref.WeakReference;\nimport java.util.Collection;\nimport java.util.Map;\n\nimport android.app.Activity;\nimport android.app.AlertDialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.graphics.Bitmap;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.provider.MediaStore;\nimport android.util.Log;\nimport android.view.KeyEvent;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.View;\nimport android.view.Window;\nimport android.view.WindowManager;\nimport android.widget.Toast;\nimport cn.hugo.android.scanner.camera.CameraManager;\nimport cn.hugo.android.scanner.common.BitmapUtils;\nimport cn.hugo.android.scanner.decode.BitmapDecoder;\nimport cn.hugo.android.scanner.decode.CaptureActivityHandler;\nimport cn.hugo.android.scanner.view.ViewfinderView;\n\nimport com.google.zxing.BarcodeFormat;\nimport com.google.zxing.DecodeHintType;\nimport com.google.zxing.Result;\nimport com.google.zxing.client.result.ResultParser;\n\n/**\n * This activity opens the camera and does the actual scanning on a background\n * thread. It draws a viewfinder to help the user place the barcode correctly,\n * shows feedback as the image processing is happening, and then overlays the\n * results when a scan is successful.\n * \n * 此Activity所做的事： 1.开启camera，在后台独立线程中完成扫描任务；\n * 2.绘制了一个扫描区（viewfinder）来帮助用户将条码置于其中以准确扫描； 3.扫描成功后会将扫描结果展示在界面上。\n * \n * @author dswitkin@google.com (Daniel Switkin)\n * @author Sean Owen\n */\npublic final class CaptureActivity extends Activity implements\n\t\tSurfaceHolder.Callback, View.OnClickListener {\n\n\tprivate static final String TAG = CaptureActivity.class.getSimpleName();\n\n\tprivate static final int REQUEST_CODE = 100;\n\n\tprivate static final int PARSE_BARCODE_FAIL = 300;\n\tprivate static final int PARSE_BARCODE_SUC = 200;\n\n\t/**\n\t * 是否有预览\n\t */\n\tprivate boolean hasSurface;\n\n\t/**\n\t * 活动监控器。如果手机没有连接电源线，那么当相机开启后如果一直处于不被使用状态则该服务会将当前activity关闭。\n\t * 活动监控器全程监控扫描活跃状态，与CaptureActivity生命周期相同.每一次扫描过后都会重置该监控，即重新倒计时。\n\t */\n\tprivate InactivityTimer inactivityTimer;\n\n\t/**\n\t * 声音震动管理器。如果扫描成功后可以播放一段音频，也可以震动提醒，可以通过配置来决定扫描成功后的行为。\n\t */\n\tprivate BeepManager beepManager;\n\n\t/**\n\t * 闪光灯调节器。自动检测环境光线强弱并决定是否开启闪光灯\n\t */\n\tprivate AmbientLightManager ambientLightManager;\n\n\tprivate CameraManager cameraManager;\n\t/**\n\t * 扫描区域\n\t */\n\tprivate ViewfinderView viewfinderView;\n\n\tprivate CaptureActivityHandler handler;\n\n\tprivate Result lastResult;\n\n\tprivate boolean isFlashlightOpen;\n\n\t/**\n\t * 【辅助解码的参数(用作MultiFormatReader的参数)】 编码类型，该参数告诉扫描器采用何种编码方式解码，即EAN-13，QR\n\t * Code等等 对应于DecodeHintType.POSSIBLE_FORMATS类型\n\t * 参考DecodeThread构造函数中如下代码：hints.put(DecodeHintType.POSSIBLE_FORMATS,\n\t * decodeFormats);\n\t */\n\tprivate Collection<BarcodeFormat> decodeFormats;\n\n\t/**\n\t * 【辅助解码的参数(用作MultiFormatReader的参数)】 该参数最终会传入MultiFormatReader，\n\t * 上面的decodeFormats和characterSet最终会先加入到decodeHints中 最终被设置到MultiFormatReader中\n\t * 参考DecodeHandler构造器中如下代码：multiFormatReader.setHints(hints);\n\t */\n\tprivate Map<DecodeHintType, ?> decodeHints;\n\n\t/**\n\t * 【辅助解码的参数(用作MultiFormatReader的参数)】 字符集，告诉扫描器该以何种字符集进行解码\n\t * 对应于DecodeHintType.CHARACTER_SET类型\n\t * 参考DecodeThread构造器如下代码：hints.put(DecodeHintType.CHARACTER_SET,\n\t * characterSet);\n\t */\n\tprivate String characterSet;\n\n\tprivate Result savedResultToShow;\n\n\tprivate IntentSource source;\n\n\t/**\n\t * 图片的路径\n\t */\n\tprivate String photoPath;\n\n\tprivate Handler mHandler = new MyHandler(this);\n\n\tstatic class MyHandler extends Handler {\n\n\t\tprivate WeakReference<Activity> activityReference;\n\n\t\tpublic MyHandler(Activity activity) {\n\t\t\tactivityReference = new WeakReference<Activity>(activity);\n\t\t}\n\n\t\t@Override\n\t\tpublic void handleMessage(Message msg) {\n\n\t\t\tswitch (msg.what) {\n\t\t\t\tcase PARSE_BARCODE_SUC: // 解析图片成功\n\t\t\t\t\tToast.makeText(activityReference.get(),\n\t\t\t\t\t\t\t\"解析成功，结果为：\" + msg.obj, Toast.LENGTH_SHORT).show();\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PARSE_BARCODE_FAIL:// 解析图片失败\n\n\t\t\t\t\tToast.makeText(activityReference.get(), \"解析图片失败\",\n\t\t\t\t\t\t\tToast.LENGTH_SHORT).show();\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tsuper.handleMessage(msg);\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\n\t\tWindow window = getWindow();\n\t\twindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n\t\tsetContentView(R.layout.capture);\n\n\t\thasSurface = false;\n\t\tinactivityTimer = new InactivityTimer(this);\n\t\tbeepManager = new BeepManager(this);\n\t\tambientLightManager = new AmbientLightManager(this);\n\n\t\t// 监听图片识别按钮\n\t\tfindViewById(R.id.capture_scan_photo).setOnClickListener(this);\n\n\t\tfindViewById(R.id.capture_flashlight).setOnClickListener(this);\n\n\t}\n\n\t@Override\n\tprotected void onResume() {\n\t\tsuper.onResume();\n\n\t\t// CameraManager must be initialized here, not in onCreate(). This is\n\t\t// necessary because we don't\n\t\t// want to open the camera driver and measure the screen size if we're\n\t\t// going to show the help on\n\t\t// first launch. That led to bugs where the scanning rectangle was the\n\t\t// wrong size and partially\n\t\t// off screen.\n\n\t\t// 相机初始化的动作需要开启相机并测量屏幕大小，这些操作\n\t\t// 不建议放到onCreate中，因为如果在onCreate中加上首次启动展示帮助信息的代码的 话，\n\t\t// 会导致扫描窗口的尺寸计算有误的bug\n\t\tcameraManager = new CameraManager(getApplication());\n\n\t\tviewfinderView = (ViewfinderView) findViewById(R.id.capture_viewfinder_view);\n\t\tviewfinderView.setCameraManager(cameraManager);\n\n\t\thandler = null;\n\t\tlastResult = null;\n\n\t\t// 摄像头预览功能必须借助SurfaceView，因此也需要在一开始对其进行初始化\n\t\t// 如果需要了解SurfaceView的原理\n\t\t// 参考:http://blog.csdn.net/luoshengyang/article/details/8661317\n\t\tSurfaceView surfaceView = (SurfaceView) findViewById(R.id.capture_preview_view); // 预览\n\t\tSurfaceHolder surfaceHolder = surfaceView.getHolder();\n\t\tif (hasSurface) {\n\t\t\t// The activity was paused but not stopped, so the surface still\n\t\t\t// exists. Therefore\n\t\t\t// surfaceCreated() won't be called, so init the camera here.\n\t\t\tinitCamera(surfaceHolder);\n\n\t\t}\n\t\telse {\n\t\t\t// 防止sdk8的设备初始化预览异常\n\t\t\tsurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);\n\n\t\t\t// Install the callback and wait for surfaceCreated() to init the\n\t\t\t// camera.\n\t\t\tsurfaceHolder.addCallback(this);\n\t\t}\n\n\t\t// 加载声音配置，其实在BeemManager的构造器中也会调用该方法，即在onCreate的时候会调用一次\n\t\tbeepManager.updatePrefs();\n\n\t\t// 启动闪光灯调节器\n\t\tambientLightManager.start(cameraManager);\n\n\t\t// 恢复活动监控器\n\t\tinactivityTimer.onResume();\n\n\t\tsource = IntentSource.NONE;\n\t\tdecodeFormats = null;\n\t\tcharacterSet = null;\n\t}\n\n\t@Override\n\tprotected void onPause() {\n\t\tif (handler != null) {\n\t\t\thandler.quitSynchronously();\n\t\t\thandler = null;\n\t\t}\n\t\tinactivityTimer.onPause();\n\t\tambientLightManager.stop();\n\t\tbeepManager.close();\n\n\t\t// 关闭摄像头\n\t\tcameraManager.closeDriver();\n\t\tif (!hasSurface) {\n\t\t\tSurfaceView surfaceView = (SurfaceView) findViewById(R.id.capture_preview_view);\n\t\t\tSurfaceHolder surfaceHolder = surfaceView.getHolder();\n\t\t\tsurfaceHolder.removeCallback(this);\n\t\t}\n\t\tsuper.onPause();\n\t}\n\n\t@Override\n\tprotected void onDestroy() {\n\t\tinactivityTimer.shutdown();\n\t\tsuper.onDestroy();\n\t}\n\n\t@Override\n\tpublic boolean onKeyDown(int keyCode, KeyEvent event) {\n\t\tswitch (keyCode) {\n\t\t\tcase KeyEvent.KEYCODE_BACK:\n\t\t\t\tif ((source == IntentSource.NONE) && lastResult != null) { // 重新进行扫描\n\t\t\t\t\trestartPreviewAfterDelay(0L);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase KeyEvent.KEYCODE_FOCUS:\n\t\t\tcase KeyEvent.KEYCODE_CAMERA:\n\t\t\t\t// Handle these events so they don't launch the Camera app\n\t\t\t\treturn true;\n\n\t\t\tcase KeyEvent.KEYCODE_VOLUME_UP:\n\t\t\t\tcameraManager.zoomIn();\n\t\t\t\treturn true;\n\n\t\t\tcase KeyEvent.KEYCODE_VOLUME_DOWN:\n\t\t\t\tcameraManager.zoomOut();\n\t\t\t\treturn true;\n\n\t\t}\n\t\treturn super.onKeyDown(keyCode, event);\n\t}\n\n\t@Override\n\tpublic void onActivityResult(int requestCode, int resultCode, Intent intent) {\n\n\t\tif (resultCode == RESULT_OK) {\n\t\t\tfinal ProgressDialog progressDialog;\n\t\t\tswitch (requestCode) {\n\t\t\t\tcase REQUEST_CODE:\n\n\t\t\t\t\t// 获取选中图片的路径\n\t\t\t\t\tCursor cursor = getContentResolver().query(\n\t\t\t\t\t\t\tintent.getData(), null, null, null, null);\n\t\t\t\t\tif (cursor.moveToFirst()) {\n\t\t\t\t\t\tphotoPath = cursor.getString(cursor\n\t\t\t\t\t\t\t\t.getColumnIndex(MediaStore.Images.Media.DATA));\n\t\t\t\t\t}\n\t\t\t\t\tcursor.close();\n\n\t\t\t\t\tprogressDialog = new ProgressDialog(this);\n\t\t\t\t\tprogressDialog.setMessage(\"正在扫描...\");\n\t\t\t\t\tprogressDialog.setCancelable(false);\n\t\t\t\t\tprogressDialog.show();\n\n\t\t\t\t\tnew Thread(new Runnable() {\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\t\tBitmap img = BitmapUtils\n\t\t\t\t\t\t\t\t\t.getCompressedBitmap(photoPath);\n\n\t\t\t\t\t\t\tBitmapDecoder decoder = new BitmapDecoder(\n\t\t\t\t\t\t\t\t\tCaptureActivity.this);\n\t\t\t\t\t\t\tResult result = decoder.getRawResult(img);\n\n\t\t\t\t\t\t\tif (result != null) {\n\t\t\t\t\t\t\t\tMessage m = mHandler.obtainMessage();\n\t\t\t\t\t\t\t\tm.what = PARSE_BARCODE_SUC;\n\t\t\t\t\t\t\t\tm.obj = ResultParser.parseResult(result)\n\t\t\t\t\t\t\t\t\t\t.toString();\n\t\t\t\t\t\t\t\tmHandler.sendMessage(m);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tMessage m = mHandler.obtainMessage();\n\t\t\t\t\t\t\t\tm.what = PARSE_BARCODE_FAIL;\n\t\t\t\t\t\t\t\tmHandler.sendMessage(m);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tprogressDialog.dismiss();\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}).start();\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void surfaceCreated(SurfaceHolder holder) {\n\t\tif (holder == null) {\n\t\t\tLog.e(TAG,\n\t\t\t\t\t\"*** WARNING *** surfaceCreated() gave us a null surface!\");\n\t\t}\n\t\tif (!hasSurface) {\n\t\t\thasSurface = true;\n\t\t\tinitCamera(holder);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void surfaceChanged(SurfaceHolder holder, int format, int width,\n\t\t\tint height) {\n\t\t/*hasSurface = false;*/\n\t}\n\n\t@Override\n\tpublic void surfaceDestroyed(SurfaceHolder holder) {\n\t\thasSurface = false;\n\t}\n\n\t/**\n\t * A valid barcode has been found, so give an indication of success and show\n\t * the results.\n\t * \n\t * @param rawResult\n\t *            The contents of the barcode.\n\t * @param scaleFactor\n\t *            amount by which thumbnail was scaled\n\t * @param barcode\n\t *            A greyscale bitmap of the camera data which was decoded.\n\t */\n\tpublic void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {\n\n\t\t// 重新计时\n\t\tinactivityTimer.onActivity();\n\n\t\tlastResult = rawResult;\n\n\t\t// 把图片画到扫描框\n\t\tviewfinderView.drawResultBitmap(barcode);\n\n\t\tbeepManager.playBeepSoundAndVibrate();\n\n\t\tToast.makeText(this,\n\t\t\t\t\"识别结果:\" + ResultParser.parseResult(rawResult).toString(),\n\t\t\t\tToast.LENGTH_SHORT).show();\n\n\t}\n\n\tpublic void restartPreviewAfterDelay(long delayMS) {\n\t\tif (handler != null) {\n\t\t\thandler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);\n\t\t}\n\t\tresetStatusView();\n\t}\n\n\tpublic ViewfinderView getViewfinderView() {\n\t\treturn viewfinderView;\n\t}\n\n\tpublic Handler getHandler() {\n\t\treturn handler;\n\t}\n\n\tpublic CameraManager getCameraManager() {\n\t\treturn cameraManager;\n\t}\n\n\tprivate void resetStatusView() {\n\t\tviewfinderView.setVisibility(View.VISIBLE);\n\t\tlastResult = null;\n\t}\n\n\tpublic void drawViewfinder() {\n\t\tviewfinderView.drawViewfinder();\n\t}\n\n\tprivate void initCamera(SurfaceHolder surfaceHolder) {\n\t\tif (surfaceHolder == null) {\n\t\t\tthrow new IllegalStateException(\"No SurfaceHolder provided\");\n\t\t}\n\n\t\tif (cameraManager.isOpen()) {\n\t\t\tLog.w(TAG,\n\t\t\t\t\t\"initCamera() while already open -- late SurfaceView callback?\");\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tcameraManager.openDriver(surfaceHolder);\n\t\t\t// Creating the handler starts the preview, which can also throw a\n\t\t\t// RuntimeException.\n\t\t\tif (handler == null) {\n\t\t\t\thandler = new CaptureActivityHandler(this, decodeFormats,\n\t\t\t\t\t\tdecodeHints, characterSet, cameraManager);\n\t\t\t}\n\t\t\tdecodeOrStoreSavedBitmap(null, null);\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\tLog.w(TAG, ioe);\n\t\t\tdisplayFrameworkBugMessageAndExit();\n\t\t}\n\t\tcatch (RuntimeException e) {\n\t\t\t// Barcode Scanner has seen crashes in the wild of this variety:\n\t\t\t// java.?lang.?RuntimeException: Fail to connect to camera service\n\t\t\tLog.w(TAG, \"Unexpected error initializing camera\", e);\n\t\t\tdisplayFrameworkBugMessageAndExit();\n\t\t}\n\t}\n\n\t/**\n\t * 向CaptureActivityHandler中发送消息，并展示扫描到的图像\n\t * \n\t * @param bitmap\n\t * @param result\n\t */\n\tprivate void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {\n\t\t// Bitmap isn't used yet -- will be used soon\n\t\tif (handler == null) {\n\t\t\tsavedResultToShow = result;\n\t\t}\n\t\telse {\n\t\t\tif (result != null) {\n\t\t\t\tsavedResultToShow = result;\n\t\t\t}\n\t\t\tif (savedResultToShow != null) {\n\t\t\t\tMessage message = Message.obtain(handler,\n\t\t\t\t\t\tR.id.decode_succeeded, savedResultToShow);\n\t\t\t\thandler.sendMessage(message);\n\t\t\t}\n\t\t\tsavedResultToShow = null;\n\t\t}\n\t}\n\n\tprivate void displayFrameworkBugMessageAndExit() {\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(this);\n\t\tbuilder.setTitle(getString(R.string.app_name));\n\t\tbuilder.setMessage(getString(R.string.msg_camera_framework_bug));\n\t\tbuilder.setPositiveButton(R.string.button_ok, new FinishListener(this));\n\t\tbuilder.setOnCancelListener(new FinishListener(this));\n\t\tbuilder.show();\n\t}\n\n\t@Override\n\tpublic void onClick(View v) {\n\t\tswitch (v.getId()) {\n\t\t\tcase R.id.capture_scan_photo: // 图片识别\n\t\t\t\t// 打开手机中的相册\n\t\t\t\tIntent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // \"android.intent.action.GET_CONTENT\"\n\t\t\t\tinnerIntent.setType(\"image/*\");\n\t\t\t\tIntent wrapperIntent = Intent.createChooser(innerIntent,\n\t\t\t\t\t\t\"选择二维码图片\");\n\t\t\t\tthis.startActivityForResult(wrapperIntent, REQUEST_CODE);\n\t\t\t\tbreak;\n\n\t\t\tcase R.id.capture_flashlight:\n\t\t\t\tif (isFlashlightOpen) {\n\t\t\t\t\tcameraManager.setTorch(false); // 关闭闪光灯\n\t\t\t\t\tisFlashlightOpen = false;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcameraManager.setTorch(true); // 打开闪光灯\n\t\t\t\t\tisFlashlightOpen = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/FinishListener.java",
    "content": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner;\n\nimport android.app.Activity;\nimport android.content.DialogInterface;\n\n/**\n * Simple listener used to exit the app in a few cases.\n *\n * @author Sean Owen\n */\npublic final class FinishListener implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {\n\n  private final Activity activityToFinish;\n\n  public FinishListener(Activity activityToFinish) {\n    this.activityToFinish = activityToFinish;\n  }\n\n  @Override\n  public void onCancel(DialogInterface dialogInterface) {\n    run();\n  }\n\n  @Override\n  public void onClick(DialogInterface dialogInterface, int i) {\n    run();\n  }\n\n  private void run() {\n    activityToFinish.finish();\n  }\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/InactivityTimer.java",
    "content": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.AsyncTask;\nimport android.os.BatteryManager;\nimport android.util.Log;\nimport cn.hugo.android.scanner.common.Runnable;\n\n/**\n * Finishes an activity after a period of inactivity if the device is on battery\n * power. <br/>\n * <br/>\n * \n * 该活动监控器全程监控扫描活跃状态，与CaptureActivity生命周期相同\n */\nfinal class InactivityTimer {\n\n\tprivate static final String TAG = InactivityTimer.class.getSimpleName();\n\n\t/**\n\t * 如果在5min内扫描器没有被使用过，则自动finish掉activity\n\t */\n\tprivate static final long INACTIVITY_DELAY_MS = 5 * 60 * 1000L;\n\n\t/**\n\t * 在本app中，此activity即为CaptureActivity\n\t */\n\tprivate final Activity activity;\n\t/**\n\t * 接受系统广播：手机是否连通电源\n\t */\n\tprivate final BroadcastReceiver powerStatusReceiver;\n\tprivate boolean registered;\n\tprivate AsyncTask<?, ?, ?> inactivityTask;\n\n\tInactivityTimer(Activity activity) {\n\t\tthis.activity = activity;\n\t\tpowerStatusReceiver = new PowerStatusReceiver();\n\t\tregistered = false;\n\t\tonActivity();\n\t}\n\n\t/**\n\t * 首先终止之前的监控任务，然后新起一个监控任务\n\t */\n\tsynchronized void onActivity() {\n\t\tcancel();\n\t\tinactivityTask = new InactivityAsyncTask();\n\t\tRunnable.execAsync(inactivityTask);\n\t}\n\n\tpublic synchronized void onPause() {\n\t\tcancel();\n\t\tif (registered) {\n\t\t\tactivity.unregisterReceiver(powerStatusReceiver);\n\t\t\tregistered = false;\n\t\t}\n\t\telse {\n\t\t\tLog.w(TAG, \"PowerStatusReceiver was never registered?\");\n\t\t}\n\t}\n\n\tpublic synchronized void onResume() {\n\t\tif (registered) {\n\t\t\tLog.w(TAG, \"PowerStatusReceiver was already registered?\");\n\t\t}\n\t\telse {\n\t\t\tactivity.registerReceiver(powerStatusReceiver, new IntentFilter(\n\t\t\t\t\tIntent.ACTION_BATTERY_CHANGED));\n\t\t\tregistered = true;\n\t\t}\n\t\tonActivity();\n\t}\n\n\t/**\n\t * 取消监控任务\n\t */\n\tprivate synchronized void cancel() {\n\t\tAsyncTask<?, ?, ?> task = inactivityTask;\n\t\tif (task != null) {\n\t\t\ttask.cancel(true);\n\t\t\tinactivityTask = null;\n\t\t}\n\t}\n\n\tvoid shutdown() {\n\t\tcancel();\n\t}\n\n\t/**\n\t * 监听是否连通电源的系统广播。如果连通电源，则停止监控任务，否则重启监控任务\n\t */\n\tprivate final class PowerStatusReceiver extends BroadcastReceiver {\n\t\t@Override\n\t\tpublic void onReceive(Context context, Intent intent) {\n\t\t\tif (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {\n\t\t\t\t// 0 indicates that we're on battery\n\t\t\t\tboolean onBatteryNow = intent.getIntExtra(\n\t\t\t\t\t\tBatteryManager.EXTRA_PLUGGED, -1) <= 0;\n\t\t\t\tif (onBatteryNow) {\n\t\t\t\t\tInactivityTimer.this.onActivity();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tInactivityTimer.this.cancel();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * 该任务很简单，就是在INACTIVITY_DELAY_MS时间后终结activity\n\t */\n\tprivate final class InactivityAsyncTask extends\n\t\t\tAsyncTask<Object, Object, Object> {\n\t\t@Override\n\t\tprotected Object doInBackground(Object... objects) {\n\t\t\ttry {\n\t\t\t\tThread.sleep(INACTIVITY_DELAY_MS);\n\t\t\t\tLog.i(TAG, \"Finishing activity due to inactivity\");\n\t\t\t\tactivity.finish();\n\t\t\t}\n\t\t\tcatch (InterruptedException e) {\n\t\t\t\t// continue without killing\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/IntentSource.java",
    "content": "/*\n * Copyright (C) 2011 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner;\n\nenum IntentSource {\n\n  NATIVE_APP_INTENT,\n  PRODUCT_SEARCH_LINK,\n  ZXING_LINK,\n  NONE\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/Intents.java",
    "content": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner;\n\n/**\n * This class provides the constants to use when sending an Intent to Barcode Scanner.\n * These strings are effectively API and cannot be changed.\n *\n * @author dswitkin@google.com (Daniel Switkin)\n */\npublic final class Intents {\n  private Intents() {\n  }\n\n  public static final class Scan {\n    /**\n     * Send this intent to open the Barcodes app in scanning mode, find a barcode, and return\n     * the results.\n     */\n    public static final String ACTION = \"com.google.zxing.client.android.SCAN\";\n\n    /**\n     * By default, sending this will decode all barcodes that we understand. However it\n     * may be useful to limit scanning to certain formats. Use\n     * {@link android.content.Intent#putExtra(String, String)} with one of the values below.\n     *\n     * Setting this is effectively shorthand for setting explicit formats with {@link #FORMATS}.\n     * It is overridden by that setting.\n     */\n    public static final String MODE = \"SCAN_MODE\";\n\n    /**\n     * Decode only UPC and EAN barcodes. This is the right choice for shopping apps which get\n     * prices, reviews, etc. for products.\n     */\n    public static final String PRODUCT_MODE = \"PRODUCT_MODE\";\n\n    /**\n     * Decode only 1D barcodes.\n     */\n    public static final String ONE_D_MODE = \"ONE_D_MODE\";\n\n    /**\n     * Decode only QR codes.\n     */\n    public static final String QR_CODE_MODE = \"QR_CODE_MODE\";\n\n    /**\n     * Decode only Data Matrix codes.\n     */\n    public static final String DATA_MATRIX_MODE = \"DATA_MATRIX_MODE\";\n\n    /**\n     * Decode only Aztec.\n     */\n    public static final String AZTEC_MODE = \"AZTEC_MODE\";\n\n    /**\n     * Decode only PDF417.\n     */\n    public static final String PDF417_MODE = \"PDF417_MODE\";\n\n    /**\n     * Comma-separated list of formats to scan for. The values must match the names of\n     * {@link com.google.zxing.BarcodeFormat}s, e.g. {@link com.google.zxing.BarcodeFormat#EAN_13}.\n     * Example: \"EAN_13,EAN_8,QR_CODE\". This overrides {@link #MODE}.\n     */\n    public static final String FORMATS = \"SCAN_FORMATS\";\n\t\n    /**\n     * Optional parameter to specify the id of the camera from which to recognize barcodes.\n     * Overrides the default camera that would otherwise would have been selected.\n     * If provided, should be an int.\n     */\n    public static final String CAMERA_ID = \"SCAN_CAMERA_ID\";\n\n    /**\n     * @see com.google.zxing.DecodeHintType#CHARACTER_SET\n     */\n    public static final String CHARACTER_SET = \"CHARACTER_SET\";\n\n    /**\n     * Optional parameters to specify the width and height of the scanning rectangle in pixels.\n     * The app will try to honor these, but will clamp them to the size of the preview frame.\n     * You should specify both or neither, and pass the size as an int.\n     */\n    public static final String WIDTH = \"SCAN_WIDTH\";\n    public static final String HEIGHT = \"SCAN_HEIGHT\";\n\n    /**\n     * Desired duration in milliseconds for which to pause after a successful scan before\n     * returning to the calling intent. Specified as a long, not an integer!\n     * For example: 1000L, not 1000.\n     */\n    public static final String RESULT_DISPLAY_DURATION_MS = \"RESULT_DISPLAY_DURATION_MS\";\n\n    /**\n     * Prompt to show on-screen when scanning by intent. Specified as a {@link String}.\n     */\n    public static final String PROMPT_MESSAGE = \"PROMPT_MESSAGE\";\n\n    /**\n     * If a barcode is found, Barcodes returns {@link android.app.Activity#RESULT_OK} to\n     * {@link android.app.Activity#onActivityResult(int, int, android.content.Intent)}\n     * of the app which requested the scan via\n     * {@link android.app.Activity#startActivityForResult(android.content.Intent, int)}\n     * The barcodes contents can be retrieved with\n     * {@link android.content.Intent#getStringExtra(String)}. \n     * If the user presses Back, the result code will be {@link android.app.Activity#RESULT_CANCELED}.\n     */\n    public static final String RESULT = \"SCAN_RESULT\";\n\n    /**\n     * Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_FORMAT}\n     * to determine which barcode format was found.\n     * See {@link com.google.zxing.BarcodeFormat} for possible values.\n     */\n    public static final String RESULT_FORMAT = \"SCAN_RESULT_FORMAT\";\n\n    /**\n     * Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_UPC_EAN_EXTENSION}\n     * to return the content of any UPC extension barcode that was also found. Only applicable\n     * to {@link com.google.zxing.BarcodeFormat#UPC_A} and {@link com.google.zxing.BarcodeFormat#EAN_13}\n     * formats.\n     */\n    public static final String RESULT_UPC_EAN_EXTENSION = \"SCAN_RESULT_UPC_EAN_EXTENSION\";\n\n    /**\n     * Call {@link android.content.Intent#getByteArrayExtra(String)} with {@link #RESULT_BYTES}\n     * to get a {@code byte[]} of raw bytes in the barcode, if available.\n     */\n    public static final String RESULT_BYTES = \"SCAN_RESULT_BYTES\";\n\n    /**\n     * Key for the value of {@link com.google.zxing.ResultMetadataType#ORIENTATION}, if available.\n     * Call {@link android.content.Intent#getIntArrayExtra(String)} with {@link #RESULT_ORIENTATION}.\n     */\n    public static final String RESULT_ORIENTATION = \"SCAN_RESULT_ORIENTATION\";\n\n    /**\n     * Key for the value of {@link com.google.zxing.ResultMetadataType#ERROR_CORRECTION_LEVEL}, if available.\n     * Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_ERROR_CORRECTION_LEVEL}.\n     */\n    public static final String RESULT_ERROR_CORRECTION_LEVEL = \"SCAN_RESULT_ERROR_CORRECTION_LEVEL\";\n\n    /**\n     * Prefix for keys that map to the values of {@link com.google.zxing.ResultMetadataType#BYTE_SEGMENTS},\n     * if available. The actual values will be set under a series of keys formed by adding 0, 1, 2, ...\n     * to this prefix. So the first byte segment is under key \"SCAN_RESULT_BYTE_SEGMENTS_0\" for example.\n     * Call {@link android.content.Intent#getByteArrayExtra(String)} with these keys.\n     */\n    public static final String RESULT_BYTE_SEGMENTS_PREFIX = \"SCAN_RESULT_BYTE_SEGMENTS_\";\n\n    /**\n     * Setting this to false will not save scanned codes in the history. Specified as a {@code boolean}.\n     */\n    public static final String SAVE_HISTORY = \"SAVE_HISTORY\";\n\n    private Scan() {\n    }\n  }\n\n  public static final class History {\n\n    public static final String ITEM_NUMBER = \"ITEM_NUMBER\";\n\n    private History() {\n    }\n  }\n\n  public static final class Encode {\n    /**\n     * Send this intent to encode a piece of data as a QR code and display it full screen, so\n     * that another person can scan the barcode from your screen.\n     */\n    public static final String ACTION = \"com.google.zxing.client.android.ENCODE\";\n\n    /**\n     * The data to encode. Use {@link android.content.Intent#putExtra(String, String)} or\n     * {@link android.content.Intent#putExtra(String, android.os.Bundle)}, \n     * depending on the type and format specified. Non-QR Code formats should\n     * just use a String here. For QR Code, see Contents for details.\n     */\n    public static final String DATA = \"ENCODE_DATA\";\n\n    /**\n     * The type of data being supplied if the format is QR Code. Use\n     * {@link android.content.Intent#putExtra(String, String)} with one of {@link Contents.Type}.\n     */\n    public static final String TYPE = \"ENCODE_TYPE\";\n\n    /**\n     * The barcode format to be displayed. If this isn't specified or is blank,\n     * it defaults to QR Code. Use {@link android.content.Intent#putExtra(String, String)}, where\n     * format is one of {@link com.google.zxing.BarcodeFormat}.\n     */\n    public static final String FORMAT = \"ENCODE_FORMAT\";\n\n    /**\n     * Normally the contents of the barcode are displayed to the user in a TextView. Setting this\n     * boolean to false will hide that TextView, showing only the encode barcode.\n     */\n    public static final String SHOW_CONTENTS = \"ENCODE_SHOW_CONTENTS\";\n\n    private Encode() {\n    }\n  }\n\n  public static final class SearchBookContents {\n    /**\n     * Use Google Book Search to search the contents of the book provided.\n     */\n    public static final String ACTION = \"com.google.zxing.client.android.SEARCH_BOOK_CONTENTS\";\n\n    /**\n     * The book to search, identified by ISBN number.\n     */\n    public static final String ISBN = \"ISBN\";\n\n    /**\n     * An optional field which is the text to search for.\n     */\n    public static final String QUERY = \"QUERY\";\n\n    private SearchBookContents() {\n    }\n  }\n\n  public static final class WifiConnect {\n    /**\n     * Internal intent used to trigger connection to a wi-fi network.\n     */\n    public static final String ACTION = \"com.google.zxing.client.android.WIFI_CONNECT\";\n\n    /**\n     * The network to connect to, all the configuration provided here.\n     */\n    public static final String SSID = \"SSID\";\n\n    /**\n     * The network to connect to, all the configuration provided here.\n     */\n    public static final String TYPE = \"TYPE\";\n\n    /**\n     * The network to connect to, all the configuration provided here.\n     */\n    public static final String PASSWORD = \"PASSWORD\";\n\n    private WifiConnect() {\n    }\n  }\n\n  public static final class Share {\n    /**\n     * Give the user a choice of items to encode as a barcode, then render it as a QR Code and\n     * display onscreen for a friend to scan with their phone.\n     */\n    public static final String ACTION = \"com.google.zxing.client.android.SHARE\";\n\n    private Share() {\n    }\n  }\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/camera/AutoFocusManager.java",
    "content": "/*\n * Copyright (C) 2012 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.camera;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.hardware.Camera;\nimport android.os.AsyncTask;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport cn.hugo.android.scanner.common.Runnable;\nimport cn.hugo.android.scanner.config.Config;\n\n/**\n * 由于对焦不是一次性完成的任务（手抖），而系统提供的对焦仅有Camera.autoFocus()方法，\n * 因此需要一个线程来不断调用Camera.autoFocus()直到用户满意按下快门为止\n */\nfinal class AutoFocusManager implements Camera.AutoFocusCallback {\n\n\tprivate static final String TAG = AutoFocusManager.class.getSimpleName();\n\n\tprivate static final long AUTO_FOCUS_INTERVAL_MS = 2000L;\n\tprivate static final Collection<String> FOCUS_MODES_CALLING_AF;\n\tstatic {\n\t\tFOCUS_MODES_CALLING_AF = new ArrayList<String>(2);\n\t\tFOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO);\n\t\tFOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO);\n\t}\n\n\tprivate boolean active;\n\tprivate final boolean useAutoFocus;\n\tprivate final Camera camera;\n\tprivate AsyncTask<?, ?, ?> outstandingTask;\n\n\tAutoFocusManager(Context context, Camera camera) {\n\t\tthis.camera = camera;\n\t\tSharedPreferences sharedPrefs = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(context);\n\t\tString currentFocusMode = camera.getParameters().getFocusMode();\n\t\tuseAutoFocus = sharedPrefs.getBoolean(Config.KEY_AUTO_FOCUS, true)\n\t\t\t\t&& FOCUS_MODES_CALLING_AF.contains(currentFocusMode);\n\t\tLog.i(TAG, \"Current focus mode '\" + currentFocusMode\n\t\t\t\t+ \"'; use auto focus? \" + useAutoFocus);\n\t\tstart();\n\t}\n\n\t@Override\n\tpublic synchronized void onAutoFocus(boolean success, Camera theCamera) {\n\t\tif (active) {\n\t\t\toutstandingTask = new AutoFocusTask();\n\t\t\tRunnable.execAsync(outstandingTask);\n\t\t}\n\t}\n\n\tsynchronized void start() {\n\t\tif (useAutoFocus) {\n\t\t\tactive = true;\n\t\t\ttry {\n\t\t\t\tcamera.autoFocus(this);\n\t\t\t}\n\t\t\tcatch (RuntimeException re) {\n\t\t\t\t// Have heard RuntimeException reported in Android 4.0.x+;\n\t\t\t\t// continue?\n\t\t\t\tLog.w(TAG, \"Unexpected exception while focusing\", re);\n\t\t\t}\n\t\t}\n\t}\n\n\tsynchronized void stop() {\n\t\tif (useAutoFocus) {\n\t\t\ttry {\n\t\t\t\tcamera.cancelAutoFocus();\n\t\t\t}\n\t\t\tcatch (RuntimeException re) {\n\t\t\t\t// Have heard RuntimeException reported in Android 4.0.x+;\n\t\t\t\t// continue?\n\t\t\t\tLog.w(TAG, \"Unexpected exception while cancelling focusing\", re);\n\t\t\t}\n\t\t}\n\t\tif (outstandingTask != null) {\n\t\t\toutstandingTask.cancel(true);\n\t\t\toutstandingTask = null;\n\t\t}\n\t\tactive = false;\n\t}\n\n\tprivate final class AutoFocusTask extends AsyncTask<Object, Object, Object> {\n\t\t@Override\n\t\tprotected Object doInBackground(Object... voids) {\n\t\t\ttry {\n\t\t\t\tThread.sleep(AUTO_FOCUS_INTERVAL_MS);\n\t\t\t}\n\t\t\tcatch (InterruptedException e) {\n\t\t\t\t// continue\n\t\t\t}\n\t\t\tsynchronized (AutoFocusManager.this) {\n\t\t\t\tif (active) {\n\t\t\t\t\tstart();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/camera/CameraConfigurationManager.java",
    "content": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.camera;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.hardware.Camera;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.view.Display;\nimport android.view.WindowManager;\nimport cn.hugo.android.scanner.config.Config;\n\n/**\n * A class which deals with reading, parsing, and setting the camera parameters\n * which are used to configure the camera hardware.\n * \n * <br/>\n * \n * 摄像头参数的设置类\n */\nfinal class CameraConfigurationManager {\n\n\tprivate static final String TAG = \"CameraConfiguration\";\n\n\t// This is bigger than the size of a small screen, which is still supported.\n\t// The routine\n\t// below will still select the default (presumably 320x240) size for these.\n\t// This prevents\n\t// accidental selection of very low resolution on some devices.\n\tprivate static final int MIN_PREVIEW_PIXELS = 480 * 320; // normal screen\n\t// private static final float MAX_EXPOSURE_COMPENSATION = 1.5f;\n\t// private static final float MIN_EXPOSURE_COMPENSATION = 0.0f;\n\tprivate static final double MAX_ASPECT_DISTORTION = 0.15;\n\n\tprivate final Context context;\n\t/**\n\t * 屏幕分辨率\n\t */\n\tprivate Point screenResolution;\n\n\t/**\n\t * 相机分辨率\n\t */\n\tprivate Point cameraResolution;\n\n\tCameraConfigurationManager(Context context) {\n\t\tthis.context = context;\n\t}\n\n\t/**\n\t * Reads, one time, values from the camera that are needed by the app.\n\t */\n\tvoid initFromCameraParameters(Camera camera) {\n\t\tCamera.Parameters parameters = camera.getParameters();\n\t\tWindowManager manager = (WindowManager) context\n\t\t\t\t.getSystemService(Context.WINDOW_SERVICE);\n\t\tDisplay display = manager.getDefaultDisplay();\n\t\tPoint theScreenResolution = new Point();\n\n\t\t// sdk8出错\n\t\t// display.getSize(theScreenResolution);\n\n\t\t// 改为此方式\n\t\ttheScreenResolution = getDisplaySize(display);\n\n\t\tscreenResolution = theScreenResolution;\n\t\tLog.i(TAG, \"Screen resolution: \" + screenResolution);\n\n\t\t//解决竖屏拉伸\n\t\tPoint screenResolutionForCamera = new Point();\n        \tscreenResolutionForCamera.x = screenResolution.x;\n        \tscreenResolutionForCamera.y = screenResolution.y;\n        \t// preview size is always something like 480*320, other 320*480\n\t\tif (screenResolution.x < screenResolution.y) {\n        \t\tscreenResolutionForCamera.x = screenResolution.y;\n        \t\tscreenResolutionForCamera.y = screenResolution.x;\n        \t}\n\n\t\tcameraResolution = findBestPreviewSizeValue(parameters,\n\t\t\t\tscreenResolutionForCamera);\n\t\t\t\t\n\t\tLog.i(TAG, \"Camera resolution: \" + cameraResolution);\n\t}\n\n\t@SuppressLint(\"NewApi\")\n\tprivate Point getDisplaySize(final Display display) {\n\t\tfinal Point point = new Point();\n\t\ttry {\n\t\t\tdisplay.getSize(point);\n\t\t}\n\t\tcatch (java.lang.NoSuchMethodError ignore) { // Older device\n\t\t\tpoint.x = display.getWidth();\n\t\t\tpoint.y = display.getHeight();\n\t\t}\n\t\treturn point;\n\t}\n\n\tvoid setDesiredCameraParameters(Camera camera, boolean safeMode) {\n\t\tCamera.Parameters parameters = camera.getParameters();\n\n\t\tif (parameters == null) {\n\t\t\tLog.w(TAG,\n\t\t\t\t\t\"Device error: no camera parameters are available. Proceeding without configuration.\");\n\t\t\treturn;\n\t\t}\n\n\t\tLog.i(TAG, \"Initial camera parameters: \" + parameters.flatten());\n\n\t\tif (safeMode) {\n\t\t\tLog.w(TAG,\n\t\t\t\t\t\"In camera config safe mode -- most settings will not be honored\");\n\t\t}\n\n\t\tSharedPreferences prefs = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(context);\n\n\t\t// 初始化闪光灯\n\t\tinitializeTorch(parameters, prefs, safeMode);\n\n\t\t// 默认使用自动对焦\n\t\tString focusMode = findSettableValue(\n\t\t\t\tparameters.getSupportedFocusModes(),\n\t\t\t\tCamera.Parameters.FOCUS_MODE_AUTO);\n\n\t\t// Maybe selected auto-focus but not available, so fall through here:\n\t\tif (!safeMode && focusMode == null) {\n\t\t\tfocusMode = findSettableValue(parameters.getSupportedFocusModes(),\n\t\t\t\t\tCamera.Parameters.FOCUS_MODE_MACRO,\n\t\t\t\t\tCamera.Parameters.FOCUS_MODE_EDOF);\n\t\t}\n\t\tif (focusMode != null) {\n\t\t\tparameters.setFocusMode(focusMode);\n\t\t}\n\n\t\tif (prefs.getBoolean(Config.KEY_INVERT_SCAN, false)) {\n\t\t\tString colorMode = findSettableValue(\n\t\t\t\t\tparameters.getSupportedColorEffects(),\n\t\t\t\t\tCamera.Parameters.EFFECT_NEGATIVE);\n\t\t\tif (colorMode != null) {\n\t\t\t\tparameters.setColorEffect(colorMode);\n\t\t\t}\n\t\t}\n\n\t\tparameters.setPreviewSize(cameraResolution.x, cameraResolution.y);\n\t\tcamera.setParameters(parameters);\n\n\t\tCamera.Parameters afterParameters = camera.getParameters();\n\t\tCamera.Size afterSize = afterParameters.getPreviewSize();\n\t\tif (afterSize != null\n\t\t\t\t&& (cameraResolution.x != afterSize.width || cameraResolution.y != afterSize.height)) {\n\t\t\tLog.w(TAG, \"Camera said it supported preview size \"\n\t\t\t\t\t+ cameraResolution.x + 'x' + cameraResolution.y\n\t\t\t\t\t+ \", but after setting it, preview size is \"\n\t\t\t\t\t+ afterSize.width + 'x' + afterSize.height);\n\t\t\tcameraResolution.x = afterSize.width;\n\t\t\tcameraResolution.y = afterSize.height;\n\t\t}\n\n\t\tcamera.setDisplayOrientation(90);\n\t}\n\n\tPoint getCameraResolution() {\n\t\treturn cameraResolution;\n\t}\n\n\tPoint getScreenResolution() {\n\t\treturn screenResolution;\n\t}\n\n\tboolean getTorchState(Camera camera) {\n\t\tif (camera != null) {\n\t\t\tCamera.Parameters parameters = camera.getParameters();\n\t\t\tif (parameters != null) {\n\t\t\t\tString flashMode = camera.getParameters().getFlashMode();\n\t\t\t\treturn flashMode != null\n\t\t\t\t\t\t&& (Camera.Parameters.FLASH_MODE_ON.equals(flashMode) || Camera.Parameters.FLASH_MODE_TORCH\n\t\t\t\t\t\t\t\t.equals(flashMode));\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tvoid setTorch(Camera camera, boolean newSetting) {\n\t\tCamera.Parameters parameters = camera.getParameters();\n\t\tdoSetTorch(parameters, newSetting, false);\n\t\tcamera.setParameters(parameters);\n\t}\n\n\tprivate void initializeTorch(Camera.Parameters parameters,\n\t\t\tSharedPreferences prefs, boolean safeMode) {\n\t\tboolean currentSetting = FrontLightMode.readPref(prefs) == FrontLightMode.ON;\n\t\tdoSetTorch(parameters, currentSetting, safeMode);\n\t}\n\n\tprivate void doSetTorch(Camera.Parameters parameters, boolean newSetting,\n\t\t\tboolean safeMode) {\n\t\tString flashMode;\n\t\tif (newSetting) {\n\t\t\tflashMode = findSettableValue(parameters.getSupportedFlashModes(),\n\t\t\t\t\tCamera.Parameters.FLASH_MODE_TORCH,\n\t\t\t\t\tCamera.Parameters.FLASH_MODE_ON);\n\t\t}\n\t\telse {\n\t\t\tflashMode = findSettableValue(parameters.getSupportedFlashModes(),\n\t\t\t\t\tCamera.Parameters.FLASH_MODE_OFF);\n\t\t}\n\t\tif (flashMode != null) {\n\t\t\tparameters.setFlashMode(flashMode);\n\t\t}\n\t}\n\n\t/**\n\t * 从相机支持的分辨率中计算出最适合的预览界面尺寸\n\t * \n\t * @param parameters\n\t * @param screenResolution\n\t * @return\n\t */\n\tprivate Point findBestPreviewSizeValue(Camera.Parameters parameters,\n\t\t\tPoint screenResolution) {\n\t\tList<Camera.Size> rawSupportedSizes = parameters\n\t\t\t\t.getSupportedPreviewSizes();\n\t\tif (rawSupportedSizes == null) {\n\t\t\tLog.w(TAG,\n\t\t\t\t\t\"Device returned no supported preview sizes; using default\");\n\t\t\tCamera.Size defaultSize = parameters.getPreviewSize();\n\t\t\treturn new Point(defaultSize.width, defaultSize.height);\n\t\t}\n\n\t\t// Sort by size, descending\n\t\tList<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(\n\t\t\t\trawSupportedSizes);\n\t\tCollections.sort(supportedPreviewSizes, new Comparator<Camera.Size>() {\n\t\t\t@Override\n\t\t\tpublic int compare(Camera.Size a, Camera.Size b) {\n\t\t\t\tint aPixels = a.height * a.width;\n\t\t\t\tint bPixels = b.height * b.width;\n\t\t\t\tif (bPixels < aPixels) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tif (bPixels > aPixels) {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t});\n\n\t\tif (Log.isLoggable(TAG, Log.INFO)) {\n\t\t\tStringBuilder previewSizesString = new StringBuilder();\n\t\t\tfor (Camera.Size supportedPreviewSize : supportedPreviewSizes) {\n\t\t\t\tpreviewSizesString.append(supportedPreviewSize.width)\n\t\t\t\t\t\t.append('x').append(supportedPreviewSize.height)\n\t\t\t\t\t\t.append(' ');\n\t\t\t}\n\t\t\tLog.i(TAG, \"Supported preview sizes: \" + previewSizesString);\n\t\t}\n\n\t\tdouble screenAspectRatio = (double) screenResolution.x\n\t\t\t\t/ (double) screenResolution.y;\n\n\t\t// Remove sizes that are unsuitable\n\t\tIterator<Camera.Size> it = supportedPreviewSizes.iterator();\n\t\twhile (it.hasNext()) {\n\t\t\tCamera.Size supportedPreviewSize = it.next();\n\t\t\tint realWidth = supportedPreviewSize.width;\n\t\t\tint realHeight = supportedPreviewSize.height;\n\t\t\tif (realWidth * realHeight < MIN_PREVIEW_PIXELS) {\n\t\t\t\tit.remove();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tboolean isCandidatePortrait = realWidth < realHeight;\n\t\t\tint maybeFlippedWidth = isCandidatePortrait ? realHeight\n\t\t\t\t\t: realWidth;\n\t\t\tint maybeFlippedHeight = isCandidatePortrait ? realWidth\n\t\t\t\t\t: realHeight;\n\n\t\t\tdouble aspectRatio = (double) maybeFlippedWidth\n\t\t\t\t\t/ (double) maybeFlippedHeight;\n\t\t\tdouble distortion = Math.abs(aspectRatio - screenAspectRatio);\n\t\t\tif (distortion > MAX_ASPECT_DISTORTION) {\n\t\t\t\tit.remove();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (maybeFlippedWidth == screenResolution.x\n\t\t\t\t\t&& maybeFlippedHeight == screenResolution.y) {\n\t\t\t\tPoint exactPoint = new Point(realWidth, realHeight);\n\t\t\t\tLog.i(TAG, \"Found preview size exactly matching screen size: \"\n\t\t\t\t\t\t+ exactPoint);\n\t\t\t\treturn exactPoint;\n\t\t\t}\n\t\t}\n\n\t\t// If no exact match, use largest preview size. This was not a great\n\t\t// idea on older devices because\n\t\t// of the additional computation needed. We're likely to get here on\n\t\t// newer Android 4+ devices, where\n\t\t// the CPU is much more powerful.\n\t\tif (!supportedPreviewSizes.isEmpty()) {\n\t\t\tCamera.Size largestPreview = supportedPreviewSizes.get(0);\n\t\t\tPoint largestSize = new Point(largestPreview.width,\n\t\t\t\t\tlargestPreview.height);\n\t\t\tLog.i(TAG, \"Using largest suitable preview size: \" + largestSize);\n\t\t\treturn largestSize;\n\t\t}\n\n\t\t// If there is nothing at all suitable, return current preview size\n\t\tCamera.Size defaultPreview = parameters.getPreviewSize();\n\t\tPoint defaultSize = new Point(defaultPreview.width,\n\t\t\t\tdefaultPreview.height);\n\t\tLog.i(TAG, \"No suitable preview sizes, using default: \" + defaultSize);\n\n\t\treturn defaultSize;\n\t}\n\n\t/**\n\t * 在supportedValues中寻找desiredValues，找不到则返回null\n\t * \n\t * @param supportedValues\n\t * @param desiredValues\n\t * @return\n\t */\n\tprivate static String findSettableValue(Collection<String> supportedValues,\n\t\t\tString... desiredValues) {\n\t\tLog.i(TAG, \"Supported values: \" + supportedValues);\n\t\tString result = null;\n\t\tif (supportedValues != null) {\n\t\t\tfor (String desiredValue : desiredValues) {\n\t\t\t\tif (supportedValues.contains(desiredValue)) {\n\t\t\t\t\tresult = desiredValue;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tLog.i(TAG, \"Settable value: \" + result);\n\t\treturn result;\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/camera/CameraManager.java",
    "content": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.camera;\n\nimport java.io.IOException;\n\nimport android.content.Context;\nimport android.graphics.Point;\nimport android.graphics.Rect;\nimport android.hardware.Camera;\nimport android.os.Handler;\nimport android.util.Log;\nimport android.view.SurfaceHolder;\n\nimport com.google.zxing.PlanarYUVLuminanceSource;\n\n/**\n * This object wraps the Camera service object and expects to be the only one\n * talking to it. The implementation encapsulates the steps needed to take\n * preview-sized images, which are used for both preview and decoding. <br/>\n * <br/>\n * \n * 该类封装了相机的所有服务并且是该app中唯一与相机打交道的类\n * \n * @author dswitkin@google.com (Daniel Switkin)\n */\npublic final class CameraManager {\n\n\tprivate static final String TAG = CameraManager.class.getSimpleName();\n\n\tprivate static final int MIN_FRAME_WIDTH = 240;\n\n\tprivate static final int MAX_FRAME_WIDTH = 1200; // = 5/8 * 1920\n\n\tprivate final Context context;\n\n\tprivate final CameraConfigurationManager configManager;\n\n\tprivate Camera camera;\n\n\tprivate AutoFocusManager autoFocusManager;\n\n\tprivate Rect framingRect;\n\n\tprivate Rect framingRectInPreview;\n\n\tprivate boolean initialized;\n\n\tprivate boolean previewing;\n\n\tprivate int requestedFramingRectWidth;\n\n\tprivate int requestedFramingRectHeight;\n\n\t/**\n\t * Preview frames are delivered here, which we pass on to the registered\n\t * handler. Make sure to clear the handler so it will only receive one\n\t * message.\n\t */\n\tprivate final PreviewCallback previewCallback;\n\n\tpublic CameraManager(Context context) {\n\t\tthis.context = context;\n\t\tthis.configManager = new CameraConfigurationManager(context);\n\t\tpreviewCallback = new PreviewCallback(configManager);\n\t}\n\n\t/**\n\t * Opens the camera driver and initializes the hardware parameters.\n\t * \n\t * @param holder\n\t *            The surface object which the camera will draw preview frames\n\t *            into.\n\t * @throws IOException\n\t *             Indicates the camera driver failed to open.\n\t */\n\tpublic synchronized void openDriver(SurfaceHolder holder)\n\t\t\tthrows IOException {\n\t\tCamera theCamera = camera;\n\t\tif (theCamera == null) {\n\t\t\t// 获取手机背面的摄像头\n\t\t\ttheCamera = OpenCameraInterface.open();\n\t\t\tif (theCamera == null) {\n\t\t\t\tthrow new IOException();\n\t\t\t}\n\t\t\tcamera = theCamera;\n\t\t}\n\n\t\t// 设置摄像头预览view\n\t\ttheCamera.setPreviewDisplay(holder);\n\n\t\tif (!initialized) {\n\t\t\tinitialized = true;\n\t\t\tconfigManager.initFromCameraParameters(theCamera);\n\t\t\tif (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) {\n\t\t\t\tsetManualFramingRect(requestedFramingRectWidth,\n\t\t\t\t\t\trequestedFramingRectHeight);\n\t\t\t\trequestedFramingRectWidth = 0;\n\t\t\t\trequestedFramingRectHeight = 0;\n\t\t\t}\n\t\t}\n\n\t\tCamera.Parameters parameters = theCamera.getParameters();\n\t\tString parametersFlattened = parameters == null ? null : parameters\n\t\t\t\t.flatten(); // Save\n\t\t\t\t\t\t\t// these,\n\t\t\t\t\t\t\t// temporarily\n\t\ttry {\n\t\t\tconfigManager.setDesiredCameraParameters(theCamera, false);\n\t\t}\n\t\tcatch (RuntimeException re) {\n\t\t\t// Driver failed\n\t\t\tLog.w(TAG,\n\t\t\t\t\t\"Camera rejected parameters. Setting only minimal safe-mode parameters\");\n\t\t\tLog.i(TAG, \"Resetting to saved camera params: \"\n\t\t\t\t\t+ parametersFlattened);\n\t\t\t// Reset:\n\t\t\tif (parametersFlattened != null) {\n\t\t\t\tparameters = theCamera.getParameters();\n\t\t\t\tparameters.unflatten(parametersFlattened);\n\t\t\t\ttry {\n\t\t\t\t\ttheCamera.setParameters(parameters);\n\t\t\t\t\tconfigManager.setDesiredCameraParameters(theCamera, true);\n\t\t\t\t}\n\t\t\t\tcatch (RuntimeException re2) {\n\t\t\t\t\t// Well, darn. Give up\n\t\t\t\t\tLog.w(TAG,\n\t\t\t\t\t\t\t\"Camera rejected even safe-mode parameters! No configuration\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic synchronized boolean isOpen() {\n\t\treturn camera != null;\n\t}\n\n\t/**\n\t * Closes the camera driver if still in use.\n\t */\n\tpublic synchronized void closeDriver() {\n\t\tif (camera != null) {\n\t\t\tcamera.release();\n\t\t\tcamera = null;\n\t\t\t// Make sure to clear these each time we close the camera, so that\n\t\t\t// any scanning rect\n\t\t\t// requested by intent is forgotten.\n\t\t\tframingRect = null;\n\t\t\tframingRectInPreview = null;\n\t\t}\n\t}\n\n\t/**\n\t * Asks the camera hardware to begin drawing preview frames to the screen.\n\t */\n\tpublic synchronized void startPreview() {\n\t\tCamera theCamera = camera;\n\t\tif (theCamera != null && !previewing) {\n\t\t\t// Starts capturing and drawing preview frames to the screen\n\t\t\t// Preview will not actually start until a surface is supplied with\n\t\t\t// setPreviewDisplay(SurfaceHolder) or\n\t\t\t// setPreviewTexture(SurfaceTexture).\n\t\t\ttheCamera.startPreview();\n\n\t\t\tpreviewing = true;\n\t\t\tautoFocusManager = new AutoFocusManager(context, camera);\n\t\t}\n\t}\n\n\t/**\n\t * Tells the camera to stop drawing preview frames.\n\t */\n\tpublic synchronized void stopPreview() {\n\t\tif (autoFocusManager != null) {\n\t\t\tautoFocusManager.stop();\n\t\t\tautoFocusManager = null;\n\t\t}\n\t\tif (camera != null && previewing) {\n\t\t\tcamera.stopPreview();\n\t\t\tpreviewCallback.setHandler(null, 0);\n\t\t\tpreviewing = false;\n\t\t}\n\t}\n\n\t/**\n\t * Convenience method for\n\t * {@link org.madmatrix.zxing.android.CaptureActivity}\n\t */\n\tpublic synchronized void setTorch(boolean newSetting) {\n\t\tif (newSetting != configManager.getTorchState(camera)) {\n\t\t\tif (camera != null) {\n\t\t\t\tif (autoFocusManager != null) {\n\t\t\t\t\tautoFocusManager.stop();\n\t\t\t\t}\n\t\t\t\tconfigManager.setTorch(camera, newSetting);\n\t\t\t\tif (autoFocusManager != null) {\n\t\t\t\t\tautoFocusManager.start();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * A single preview frame will be returned to the handler supplied. The data\n\t * will arrive as byte[] in the message.obj field, with width and height\n\t * encoded as message.arg1 and message.arg2, respectively. <br/>\n\t * \n\t * 两个绑定操作：<br/>\n\t * 1：将handler与回调函数绑定；<br/>\n\t * 2：将相机与回调函数绑定<br/>\n\t * 综上，该函数的作用是当相机的预览界面准备就绪后就会调用hander向其发送传入的message\n\t * \n\t * @param handler\n\t *            The handler to send the message to.\n\t * @param message\n\t *            The what field of the message to be sent.\n\t */\n\tpublic synchronized void requestPreviewFrame(Handler handler, int message) {\n\t\tCamera theCamera = camera;\n\t\tif (theCamera != null && previewing) {\n\t\t\tpreviewCallback.setHandler(handler, message);\n\n\t\t\t// 绑定相机回调函数，当预览界面准备就绪后会回调Camera.PreviewCallback.onPreviewFrame\n\t\t\ttheCamera.setOneShotPreviewCallback(previewCallback);\n\t\t}\n\t}\n\n\t/**\n\t * Calculates the framing rect which the UI should draw to show the user\n\t * where to place the barcode. This target helps with alignment as well as\n\t * forces the user to hold the device far enough away to ensure the image\n\t * will be in focus.\n\t * \n\t * @return The rectangle to draw on screen in window coordinates.\n\t */\n\tpublic synchronized Rect getFramingRect() {\n\t\tif (framingRect == null) {\n\t\t\tif (camera == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tPoint screenResolution = configManager.getScreenResolution();\n\t\t\tif (screenResolution == null) {\n\t\t\t\t// Called early, before init even finished\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tint width = findDesiredDimensionInRange(screenResolution.x,\n\t\t\t\t\tMIN_FRAME_WIDTH, MAX_FRAME_WIDTH);\n\t\t\t// 将扫描框设置成一个正方形\n\t\t\tint height = width;\n\n\t\t\tint leftOffset = (screenResolution.x - width) / 2;\n\t\t\tint topOffset = (screenResolution.y - height) / 2;\n\t\t\tframingRect = new Rect(leftOffset, topOffset, leftOffset + width,\n\t\t\t\t\ttopOffset + height);\n\n\t\t\tLog.d(TAG, \"Calculated framing rect: \" + framingRect);\n\t\t}\n\n\t\treturn framingRect;\n\t}\n\n\t/**\n\t * Target 5/8 of each dimension<br/>\n\t * 计算结果在hardMin~hardMax之间\n\t * \n\t * @param resolution\n\t * @param hardMin\n\t * @param hardMax\n\t * @return\n\t */\n\tprivate static int findDesiredDimensionInRange(int resolution, int hardMin,\n\t\t\tint hardMax) {\n\t\tint dim = 5 * resolution / 8; // Target 5/8 of each dimension\n\t\tif (dim < hardMin) {\n\t\t\treturn hardMin;\n\t\t}\n\t\tif (dim > hardMax) {\n\t\t\treturn hardMax;\n\t\t}\n\t\treturn dim;\n\t}\n\n\t/**\n\t * Like {@link #getFramingRect} but coordinates are in terms of the preview\n\t * frame, not UI / screen.\n\t */\n\tpublic synchronized Rect getFramingRectInPreview() {\n\t\tif (framingRectInPreview == null) {\n\t\t\tRect framingRect = getFramingRect();\n\t\t\tif (framingRect == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tRect rect = new Rect(framingRect);\n\t\t\tPoint cameraResolution = configManager.getCameraResolution();\n\t\t\tPoint screenResolution = configManager.getScreenResolution();\n\t\t\tif (cameraResolution == null || screenResolution == null) {\n\t\t\t\t// Called early, before init even finished\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\trect.left = rect.left * cameraResolution.y / screenResolution.x;\n\t\t\trect.right = rect.right * cameraResolution.y / screenResolution.x;\n\t\t\trect.top = rect.top * cameraResolution.x / screenResolution.y;\n\t\t\trect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;\n\t\t\tframingRectInPreview = rect;\n\n\t\t\tLog.d(TAG, \"Calculated framingRectInPreview rect: \"\n\t\t\t\t\t+ framingRectInPreview);\n\t\t\tLog.d(TAG, \"cameraResolution: \" + cameraResolution);\n\t\t\tLog.d(TAG, \"screenResolution: \" + screenResolution);\n\t\t}\n\n\t\treturn framingRectInPreview;\n\t}\n\n\t/**\n\t * Allows third party apps to specify the scanning rectangle dimensions,\n\t * rather than determine them automatically based on screen resolution.\n\t * \n\t * @param width\n\t *            The width in pixels to scan.\n\t * @param height\n\t *            The height in pixels to scan.\n\t */\n\tpublic synchronized void setManualFramingRect(int width, int height) {\n\t\tif (initialized) {\n\t\t\tPoint screenResolution = configManager.getScreenResolution();\n\t\t\tif (width > screenResolution.x) {\n\t\t\t\twidth = screenResolution.x;\n\t\t\t}\n\t\t\tif (height > screenResolution.y) {\n\t\t\t\theight = screenResolution.y;\n\t\t\t}\n\t\t\tint leftOffset = (screenResolution.x - width) / 2;\n\t\t\tint topOffset = (screenResolution.y - height) / 2;\n\t\t\tframingRect = new Rect(leftOffset, topOffset, leftOffset + width,\n\t\t\t\t\ttopOffset + height);\n\t\t\tLog.d(TAG, \"Calculated manual framing rect: \" + framingRect);\n\t\t\tframingRectInPreview = null;\n\t\t}\n\t\telse {\n\t\t\trequestedFramingRectWidth = width;\n\t\t\trequestedFramingRectHeight = height;\n\t\t}\n\t}\n\n\t/**\n\t * A factory method to build the appropriate LuminanceSource object based on\n\t * the format of the preview buffers, as described by Camera.Parameters.\n\t * \n\t * @param data\n\t *            A preview frame.\n\t * @param width\n\t *            The width of the image.\n\t * @param height\n\t *            The height of the image.\n\t * @return A PlanarYUVLuminanceSource instance.\n\t */\n\tpublic PlanarYUVLuminanceSource buildLuminanceSource(byte[] data,\n\t\t\tint width, int height) {\n\t\tRect rect = getFramingRectInPreview();\n\t\tif (rect == null) {\n\t\t\treturn null;\n\t\t}\n\t\t// Go ahead and assume it's YUV rather than die.\n\t\treturn new PlanarYUVLuminanceSource(data, width, height, rect.left,\n\t\t\t\trect.top, rect.width(), rect.height(), false);\n\t}\n\n\t/**\n\t * 焦点放小\n\t */\n\tpublic void zoomOut() {\n\t\tif (camera != null && camera.getParameters().isZoomSupported()) {\n\n\t\t\tCamera.Parameters parameters = camera.getParameters();\n\t\t\tif (parameters.getZoom() <= 0) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tparameters.setZoom(parameters.getZoom() - 1);\n\t\t\tcamera.setParameters(parameters);\n\n\t\t}\n\t}\n\n\t/**\n\t * 焦点放大\n\t */\n\tpublic void zoomIn() {\n\t\tif (camera != null && camera.getParameters().isZoomSupported()) {\n\n\t\t\tCamera.Parameters parameters = camera.getParameters();\n\t\t\tif (parameters.getZoom() >= parameters.getMaxZoom()) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tparameters.setZoom(parameters.getZoom() + 1);\n\t\t\tcamera.setParameters(parameters);\n\n\t\t}\n\t}\n\n\t/*\n\t * 缩放\n\t * \n\t * @param scale\n\t */\n\tpublic void setCameraZoom(int scale) {\n\t\tif (camera != null && camera.getParameters().isZoomSupported()\n\t\t\t\t&& scale <= camera.getParameters().getMaxZoom() && scale >= 0) {\n\n\t\t\tCamera.Parameters parameters = camera.getParameters();\n\n\t\t\tparameters.setZoom(scale);\n\t\t\tcamera.setParameters(parameters);\n\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/camera/FrontLightMode.java",
    "content": "/*\n * Copyright (C) 2012 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.camera;\n\nimport android.content.SharedPreferences;\nimport cn.hugo.android.scanner.config.Config;\n\n/**\n * Enumerates settings of the prefernce controlling the front light.\n */\npublic enum FrontLightMode {\n\n\t/** Always on. */\n\tON,\n\t/** On only when ambient light is low. */\n\tAUTO,\n\t/** Always off. */\n\tOFF;\n\n\tprivate static FrontLightMode parse(String modeString) {\n\t\treturn modeString == null ? OFF : valueOf(modeString);\n\t}\n\n\tpublic static FrontLightMode readPref(SharedPreferences sharedPrefs) {\n\t\treturn parse(sharedPrefs.getString(\n\t\t\t\tConfig.KEY_FRONT_LIGHT_MODE, null));\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/camera/OpenCameraInterface.java",
    "content": "/*\n * Copyright (C) 2012 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.camera;\n\nimport android.hardware.Camera;\nimport android.util.Log;\n\n/**\n * 该类用于检测手机上摄像头的个数，如果有两个摄像头，则取背面的摄像头\n */\npublic final class OpenCameraInterface {\n\n\tprivate static final String TAG = OpenCameraInterface.class.getName();\n\n\tprivate OpenCameraInterface() {\n\t}\n\n\t/**\n\t * Opens a rear-facing camera with {@link Camera#open(int)}, if one exists,\n\t * or opens camera 0.\n\t */\n\tpublic static Camera open() {\n\n\t\tint numCameras = Camera.getNumberOfCameras();\n\t\tif (numCameras == 0) {\n\t\t\tLog.w(TAG, \"No cameras!\");\n\t\t\treturn null;\n\t\t}\n\n\t\tint index = 0;\n\t\twhile (index < numCameras) {\n\t\t\tCamera.CameraInfo cameraInfo = new Camera.CameraInfo();\n\t\t\tCamera.getCameraInfo(index, cameraInfo);\n\t\t\t// CAMERA_FACING_BACK：手机背面的摄像头\n\t\t\tif (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\n\t\tCamera camera;\n\t\tif (index < numCameras) {\n\t\t\tLog.i(TAG, \"Opening camera #\" + index);\n\t\t\tcamera = Camera.open(index);\n\t\t} else {\n\t\t\tLog.i(TAG, \"No camera facing back; returning camera #0\");\n\t\t\tcamera = Camera.open(0);\n\t\t}\n\n\t\treturn camera;\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/camera/PreviewCallback.java",
    "content": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.camera;\n\nimport android.graphics.Point;\nimport android.hardware.Camera;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.Log;\n\n/**\n * 该类的作用是在预览界面加载好后向ui线程发消息\n */\nfinal class PreviewCallback implements Camera.PreviewCallback {\n\n\tprivate static final String TAG = PreviewCallback.class.getSimpleName();\n\n\tprivate final CameraConfigurationManager configManager;\n\tprivate Handler previewHandler;\n\tprivate int previewMessage;\n\n\tPreviewCallback(CameraConfigurationManager configManager) {\n\t\tthis.configManager = configManager;\n\t}\n\n\t/**\n\t * 绑定handler，用于发消息到ui线程\n\t * \n\t * @param previewHandler\n\t * @param previewMessage\n\t */\n\tvoid setHandler(Handler previewHandler, int previewMessage) {\n\t\tthis.previewHandler = previewHandler;\n\t\tthis.previewMessage = previewMessage;\n\t}\n\n\t@Override\n\tpublic void onPreviewFrame(byte[] data, Camera camera) {\n\t\tPoint cameraResolution = configManager.getCameraResolution();\n\t\tHandler thePreviewHandler = previewHandler;\n\t\tif (cameraResolution != null && thePreviewHandler != null) {\n\t\t\tMessage message = thePreviewHandler.obtainMessage(previewMessage, cameraResolution.x, cameraResolution.y,\n\t\t\t\t\tdata);\n\t\t\tmessage.sendToTarget();\n\t\t\tpreviewHandler = null;\n\t\t} else {\n\t\t\tLog.d(TAG, \"Got preview callback, but no handler or resolution available\");\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/common/BitmapUtils.java",
    "content": "package cn.hugo.android.scanner.common;\n\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\n\npublic class BitmapUtils {\n\n\tpublic static Bitmap decodeSampledBitmapFromResource(Resources res,\n\t\t\tint resId, int reqWidth, int reqHeight) {\n\n\t\t// First decode with inJustDecodeBounds=true to check dimensions\n\t\tfinal BitmapFactory.Options options = new BitmapFactory.Options();\n\t\toptions.inJustDecodeBounds = true;\n\t\tBitmapFactory.decodeResource(res, resId, options);\n\n\t\t// Calculate inSampleSize\n\t\toptions.inSampleSize = calculateInSampleSize(options, reqWidth,\n\t\t\t\treqHeight);\n\n\t\t// Decode bitmap with inSampleSize set\n\t\toptions.inJustDecodeBounds = false;\n\t\treturn BitmapFactory.decodeResource(res, resId, options);\n\t}\n\n\tpublic static int calculateInSampleSize(BitmapFactory.Options options,\n\t\t\tint reqWidth, int reqHeight) {\n\t\t// Raw height and width of image\n\t\tfinal int height = options.outHeight;\n\t\tfinal int width = options.outWidth;\n\t\tint inSampleSize = 1;\n\n\t\tif (height > reqHeight || width > reqWidth) {\n\n\t\t\t// Calculate ratios of height and width to requested height and\n\t\t\t// width\n\t\t\tfinal int heightRatio = Math.round((float) height\n\t\t\t\t\t/ (float) reqHeight);\n\t\t\tfinal int widthRatio = Math.round((float) width / (float) reqWidth);\n\n\t\t\t// Choose the smallest ratio as inSampleSize value, this will\n\t\t\t// guarantee\n\t\t\t// a final image with both dimensions larger than or equal to the\n\t\t\t// requested height and width.\n\t\t\tinSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;\n\t\t}\n\n\t\treturn inSampleSize;\n\t}\n\n\tpublic static Bitmap getCompressedBitmap(String path) {\n\t\tBitmapFactory.Options options = new BitmapFactory.Options();\n\t\toptions.inJustDecodeBounds = true;\n\t\tBitmapFactory.decodeFile(path, options);\n\t\toptions.inSampleSize = calculateInSampleSize(options, 480, 800);\n\t\toptions.inJustDecodeBounds = false;\n\t\treturn BitmapFactory.decodeFile(path, options);\n\t}\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/common/Runnable.java",
    "content": "package cn.hugo.android.scanner.common;\n\nimport android.annotation.SuppressLint;\nimport android.os.AsyncTask;\nimport android.os.Build;\n\n/**\n * 兼容低版本的子线程开启任务\n * \n * @author hugo\n * \n */\npublic class Runnable {\n\n\t@SuppressLint(\"NewApi\")\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static void execAsync(AsyncTask<?, ?, ?> task) {\n\t\tif (Build.VERSION.SDK_INT >= 11) {\n\t\t\ttask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);\n\t\t}\n\t\telse {\n\t\t\ttask.execute();\n\t\t}\n\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/config/Config.java",
    "content": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.config;\n\n/**\n * The main settings activity.\n * \n * @author dswitkin@google.com (Daniel Switkin)\n * @author Sean Owen\n */\npublic final class Config {\n\tpublic static final String KEY_DECODE_1D = \"preferences_decode_1D\";\n\tpublic static final String KEY_DECODE_1D_PRODUCT = \"preferences_decode_1D_product\";\n\tpublic static final String KEY_DECODE_1D_INDUSTRIAL = \"preferences_decode_1D_industrial\";\n\tpublic static final String KEY_DECODE_QR = \"preferences_decode_QR\";\n\tpublic static final String KEY_DECODE_DATA_MATRIX = \"preferences_decode_Data_Matrix\";\n\tpublic static final String KEY_DECODE_AZTEC = \"preferences_decode_Aztec\";\n\tpublic static final String KEY_DECODE_PDF417 = \"preferences_decode_PDF417\";\n\n\tpublic static final String KEY_CUSTOM_PRODUCT_SEARCH = \"preferences_custom_product_search\";\n\n\tpublic static final String KEY_PLAY_BEEP = \"preferences_play_beep\";\n\tpublic static final String KEY_VIBRATE = \"preferences_vibrate\";\n\tpublic static final String KEY_COPY_TO_CLIPBOARD = \"preferences_copy_to_clipboard\";\n\tpublic static final String KEY_FRONT_LIGHT_MODE = \"preferences_front_light_mode\";\n\tpublic static final String KEY_BULK_MODE = \"preferences_bulk_mode\";\n\tpublic static final String KEY_REMEMBER_DUPLICATES = \"preferences_remember_duplicates\";\n\tpublic static final String KEY_SUPPLEMENTAL = \"preferences_supplemental\";\n\tpublic static final String KEY_AUTO_FOCUS = \"preferences_auto_focus\";\n\tpublic static final String KEY_INVERT_SCAN = \"preferences_invert_scan\";\n\tpublic static final String KEY_SEARCH_COUNTRY = \"preferences_search_country\";\n\tpublic static final String KEY_DISABLE_AUTO_ORIENTATION = \"preferences_orientation\";\n\n\tpublic static final String KEY_DISABLE_CONTINUOUS_FOCUS = \"preferences_disable_continuous_focus\";\n\tpublic static final String KEY_DISABLE_EXPOSURE = \"preferences_disable_exposure\";\n\tpublic static final String KEY_DISABLE_METERING = \"preferences_disable_metering\";\n\tpublic static final String KEY_DISABLE_BARCODE_SCENE_MODE = \"preferences_disable_barcode_scene_mode\";\n\tpublic static final String KEY_AUTO_OPEN_WEB = \"preferences_auto_open_web\";\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/decode/BitmapDecoder.java",
    "content": "package cn.hugo.android.scanner.decode;\n\nimport java.util.Hashtable;\nimport java.util.Vector;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\n\nimport com.google.zxing.BarcodeFormat;\nimport com.google.zxing.BinaryBitmap;\nimport com.google.zxing.DecodeHintType;\nimport com.google.zxing.MultiFormatReader;\nimport com.google.zxing.NotFoundException;\nimport com.google.zxing.Result;\nimport com.google.zxing.common.HybridBinarizer;\n\n/**\n * 从bitmap解码\n * \n * @author hugo\n * \n */\npublic class BitmapDecoder {\n\n\tMultiFormatReader multiFormatReader;\n\n\tpublic BitmapDecoder(Context context) {\n\n\t\tmultiFormatReader = new MultiFormatReader();\n\n\t\t// 解码的参数\n\t\tHashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(\n\t\t\t\t2);\n\t\t// 可以解析的编码类型\n\t\tVector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();\n\t\tif (decodeFormats == null || decodeFormats.isEmpty()) {\n\t\t\tdecodeFormats = new Vector<BarcodeFormat>();\n\n\t\t\t// 这里设置可扫描的类型，我这里选择了都支持\n\t\t\tdecodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);\n\t\t\tdecodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);\n\t\t\tdecodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);\n\t\t}\n\t\thints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);\n\n\t\t// 设置继续的字符编码格式为UTF8\n\t\thints.put(DecodeHintType.CHARACTER_SET, \"UTF8\");\n\n\t\t// 设置解析配置参数\n\t\tmultiFormatReader.setHints(hints);\n\n\t}\n\n\t/**\n\t * 获取解码结果\n\t * \n\t * @param bitmap\n\t * @return\n\t */\n\tpublic Result getRawResult(Bitmap bitmap) {\n\t\tif (bitmap == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\treturn multiFormatReader.decodeWithState(new BinaryBitmap(\n\t\t\t\t\tnew HybridBinarizer(new BitmapLuminanceSource(bitmap))));\n\t\t}\n\t\tcatch (NotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn null;\n\t}\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/decode/BitmapLuminanceSource.java",
    "content": "package cn.hugo.android.scanner.decode;\n\nimport android.graphics.Bitmap;\n\nimport com.google.zxing.LuminanceSource;\n\npublic class BitmapLuminanceSource extends LuminanceSource {\n\n\tprivate byte bitmapPixels[];\n\n\tprotected BitmapLuminanceSource(Bitmap bitmap) {\n\t\tsuper(bitmap.getWidth(), bitmap.getHeight());\n\n\t\t// 首先，要取得该图片的像素数组内容\n\t\tint[] data = new int[bitmap.getWidth() * bitmap.getHeight()];\n\t\tthis.bitmapPixels = new byte[bitmap.getWidth() * bitmap.getHeight()];\n\t\tbitmap.getPixels(data, 0, getWidth(), 0, 0, getWidth(), getHeight());\n\n\t\t// 将int数组转换为byte数组，也就是取像素值中蓝色值部分作为辨析内容\n\t\tfor (int i = 0; i < data.length; i++) {\n\t\t\tthis.bitmapPixels[i] = (byte) data[i];\n\t\t}\n\t}\n\n\t@Override\n\tpublic byte[] getMatrix() {\n\t\t// 返回我们生成好的像素数据\n\t\treturn bitmapPixels;\n\t}\n\n\t@Override\n\tpublic byte[] getRow(int y, byte[] row) {\n\t\t// 这里要得到指定行的像素数据\n\t\tSystem.arraycopy(bitmapPixels, y * getWidth(), row, 0, getWidth());\n\t\treturn row;\n\t}\n}"
  },
  {
    "path": "src/cn/hugo/android/scanner/decode/CaptureActivityHandler.java",
    "content": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.decode;\n\nimport java.util.Collection;\nimport java.util.Map;\n\nimport android.app.Activity;\nimport android.content.ActivityNotFoundException;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.pm.ResolveInfo;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.provider.Browser;\nimport android.util.Log;\nimport cn.hugo.android.scanner.CaptureActivity;\nimport cn.hugo.android.scanner.R;\nimport cn.hugo.android.scanner.camera.CameraManager;\nimport cn.hugo.android.scanner.view.ViewfinderResultPointCallback;\n\nimport com.google.zxing.BarcodeFormat;\nimport com.google.zxing.DecodeHintType;\nimport com.google.zxing.Result;\n\n/**\n * This class handles all the messaging which comprises the state machine for\n * capture.\n * \n * @author dswitkin@google.com (Daniel Switkin)\n */\npublic final class CaptureActivityHandler extends Handler {\n\n\tprivate static final String TAG = CaptureActivityHandler.class\n\t\t\t.getSimpleName();\n\n\tprivate final CaptureActivity activity;\n\n\t/**\n\t * 真正负责扫描任务的核心线程\n\t */\n\tprivate final DecodeThread decodeThread;\n\n\tprivate State state;\n\n\tprivate final CameraManager cameraManager;\n\n\t/**\n\t * 当前扫描的状态\n\t */\n\tprivate enum State {\n\t\t/**\n\t\t * 预览\n\t\t */\n\t\tPREVIEW,\n\t\t/**\n\t\t * 扫描成功\n\t\t */\n\t\tSUCCESS,\n\t\t/**\n\t\t * 结束扫描\n\t\t */\n\t\tDONE\n\t}\n\n\tpublic CaptureActivityHandler(CaptureActivity activity,\n\t\t\tCollection<BarcodeFormat> decodeFormats,\n\t\t\tMap<DecodeHintType, ?> baseHints, String characterSet,\n\t\t\tCameraManager cameraManager) {\n\t\tthis.activity = activity;\n\n\t\t// 启动扫描线程\n\t\tdecodeThread = new DecodeThread(activity, decodeFormats, baseHints,\n\t\t\t\tcharacterSet, new ViewfinderResultPointCallback(\n\t\t\t\t\t\tactivity.getViewfinderView()));\n\t\tdecodeThread.start();\n\n\t\tstate = State.SUCCESS;\n\n\t\t// Start ourselves capturing previews and decoding.\n\t\tthis.cameraManager = cameraManager;\n\n\t\t// 开启相机预览界面\n\t\tcameraManager.startPreview();\n\n\t\trestartPreviewAndDecode();\n\t}\n\n\t@Override\n\tpublic void handleMessage(Message message) {\n\t\tswitch (message.what) {\n\t\t\tcase R.id.restart_preview: // 准备进行下一次扫描\n\t\t\t\tLog.d(TAG, \"Got restart preview message\");\n\t\t\t\trestartPreviewAndDecode();\n\t\t\t\tbreak;\n\t\t\tcase R.id.decode_succeeded:\n\t\t\t\tLog.d(TAG, \"Got decode succeeded message\");\n\t\t\t\tstate = State.SUCCESS;\n\t\t\t\tBundle bundle = message.getData();\n\t\t\t\tBitmap barcode = null;\n\t\t\t\tfloat scaleFactor = 1.0f;\n\t\t\t\tif (bundle != null) {\n\t\t\t\t\tbyte[] compressedBitmap = bundle\n\t\t\t\t\t\t\t.getByteArray(DecodeThread.BARCODE_BITMAP);\n\t\t\t\t\tif (compressedBitmap != null) {\n\t\t\t\t\t\tbarcode = BitmapFactory.decodeByteArray(\n\t\t\t\t\t\t\t\tcompressedBitmap, 0, compressedBitmap.length,\n\t\t\t\t\t\t\t\tnull);\n\t\t\t\t\t\t// Mutable copy:\n\t\t\t\t\t\tbarcode = barcode.copy(Bitmap.Config.ARGB_8888, true);\n\t\t\t\t\t}\n\t\t\t\t\tscaleFactor = bundle\n\t\t\t\t\t\t\t.getFloat(DecodeThread.BARCODE_SCALED_FACTOR);\n\t\t\t\t}\n\t\t\t\tactivity.handleDecode((Result) message.obj, barcode,\n\t\t\t\t\t\tscaleFactor);\n\t\t\t\tbreak;\n\t\t\tcase R.id.decode_failed:\n\t\t\t\t// We're decoding as fast as possible, so when one decode fails,\n\t\t\t\t// start another.\n\t\t\t\tstate = State.PREVIEW;\n\t\t\t\tcameraManager.requestPreviewFrame(decodeThread.getHandler(),\n\t\t\t\t\t\tR.id.decode);\n\t\t\t\tbreak;\n\t\t\tcase R.id.return_scan_result:\n\t\t\t\tLog.d(TAG, \"Got return scan result message\");\n\t\t\t\tactivity.setResult(Activity.RESULT_OK, (Intent) message.obj);\n\t\t\t\tactivity.finish();\n\t\t\t\tbreak;\n\t\t\tcase R.id.launch_product_query:\n\t\t\t\tLog.d(TAG, \"Got product query message\");\n\t\t\t\tString url = (String) message.obj;\n\n\t\t\t\tIntent intent = new Intent(Intent.ACTION_VIEW);\n\t\t\t\tintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);\n\t\t\t\tintent.setData(Uri.parse(url));\n\n\t\t\t\t/**\n\t\t\t\t * 这段代码是zxing项目组想要用chrome打开浏览器浏览url\n\t\t\t\t */\n\t\t\t\tResolveInfo resolveInfo = activity.getPackageManager()\n\t\t\t\t\t\t.resolveActivity(intent,\n\t\t\t\t\t\t\t\tPackageManager.MATCH_DEFAULT_ONLY);\n\t\t\t\tString browserPackageName = null;\n\t\t\t\tif (resolveInfo != null && resolveInfo.activityInfo != null) {\n\t\t\t\t\tbrowserPackageName = resolveInfo.activityInfo.packageName;\n\t\t\t\t\tLog.d(TAG, \"Using browser in package \" + browserPackageName);\n\t\t\t\t}\n\n\t\t\t\t// Needed for default Android browser / Chrome only apparently\n\t\t\t\tif (\"com.android.browser\".equals(browserPackageName)\n\t\t\t\t\t\t|| \"com.android.chrome\".equals(browserPackageName)) {\n\t\t\t\t\tintent.setPackage(browserPackageName);\n\t\t\t\t\tintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t\t\t\t\tintent.putExtra(Browser.EXTRA_APPLICATION_ID,\n\t\t\t\t\t\t\tbrowserPackageName);\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tactivity.startActivity(intent);\n\t\t\t\t}\n\t\t\t\tcatch (ActivityNotFoundException ignored) {\n\t\t\t\t\tLog.w(TAG, \"Can't find anything to handle VIEW of URI \"\n\t\t\t\t\t\t\t+ url);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tpublic void quitSynchronously() {\n\t\tstate = State.DONE;\n\t\tcameraManager.stopPreview();\n\t\tMessage quit = Message.obtain(decodeThread.getHandler(), R.id.quit);\n\t\tquit.sendToTarget();\n\n\t\ttry {\n\t\t\t// Wait at most half a second; should be enough time, and onPause()\n\t\t\t// will timeout quickly\n\t\t\tdecodeThread.join(500L);\n\t\t}\n\t\tcatch (InterruptedException e) {\n\t\t\t// continue\n\t\t}\n\n\t\t// Be absolutely sure we don't send any queued up messages\n\t\tremoveMessages(R.id.decode_succeeded);\n\t\tremoveMessages(R.id.decode_failed);\n\t}\n\n\t/**\n\t * 完成一次扫描后，只需要再调用此方法即可\n\t */\n\tprivate void restartPreviewAndDecode() {\n\t\tif (state == State.SUCCESS) {\n\t\t\tstate = State.PREVIEW;\n\n\t\t\t// 向decodeThread绑定的handler（DecodeHandler)发送解码消息\n\t\t\tcameraManager.requestPreviewFrame(decodeThread.getHandler(),\n\t\t\t\t\tR.id.decode);\n\t\t\tactivity.drawViewfinder();\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/decode/DecodeFormatManager.java",
    "content": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.decode;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.regex.Pattern;\n\nimport android.content.Intent;\nimport android.net.Uri;\nimport cn.hugo.android.scanner.Intents;\n\nimport com.google.zxing.BarcodeFormat;\n\nfinal class DecodeFormatManager {\n\n\tprivate static final Pattern COMMA_PATTERN = Pattern.compile(\",\");\n\n\tstatic final Collection<BarcodeFormat> PRODUCT_FORMATS;\n\tstatic final Collection<BarcodeFormat> ONE_D_FORMATS;\n\tstatic final Collection<BarcodeFormat> QR_CODE_FORMATS = EnumSet\n\t\t\t.of(BarcodeFormat.QR_CODE);\n\tstatic final Collection<BarcodeFormat> DATA_MATRIX_FORMATS = EnumSet\n\t\t\t.of(BarcodeFormat.DATA_MATRIX);\n\tstatic {\n\t\tPRODUCT_FORMATS = EnumSet.of(BarcodeFormat.UPC_A, BarcodeFormat.UPC_E,\n\t\t\t\tBarcodeFormat.EAN_13, BarcodeFormat.EAN_8,\n\t\t\t\tBarcodeFormat.RSS_14, BarcodeFormat.RSS_EXPANDED);\n\t\tONE_D_FORMATS = EnumSet.of(BarcodeFormat.CODE_39,\n\t\t\t\tBarcodeFormat.CODE_93, BarcodeFormat.CODE_128,\n\t\t\t\tBarcodeFormat.ITF, BarcodeFormat.CODABAR);\n\t\tONE_D_FORMATS.addAll(PRODUCT_FORMATS);\n\t}\n\n\tprivate DecodeFormatManager() {\n\t}\n\n\tstatic Collection<BarcodeFormat> parseDecodeFormats(Intent intent) {\n\t\tIterable<String> scanFormats = null;\n\t\tCharSequence scanFormatsString = intent\n\t\t\t\t.getStringExtra(Intents.Scan.FORMATS);\n\t\tif (scanFormatsString != null) {\n\t\t\tscanFormats = Arrays.asList(COMMA_PATTERN.split(scanFormatsString));\n\t\t}\n\t\treturn parseDecodeFormats(scanFormats,\n\t\t\t\tintent.getStringExtra(Intents.Scan.MODE));\n\t}\n\n\tstatic Collection<BarcodeFormat> parseDecodeFormats(Uri inputUri) {\n\t\tList<String> formats = inputUri\n\t\t\t\t.getQueryParameters(Intents.Scan.FORMATS);\n\t\tif (formats != null && formats.size() == 1 && formats.get(0) != null) {\n\t\t\tformats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));\n\t\t}\n\t\treturn parseDecodeFormats(formats,\n\t\t\t\tinputUri.getQueryParameter(Intents.Scan.MODE));\n\t}\n\n\tprivate static Collection<BarcodeFormat> parseDecodeFormats(\n\t\t\tIterable<String> scanFormats, String decodeMode) {\n\t\tif (scanFormats != null) {\n\t\t\tCollection<BarcodeFormat> formats = EnumSet\n\t\t\t\t\t.noneOf(BarcodeFormat.class);\n\t\t\ttry {\n\t\t\t\tfor (String format : scanFormats) {\n\t\t\t\t\tformats.add(BarcodeFormat.valueOf(format));\n\t\t\t\t}\n\t\t\t\treturn formats;\n\t\t\t}\n\t\t\tcatch (IllegalArgumentException iae) {\n\t\t\t\t// ignore it then\n\t\t\t}\n\t\t}\n\t\tif (decodeMode != null) {\n\t\t\tif (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {\n\t\t\t\treturn PRODUCT_FORMATS;\n\t\t\t}\n\t\t\tif (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {\n\t\t\t\treturn QR_CODE_FORMATS;\n\t\t\t}\n\t\t\tif (Intents.Scan.DATA_MATRIX_MODE.equals(decodeMode)) {\n\t\t\t\treturn DATA_MATRIX_FORMATS;\n\t\t\t}\n\t\t\tif (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {\n\t\t\t\treturn ONE_D_FORMATS;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/decode/DecodeHandler.java",
    "content": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.decode;\n\nimport java.io.ByteArrayOutputStream;\nimport java.util.Map;\n\nimport android.graphics.Bitmap;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport android.util.Log;\nimport cn.hugo.android.scanner.CaptureActivity;\nimport cn.hugo.android.scanner.R;\n\nimport com.google.zxing.BinaryBitmap;\nimport com.google.zxing.DecodeHintType;\nimport com.google.zxing.MultiFormatReader;\nimport com.google.zxing.PlanarYUVLuminanceSource;\nimport com.google.zxing.ReaderException;\nimport com.google.zxing.Result;\nimport com.google.zxing.common.HybridBinarizer;\n\nfinal class DecodeHandler extends Handler {\n\n\tprivate static final String TAG = DecodeHandler.class.getSimpleName();\n\n\tprivate final CaptureActivity activity;\n\n\tprivate final MultiFormatReader multiFormatReader;\n\n\tprivate boolean running = true;\n\n\tDecodeHandler(CaptureActivity activity, Map<DecodeHintType, Object> hints) {\n\t\tmultiFormatReader = new MultiFormatReader();\n\t\tmultiFormatReader.setHints(hints);\n\t\tthis.activity = activity;\n\t}\n\n\t@Override\n\tpublic void handleMessage(Message message) {\n\t\tif (!running) {\n\t\t\treturn;\n\t\t}\n\t\tswitch (message.what) {\n\t\t\tcase R.id.decode:\n\t\t\t\tdecode((byte[]) message.obj, message.arg1, message.arg2);\n\t\t\t\tbreak;\n\t\t\tcase R.id.quit:\n\t\t\t\trunning = false;\n\t\t\t\tLooper.myLooper().quit();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/**\n\t * Decode the data within the viewfinder rectangle, and time how long it\n\t * took. For efficiency, reuse the same reader objects from one decode to\n\t * the next.\n\t * \n\t * @param data\n\t *            The YUV preview frame.\n\t * @param width\n\t *            The width of the preview frame.\n\t * @param height\n\t *            The height of the preview frame.\n\t */\n\tprivate void decode(byte[] data, int width, int height) {\n\t\tlong start = System.currentTimeMillis();\n\t\tResult rawResult = null;\n\n\t\tbyte[] rotatedData = new byte[data.length];\n\t\tfor (int y = 0; y < height; y++) {\n\t\t\tfor (int x = 0; x < width; x++)\n\t\t\t\trotatedData[x * height + height - y - 1] = data[x + y * width];\n\t\t}\n\t\tint tmp = width;\n\t\twidth = height;\n\t\theight = tmp;\n\n\t\tPlanarYUVLuminanceSource source = activity.getCameraManager()\n\t\t\t\t.buildLuminanceSource(rotatedData, width, height);\n\t\tif (source != null) {\n\t\t\tBinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));\n\t\t\ttry {\n\t\t\t\t// 预览界面最终取到的是个bitmap，然后对其进行解码\n\t\t\t\trawResult = multiFormatReader.decodeWithState(bitmap);\n\t\t\t}\n\t\t\tcatch (ReaderException re) {\n\t\t\t\t// continue\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tmultiFormatReader.reset();\n\t\t\t}\n\t\t}\n\n\t\tHandler handler = activity.getHandler();\n\t\tif (rawResult != null) {\n\t\t\t// Don't log the barcode contents for security.\n\t\t\tlong end = System.currentTimeMillis();\n\t\t\tLog.d(TAG, \"Found barcode in \" + (end - start) + \" ms\");\n\t\t\tif (handler != null) {\n\t\t\t\tMessage message = Message.obtain(handler,\n\t\t\t\t\t\tR.id.decode_succeeded, rawResult);\n\t\t\t\tBundle bundle = new Bundle();\n\t\t\t\tbundleThumbnail(source, bundle);\n\t\t\t\tmessage.setData(bundle);\n\t\t\t\tmessage.sendToTarget();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (handler != null) {\n\t\t\t\tMessage message = Message.obtain(handler, R.id.decode_failed);\n\t\t\t\tmessage.sendToTarget();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void bundleThumbnail(PlanarYUVLuminanceSource source,\n\t\t\tBundle bundle) {\n\t\tint[] pixels = source.renderThumbnail();\n\t\tint width = source.getThumbnailWidth();\n\t\tint height = source.getThumbnailHeight();\n\t\tBitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height,\n\t\t\t\tBitmap.Config.ARGB_8888);\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\tbitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);\n\t\tbundle.putByteArray(DecodeThread.BARCODE_BITMAP, out.toByteArray());\n\t\tbundle.putFloat(DecodeThread.BARCODE_SCALED_FACTOR, (float) width\n\t\t\t\t/ source.getWidth());\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/decode/DecodeThread.java",
    "content": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.decode;\n\nimport java.util.Collection;\nimport java.util.EnumMap;\nimport java.util.EnumSet;\nimport java.util.Map;\nimport java.util.concurrent.CountDownLatch;\n\nimport android.content.SharedPreferences;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport cn.hugo.android.scanner.CaptureActivity;\nimport cn.hugo.android.scanner.config.Config;\n\nimport com.google.zxing.BarcodeFormat;\nimport com.google.zxing.DecodeHintType;\nimport com.google.zxing.ResultPointCallback;\n\n/**\n * This thread does all the heavy lifting of decoding the images.\n * \n * @author dswitkin@google.com (Daniel Switkin)\n */\nfinal class DecodeThread extends Thread {\n\n\tpublic static final String BARCODE_BITMAP = \"barcode_bitmap\";\n\n\tpublic static final String BARCODE_SCALED_FACTOR = \"barcode_scaled_factor\";\n\n\tprivate final CaptureActivity activity;\n\n\tprivate final Map<DecodeHintType, Object> hints;\n\n\tprivate Handler handler;\n\n\tprivate final CountDownLatch handlerInitLatch;\n\n\tDecodeThread(CaptureActivity activity,\n\t\t\tCollection<BarcodeFormat> decodeFormats,\n\t\t\tMap<DecodeHintType, ?> baseHints, String characterSet,\n\t\t\tResultPointCallback resultPointCallback) {\n\n\t\tthis.activity = activity;\n\t\thandlerInitLatch = new CountDownLatch(1);\n\n\t\thints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);\n\t\tif (baseHints != null) {\n\t\t\thints.putAll(baseHints);\n\t\t}\n\n\t\t// The prefs can't change while the thread is running, so pick them up\n\t\t// once here.\n\t\tif (decodeFormats == null || decodeFormats.isEmpty()) {\n\t\t\tSharedPreferences prefs = PreferenceManager\n\t\t\t\t\t.getDefaultSharedPreferences(activity);\n\t\t\tdecodeFormats = EnumSet.noneOf(BarcodeFormat.class);\n\t\t\tif (prefs.getBoolean(Config.KEY_DECODE_1D, false)) {\n\t\t\t\tdecodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);\n\t\t\t}\n\t\t\tif (prefs.getBoolean(Config.KEY_DECODE_QR, false)) {\n\t\t\t\tdecodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);\n\t\t\t}\n\t\t\tif (prefs.getBoolean(Config.KEY_DECODE_DATA_MATRIX,\n\t\t\t\t\tfalse)) {\n\t\t\t\tdecodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);\n\t\t\t}\n\t\t}\n\t\thints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);\n\n\t\tif (characterSet != null) {\n\t\t\thints.put(DecodeHintType.CHARACTER_SET, characterSet);\n\t\t}\n\t\thints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK,\n\t\t\t\tresultPointCallback);\n\t\tLog.i(\"DecodeThread\", \"Hints: \" + hints);\n\t}\n\n\tHandler getHandler() {\n\t\ttry {\n\t\t\thandlerInitLatch.await();\n\t\t}\n\t\tcatch (InterruptedException ie) {\n\t\t\t// continue?\n\t\t}\n\t\treturn handler;\n\t}\n\n\t@Override\n\tpublic void run() {\n\t\tLooper.prepare();\n\t\thandler = new DecodeHandler(activity, hints);\n\t\thandlerInitLatch.countDown();\n\t\tLooper.loop();\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/view/ViewfinderResultPointCallback.java",
    "content": "/*\n * Copyright (C) 2009 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cn.hugo.android.scanner.view;\n\nimport com.google.zxing.ResultPoint;\nimport com.google.zxing.ResultPointCallback;\n\npublic final class ViewfinderResultPointCallback implements ResultPointCallback {\n\n\tprivate final ViewfinderView viewfinderView;\n\n\tpublic ViewfinderResultPointCallback(ViewfinderView viewfinderView) {\n\t\tthis.viewfinderView = viewfinderView;\n\t}\n\n\t@Override\n\tpublic void foundPossibleResultPoint(ResultPoint point) {\n\t\tviewfinderView.addPossibleResultPoint(point);\n\t}\n\n}\n"
  },
  {
    "path": "src/cn/hugo/android/scanner/view/ViewfinderView.java",
    "content": "package cn.hugo.android.scanner.view;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Rect;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.util.AttributeSet;\nimport android.view.View;\nimport cn.hugo.android.scanner.R;\nimport cn.hugo.android.scanner.camera.CameraManager;\n\nimport com.google.zxing.ResultPoint;\n\n/**\n * This view is overlaid on top of the camera preview. It adds the viewfinder\n * rectangle and partial transparency outside it, as well as the laser scanner\n * animation and result points.\n * \n * <br/>\n * <br/>\n * 该视图是覆盖在相机的预览视图之上的一层视图。扫描区构成原理，其实是在预览视图上画四块遮罩层，\n * 中间留下的部分保持透明，并画上一条激光线，实际上该线条就是展示而已，与扫描功能没有任何关系。\n * \n * @author dswitkin@google.com (Daniel Switkin)\n */\npublic final class ViewfinderView extends View {\n\n\t/**\n\t * 刷新界面的时间\n\t */\n\tprivate static final long ANIMATION_DELAY = 10L;\n\tprivate static final int OPAQUE = 0xFF;\n\n\tprivate int CORNER_PADDING;\n\n\t/**\n\t * 扫描框中的中间线的宽度\n\t */\n\tprivate static int MIDDLE_LINE_WIDTH;\n\n\t/**\n\t * 扫描框中的中间线的与扫描框左右的间隙\n\t */\n\tprivate static int MIDDLE_LINE_PADDING;\n\n\t/**\n\t * 中间那条线每次刷新移动的距离\n\t */\n\tprivate static final int SPEEN_DISTANCE = 10;\n\n\t/**\n\t * 画笔对象的引用\n\t */\n\tprivate Paint paint;\n\n\t/**\n\t * 中间滑动线的最顶端位置\n\t */\n\tprivate int slideTop;\n\n\t/**\n\t * 中间滑动线的最底端位置\n\t */\n\tprivate int slideBottom;\n\n\tprivate static final int MAX_RESULT_POINTS = 20;\n\n\tprivate Bitmap resultBitmap;\n\n\t/**\n\t * 遮掩层的颜色\n\t */\n\tprivate final int maskColor;\n\tprivate final int resultColor;\n\n\tprivate final int resultPointColor;\n\tprivate List<ResultPoint> possibleResultPoints;\n\n\tprivate List<ResultPoint> lastPossibleResultPoints;\n\n\t/**\n\t * 第一次绘制控件\n\t */\n\tboolean isFirst = true;\n\n\tprivate CameraManager cameraManager;\n\n\t// This constructor is used when the class is built from an XML resource.\n\tpublic ViewfinderView(Context context, AttributeSet attrs) {\n\t\tsuper(context, attrs);\n\n\t\tCORNER_PADDING = dip2px(context, 0.0F);\n\t\tMIDDLE_LINE_PADDING = dip2px(context, 20.0F);\n\t\tMIDDLE_LINE_WIDTH = dip2px(context, 3.0F);\n\n\t\tpaint = new Paint(Paint.ANTI_ALIAS_FLAG); // 开启反锯齿\n\n\t\tResources resources = getResources();\n\t\tmaskColor = resources.getColor(R.color.viewfinder_mask); // 遮掩层颜色\n\t\tresultColor = resources.getColor(R.color.result_view);\n\n\t\tresultPointColor = resources.getColor(R.color.possible_result_points);\n\t\tpossibleResultPoints = new ArrayList<ResultPoint>(5);\n\t\tlastPossibleResultPoints = null;\n\n\t}\n\n\tpublic void setCameraManager(CameraManager cameraManager) {\n\t\tthis.cameraManager = cameraManager;\n\t}\n\n\t@Override\n\tpublic void onDraw(Canvas canvas) {\n\t\tif (cameraManager == null) {\n\t\t\treturn; // not ready yet, early draw before done configuring\n\t\t}\n\t\tRect frame = cameraManager.getFramingRect();\n\t\tif (frame == null) {\n\t\t\treturn;\n\t\t}\n\n\t\t// 绘制遮掩层\n\t\tdrawCover(canvas, frame);\n\n\t\tif (resultBitmap != null) { // 绘制扫描结果的图\n\t\t\t// Draw the opaque result bitmap over the scanning rectangle\n\t\t\tpaint.setAlpha(0xA0);\n\t\t\tcanvas.drawBitmap(resultBitmap, null, frame, paint);\n\t\t}\n\t\telse {\n\n\t\t\t// 画扫描框边上的角\n\t\t\tdrawRectEdges(canvas, frame);\n\n\t\t\t// 绘制扫描线\n\t\t\tdrawScanningLine(canvas, frame);\n\n\t\t\tList<ResultPoint> currentPossible = possibleResultPoints;\n\t\t\tCollection<ResultPoint> currentLast = lastPossibleResultPoints;\n\t\t\tif (currentPossible.isEmpty()) {\n\t\t\t\tlastPossibleResultPoints = null;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpossibleResultPoints = new ArrayList<ResultPoint>(5);\n\t\t\t\tlastPossibleResultPoints = currentPossible;\n\t\t\t\tpaint.setAlpha(OPAQUE);\n\t\t\t\tpaint.setColor(resultPointColor);\n\t\t\t\tfor (ResultPoint point : currentPossible) {\n\t\t\t\t\tcanvas.drawCircle(frame.left + point.getX(), frame.top\n\t\t\t\t\t\t\t+ point.getY(), 6.0f, paint);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (currentLast != null) {\n\t\t\t\tpaint.setAlpha(OPAQUE / 2);\n\t\t\t\tpaint.setColor(resultPointColor);\n\t\t\t\tfor (ResultPoint point : currentLast) {\n\t\t\t\t\tcanvas.drawCircle(frame.left + point.getX(), frame.top\n\t\t\t\t\t\t\t+ point.getY(), 3.0f, paint);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 只刷新扫描框的内容，其他地方不刷新\n\t\t\tpostInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,\n\t\t\t\t\tframe.right, frame.bottom);\n\n\t\t}\n\t}\n\n\t/**\n\t * 绘制扫描线\n\t * \n\t * @param canvas\n\t * @param frame\n\t *            扫描框\n\t */\n\tprivate void drawScanningLine(Canvas canvas, Rect frame) {\n\n\t\t// 初始化中间线滑动的最上边和最下边\n\t\tif (isFirst) {\n\t\t\tisFirst = false;\n\t\t\tslideTop = frame.top;\n\t\t\tslideBottom = frame.bottom;\n\t\t}\n\n\t\t// 绘制中间的线,每次刷新界面，中间的线往下移动SPEEN_DISTANCE\n\t\tslideTop += SPEEN_DISTANCE;\n\t\tif (slideTop >= slideBottom) {\n\t\t\tslideTop = frame.top;\n\t\t}\n\n\t\t// 从图片资源画扫描线\n\t\tRect lineRect = new Rect();\n\t\tlineRect.left = frame.left + MIDDLE_LINE_PADDING;\n\t\tlineRect.right = frame.right - MIDDLE_LINE_PADDING;\n\t\tlineRect.top = slideTop;\n\t\tlineRect.bottom = (slideTop + MIDDLE_LINE_WIDTH);\n\t\tcanvas.drawBitmap(((BitmapDrawable) (BitmapDrawable) getResources()\n\t\t\t\t.getDrawable(R.drawable.scan_laser)).getBitmap(), null,\n\t\t\t\tlineRect, paint);\n\n\t}\n\n\t/**\n\t * 绘制遮掩层\n\t * \n\t * @param canvas\n\t * @param frame\n\t */\n\tprivate void drawCover(Canvas canvas, Rect frame) {\n\n\t\t// 获取屏幕的宽和高\n\t\tint width = canvas.getWidth();\n\t\tint height = canvas.getHeight();\n\n\t\t// Draw the exterior (i.e. outside the framing rect) darkened\n\t\tpaint.setColor(resultBitmap != null ? resultColor : maskColor);\n\n\t\t// 画出扫描框外面的阴影部分，共四个部分，扫描框的上面到屏幕上面，扫描框的下面到屏幕下面\n\t\t// 扫描框的左边面到屏幕左边，扫描框的右边到屏幕右边\n\t\tcanvas.drawRect(0, 0, width, frame.top, paint);\n\t\tcanvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);\n\t\tcanvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1,\n\t\t\t\tpaint);\n\t\tcanvas.drawRect(0, frame.bottom + 1, width, height, paint);\n\t}\n\n\t/**\n\t * 描绘方形的四个角\n\t * \n\t * @param canvas\n\t * @param frame\n\t */\n\tprivate void drawRectEdges(Canvas canvas, Rect frame) {\n\n\t\tpaint.setColor(Color.WHITE);\n\t\tpaint.setAlpha(OPAQUE);\n\n\t\tResources resources = getResources();\n\t\t/**\n\t\t * 这些资源可以用缓存进行管理，不需要每次刷新都新建\n\t\t */\n\t\tBitmap bitmapCornerTopleft = BitmapFactory.decodeResource(resources,\n\t\t\t\tR.drawable.scan_corner_top_left);\n\t\tBitmap bitmapCornerTopright = BitmapFactory.decodeResource(resources,\n\t\t\t\tR.drawable.scan_corner_top_right);\n\t\tBitmap bitmapCornerBottomLeft = BitmapFactory.decodeResource(resources,\n\t\t\t\tR.drawable.scan_corner_bottom_left);\n\t\tBitmap bitmapCornerBottomRight = BitmapFactory.decodeResource(\n\t\t\t\tresources, R.drawable.scan_corner_bottom_right);\n\n\t\tcanvas.drawBitmap(bitmapCornerTopleft, frame.left + CORNER_PADDING,\n\t\t\t\tframe.top + CORNER_PADDING, paint);\n\t\tcanvas.drawBitmap(bitmapCornerTopright, frame.right - CORNER_PADDING\n\t\t\t\t- bitmapCornerTopright.getWidth(), frame.top + CORNER_PADDING,\n\t\t\t\tpaint);\n\t\tcanvas.drawBitmap(bitmapCornerBottomLeft, frame.left + CORNER_PADDING,\n\t\t\t\t2 + (frame.bottom - CORNER_PADDING - bitmapCornerBottomLeft\n\t\t\t\t\t\t.getHeight()), paint);\n\t\tcanvas.drawBitmap(bitmapCornerBottomRight, frame.right - CORNER_PADDING\n\t\t\t\t- bitmapCornerBottomRight.getWidth(), 2 + (frame.bottom\n\t\t\t\t- CORNER_PADDING - bitmapCornerBottomRight.getHeight()), paint);\n\n\t\tbitmapCornerTopleft.recycle();\n\t\tbitmapCornerTopleft = null;\n\t\tbitmapCornerTopright.recycle();\n\t\tbitmapCornerTopright = null;\n\t\tbitmapCornerBottomLeft.recycle();\n\t\tbitmapCornerBottomLeft = null;\n\t\tbitmapCornerBottomRight.recycle();\n\t\tbitmapCornerBottomRight = null;\n\n\t}\n\n\tpublic void drawViewfinder() {\n\t\tBitmap resultBitmap = this.resultBitmap;\n\t\tthis.resultBitmap = null;\n\t\tif (resultBitmap != null) {\n\t\t\tresultBitmap.recycle();\n\t\t}\n\t\tinvalidate();\n\t}\n\n\t/**\n\t * Draw a bitmap with the result points highlighted instead of the live\n\t * scanning display.\n\t * \n\t * @param barcode\n\t *            An image of the decoded barcode.\n\t */\n\tpublic void drawResultBitmap(Bitmap barcode) {\n\t\tresultBitmap = barcode;\n\t\tinvalidate();\n\t}\n\n\tpublic void addPossibleResultPoint(ResultPoint point) {\n\t\tList<ResultPoint> points = possibleResultPoints;\n\t\tsynchronized (points) {\n\t\t\tpoints.add(point);\n\t\t\tint size = points.size();\n\t\t\tif (size > MAX_RESULT_POINTS) {\n\t\t\t\t// trim it\n\t\t\t\tpoints.subList(0, size - MAX_RESULT_POINTS / 2).clear();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * dp转px\n\t * \n\t * @param context\n\t * @param dipValue\n\t * @return\n\t */\n\tpublic int dip2px(Context context, float dipValue) {\n\t\tfinal float scale = context.getResources().getDisplayMetrics().density;\n\t\treturn (int) (dipValue * scale + 0.5f);\n\t}\n\n}\n"
  }
]