Repository: ThinWonton/BarcodeScanner
Branch: master
Commit: f8c7ee1a6b55
Files: 50
Total size: 125.8 KB
Directory structure:
gitextract_xyz60noi/
├── .classpath
├── .gitignore
├── .project
├── AndroidManifest.xml
├── LICENSE
├── README.md
├── doc/
│ └── readme.txt
├── libs/
│ ├── android-core-3.1.1-SNAPSHOT.jar
│ ├── android-support-v4.jar
│ └── core-3.1.1-SNAPSHOT.jar
├── lint.xml
├── proguard-project.txt
├── project.properties
├── res/
│ ├── drawable/
│ │ ├── scan_flashlight.xml
│ │ ├── scan_history.xml
│ │ ├── scan_photo.xml
│ │ ├── seekbar_bg.xml
│ │ └── seekbar_style.xml
│ ├── layout/
│ │ └── capture.xml
│ ├── raw/
│ │ └── beep.ogg
│ ├── values/
│ │ ├── colors.xml
│ │ ├── ids.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ ├── values-v11/
│ │ └── styles.xml
│ └── values-v14/
│ └── styles.xml
└── src/
└── cn/
└── hugo/
└── android/
└── scanner/
├── AmbientLightManager.java
├── BeepManager.java
├── CaptureActivity.java
├── FinishListener.java
├── InactivityTimer.java
├── IntentSource.java
├── Intents.java
├── camera/
│ ├── AutoFocusManager.java
│ ├── CameraConfigurationManager.java
│ ├── CameraManager.java
│ ├── FrontLightMode.java
│ ├── OpenCameraInterface.java
│ └── PreviewCallback.java
├── common/
│ ├── BitmapUtils.java
│ └── Runnable.java
├── config/
│ └── Config.java
├── decode/
│ ├── BitmapDecoder.java
│ ├── BitmapLuminanceSource.java
│ ├── CaptureActivityHandler.java
│ ├── DecodeFormatManager.java
│ ├── DecodeHandler.java
│ └── DecodeThread.java
└── view/
├── ViewfinderResultPointCallback.java
└── ViewfinderView.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .classpath
================================================
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
================================================
FILE: .gitignore
================================================
# Built application files
*.apk
*.ap_
# Files for the Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
================================================
FILE: .project
================================================
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>BarcodeScanner</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
================================================
FILE: AndroidManifest.xml
================================================
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.hugo.android.scanner"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.CAMERA" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="cn.hugo.android.scanner.CaptureActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
BarcodeScanner
==============
Android手机客户端关于二维码扫描的源码,使用了zxing 3.1.1代码并对其进行了精简,支持低版本的sdk,实现了二维码和一维码的扫描、从图片解析一维码和二维码,闪光灯、调焦。。。




================================================
FILE: doc/readme.txt
================================================
参考文档
http://my.oschina.net/madmatrix/blog/189031
================================================
FILE: lint.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<lint>
</lint>
================================================
FILE: proguard-project.txt
================================================
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
================================================
FILE: project.properties
================================================
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-19
================================================
FILE: res/drawable/scan_flashlight.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/scan_flashlight_pressed" android:state_pressed="true"></item>
<item android:drawable="@drawable/scan_flashlight_normal"></item>
</selector>
================================================
FILE: res/drawable/scan_history.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/scan_history_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/scan_history_normal"/>
</selector>
================================================
FILE: res/drawable/scan_photo.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/scan_photo_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/scan_photo_normal"/>
</selector>
================================================
FILE: res/drawable/seekbar_bg.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background">
<shape>
<corners android:radius="10.0dip" />
<gradient
android:angle="360.0"
android:centerColor="#89898989"
android:centerY="0.45"
android:endColor="#89898989"
android:startColor="#89898989" />
</shape>
</item>
</layer-list>
================================================
FILE: res/drawable/seekbar_style.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background">
<shape>
<corners android:radius="10.0dip" />
<gradient
android:angle="270.0"
android:centerColor="#ff606060"
android:centerY="0.45"
android:endColor="#ff808080"
android:startColor="#ff808080" />
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="10.0dip" />
<gradient
android:angle="270.0"
android:centerColor="#ffe6e6e6"
android:centerY="0.45"
android:endColor="#fff6f6f6"
android:startColor="#fff6f6f6" />
</shape>
</clip>
</item>
</layer-list>
================================================
FILE: res/layout/capture.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/capture_frame"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<SurfaceView
android:id="@+id/capture_preview_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center" />
<cn.hugo.android.scanner.view.ViewfinderView
android:id="@+id/capture_viewfinder_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="@android:color/transparent" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="85.0dip"
android:background="@color/capture_text_cover_bg"
android:orientation="horizontal"
android:weightSum="5.0" >
<LinearLayout
android:layout_width="0.0dip"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:id="@+id/capture_flashlight"
android:layout_width="30.0dip"
android:layout_height="30.0dip"
android:layout_gravity="center_vertical"
android:clickable="true"
android:scaleType="fitCenter"
android:src="@drawable/scan_flashlight" />
</LinearLayout>
<TextView
android:id="@+id/capture_top_hint"
android:layout_width="0.0dip"
android:layout_height="85.0dip"
android:layout_gravity="top|center"
android:layout_weight="3.0"
android:gravity="center"
android:paddingLeft="20.0dip"
android:text="@string/top_hint"
android:textColor="#ffffffff"
android:textSize="13.0sp" />
<LinearLayout
android:layout_width="0.0dip"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:id="@+id/capture_scan_photo"
android:layout_width="30.0dip"
android:layout_height="30.0dip"
android:layout_gravity="center_vertical"
android:clickable="true"
android:scaleType="fitCenter"
android:src="@drawable/scan_photo" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="95.0dip"
android:layout_gravity="bottom|center"
android:background="@color/capture_text_cover_bg"
android:orientation="horizontal" >
<Button
android:id="@+id/capture_button_cancel"
android:layout_width="70.0dip"
android:layout_height="40.0dip"
android:layout_gravity="center_vertical"
android:layout_marginLeft="20.0dip"
android:text="@string/cancel"
android:textSize="14.0sp" />
<Button
android:id="@+id/capture_button_createcode"
android:layout_width="70.0dip"
android:layout_height="40.0dip"
android:layout_gravity="center_vertical"
android:layout_marginLeft="20.0dip"
android:text="@string/create"
android:textSize="14.0sp"
android:visibility="gone" />
<TextView
android:id="@+id/capture_bottom_hint"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:paddingLeft="20.0dip"
android:paddingRight="20.0dip"
android:text="@string/bottom_hint"
android:textColor="#ffffffff"
android:textSize="13.0sp" />
</LinearLayout>
</FrameLayout>
================================================
FILE: res/values/colors.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<color name="contents_text">#ff000000</color>
<color name="encode_view">#ffffffff</color>
<color name="possible_result_points">#c0ffbd21</color> <!-- Android standard ICS color -->
<color name="result_minor_text">#ffc0c0c0</color>
<color name="result_points">#c099cc00</color> <!-- Android standard ICS color -->
<color name="result_text">#ffffffff</color>
<color name="result_view">#b0000000</color>
<color name="status_text">#ffffffff</color>
<color name="transparent">#00000000</color>
<color name="viewfinder_laser">#ffcc0000</color> <!-- Android standard ICS color -->
<color name="viewfinder_mask">#00000000</color>
<color name="capture_text_cover_bg">#99535353</color>
<color name="seek_bar_text">#fff6f6f6</color>
</resources>
================================================
FILE: res/values/ids.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2008 ZXing authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<resources>
<!-- Messages IDs -->
<item type="id" name="auto_focus"/>
<item type="id" name="decode"/>
<item type="id" name="decode_failed"/>
<item type="id" name="decode_succeeded"/>
<item type="id" name="launch_product_query"/>
<item type="id" name="quit"/>
<item type="id" name="restart_preview"/>
<item type="id" name="return_scan_result"/>
<item type="id" name="search_book_contents_failed"/>
<item type="id" name="search_book_contents_succeeded"/>
</resources>
================================================
FILE: res/values/strings.xml
================================================
<resources>
<string name="app_name">二维条形码扫描</string>
<string name="placeHolder">placeHolder</string>
<string name="seekbar_add">+</string>
<string name="seekbar_minus">-</string>
<string name="create">生成</string>
<string name="scan_failed">扫描失败</string>
<string name="bottom_hint">建议与镜头保持10CM距离,尽量避免逆光和阴影</string>
<string name="top_hint">将条形码或二维码置于取景框内系统会自动扫描</string>
<string name="cancel">取消</string>
<string name="msg_camera_framework_bug">抱歉,Android相机出现问题。您可能需要重启设备。</string>
<string name="button_ok">确定</string>
</resources>
================================================
FILE: res/values/styles.xml
================================================
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
================================================
FILE: res/values-v11/styles.xml
================================================
<resources>
<!--
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
<!-- API 11 theme customizations can go here. -->
</style>
</resources>
================================================
FILE: res/values-v14/styles.xml
================================================
<resources>
<!--
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- API 14 theme customizations can go here. -->
</style>
</resources>
================================================
FILE: src/cn/hugo/android/scanner/AmbientLightManager.java
================================================
/*
* Copyright (C) 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.preference.PreferenceManager;
import cn.hugo.android.scanner.camera.CameraManager;
import cn.hugo.android.scanner.camera.FrontLightMode;
/**
* Detects ambient light and switches on the front light when very dark, and off
* again when sufficiently light.
*
* @author Sean Owen
* @author Nikolaus Huber
*/
final class AmbientLightManager implements SensorEventListener {
private static final float TOO_DARK_LUX = 45.0f;
private static final float BRIGHT_ENOUGH_LUX = 450.0f;
private final Context context;
private CameraManager cameraManager;
/**
* 光传感器
*/
private Sensor lightSensor;
AmbientLightManager(Context context) {
this.context = context;
}
void start(CameraManager cameraManager) {
this.cameraManager = cameraManager;
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
if (FrontLightMode.readPref(sharedPrefs) == FrontLightMode.AUTO) {
SensorManager sensorManager = (SensorManager) context
.getSystemService(Context.SENSOR_SERVICE);
lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (lightSensor != null) {
sensorManager.registerListener(this, lightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
}
void stop() {
if (lightSensor != null) {
SensorManager sensorManager = (SensorManager) context
.getSystemService(Context.SENSOR_SERVICE);
sensorManager.unregisterListener(this);
cameraManager = null;
lightSensor = null;
}
}
/**
* 该方法会在周围环境改变后回调,然后根据设置好的临界值决定是否打开闪光灯
*/
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float ambientLightLux = sensorEvent.values[0];
if (cameraManager != null) {
if (ambientLightLux <= TOO_DARK_LUX) {
cameraManager.setTorch(true);
}
else if (ambientLightLux >= BRIGHT_ENOUGH_LUX) {
cameraManager.setTorch(false);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// do nothing
}
}
================================================
FILE: src/cn/hugo/android/scanner/BeepManager.java
================================================
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import cn.hugo.android.scanner.config.Config;
/**
* Manages beeps and vibrations for {@link CaptureActivity}.
*/
final class BeepManager implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener {
private static final String TAG = BeepManager.class.getSimpleName();
private static final float BEEP_VOLUME = 0.10f;
private static final long VIBRATE_DURATION = 200L;
private final Activity activity;
private MediaPlayer mediaPlayer;
private boolean playBeep;
private boolean vibrate;
BeepManager(Activity activity) {
this.activity = activity;
this.mediaPlayer = null;
updatePrefs();
}
/**
* 扫描成功后可以播放提示音并震动,这两种功能都是用户自定义的 在Barcode Scanner中点击菜单键,点设置即可看到这两项的设置
*/
synchronized void updatePrefs() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(activity);
playBeep = shouldBeep(prefs, activity);
vibrate = prefs.getBoolean(Config.KEY_VIBRATE, false);
if (playBeep && mediaPlayer == null) {
// The volume on STREAM_SYSTEM is not adjustable, and users found it
// too loud,
// so we now play on the music stream.
activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = buildMediaPlayer(activity);
}
}
/**
* 根据配置播放提示音和震动
*/
synchronized void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) activity
.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
private static boolean shouldBeep(SharedPreferences prefs, Context activity) {
boolean shouldPlayBeep = prefs.getBoolean(Config.KEY_PLAY_BEEP, true);
if (shouldPlayBeep) {
// See if sound settings overrides this
AudioManager audioService = (AudioManager) activity
.getSystemService(Context.AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
shouldPlayBeep = false;
}
}
return shouldPlayBeep;
}
private MediaPlayer buildMediaPlayer(Context activity) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
AssetFileDescriptor file = activity.getResources().openRawResourceFd(
R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(),
file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
}
catch (IOException ioe) {
Log.w(TAG, ioe);
mediaPlayer = null;
}
return mediaPlayer;
}
@Override
public void onCompletion(MediaPlayer mp) {
// When the beep has finished playing, rewind to queue up another one.
mp.seekTo(0);
}
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
// we are finished, so put up an appropriate error toast if required
// and finish
activity.finish();
}
else {
// possibly media player error, so release and recreate
mp.release();
mediaPlayer = null;
updatePrefs();
}
return true;
}
/**
* 新增
* 关闭beep声音
*/
public synchronized void close() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
================================================
FILE: src/cn/hugo/android/scanner/CaptureActivity.java
================================================
package cn.hugo.android.scanner;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import cn.hugo.android.scanner.camera.CameraManager;
import cn.hugo.android.scanner.common.BitmapUtils;
import cn.hugo.android.scanner.decode.BitmapDecoder;
import cn.hugo.android.scanner.decode.CaptureActivityHandler;
import cn.hugo.android.scanner.view.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.client.result.ResultParser;
/**
* This activity opens the camera and does the actual scanning on a background
* thread. It draws a viewfinder to help the user place the barcode correctly,
* shows feedback as the image processing is happening, and then overlays the
* results when a scan is successful.
*
* 此Activity所做的事: 1.开启camera,在后台独立线程中完成扫描任务;
* 2.绘制了一个扫描区(viewfinder)来帮助用户将条码置于其中以准确扫描; 3.扫描成功后会将扫描结果展示在界面上。
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/
public final class CaptureActivity extends Activity implements
SurfaceHolder.Callback, View.OnClickListener {
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final int REQUEST_CODE = 100;
private static final int PARSE_BARCODE_FAIL = 300;
private static final int PARSE_BARCODE_SUC = 200;
/**
* 是否有预览
*/
private boolean hasSurface;
/**
* 活动监控器。如果手机没有连接电源线,那么当相机开启后如果一直处于不被使用状态则该服务会将当前activity关闭。
* 活动监控器全程监控扫描活跃状态,与CaptureActivity生命周期相同.每一次扫描过后都会重置该监控,即重新倒计时。
*/
private InactivityTimer inactivityTimer;
/**
* 声音震动管理器。如果扫描成功后可以播放一段音频,也可以震动提醒,可以通过配置来决定扫描成功后的行为。
*/
private BeepManager beepManager;
/**
* 闪光灯调节器。自动检测环境光线强弱并决定是否开启闪光灯
*/
private AmbientLightManager ambientLightManager;
private CameraManager cameraManager;
/**
* 扫描区域
*/
private ViewfinderView viewfinderView;
private CaptureActivityHandler handler;
private Result lastResult;
private boolean isFlashlightOpen;
/**
* 【辅助解码的参数(用作MultiFormatReader的参数)】 编码类型,该参数告诉扫描器采用何种编码方式解码,即EAN-13,QR
* Code等等 对应于DecodeHintType.POSSIBLE_FORMATS类型
* 参考DecodeThread构造函数中如下代码:hints.put(DecodeHintType.POSSIBLE_FORMATS,
* decodeFormats);
*/
private Collection<BarcodeFormat> decodeFormats;
/**
* 【辅助解码的参数(用作MultiFormatReader的参数)】 该参数最终会传入MultiFormatReader,
* 上面的decodeFormats和characterSet最终会先加入到decodeHints中 最终被设置到MultiFormatReader中
* 参考DecodeHandler构造器中如下代码:multiFormatReader.setHints(hints);
*/
private Map<DecodeHintType, ?> decodeHints;
/**
* 【辅助解码的参数(用作MultiFormatReader的参数)】 字符集,告诉扫描器该以何种字符集进行解码
* 对应于DecodeHintType.CHARACTER_SET类型
* 参考DecodeThread构造器如下代码:hints.put(DecodeHintType.CHARACTER_SET,
* characterSet);
*/
private String characterSet;
private Result savedResultToShow;
private IntentSource source;
/**
* 图片的路径
*/
private String photoPath;
private Handler mHandler = new MyHandler(this);
static class MyHandler extends Handler {
private WeakReference<Activity> activityReference;
public MyHandler(Activity activity) {
activityReference = new WeakReference<Activity>(activity);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case PARSE_BARCODE_SUC: // 解析图片成功
Toast.makeText(activityReference.get(),
"解析成功,结果为:" + msg.obj, Toast.LENGTH_SHORT).show();
break;
case PARSE_BARCODE_FAIL:// 解析图片失败
Toast.makeText(activityReference.get(), "解析图片失败",
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
super.handleMessage(msg);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.capture);
hasSurface = false;
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
ambientLightManager = new AmbientLightManager(this);
// 监听图片识别按钮
findViewById(R.id.capture_scan_photo).setOnClickListener(this);
findViewById(R.id.capture_flashlight).setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is
// necessary because we don't
// want to open the camera driver and measure the screen size if we're
// going to show the help on
// first launch. That led to bugs where the scanning rectangle was the
// wrong size and partially
// off screen.
// 相机初始化的动作需要开启相机并测量屏幕大小,这些操作
// 不建议放到onCreate中,因为如果在onCreate中加上首次启动展示帮助信息的代码的 话,
// 会导致扫描窗口的尺寸计算有误的bug
cameraManager = new CameraManager(getApplication());
viewfinderView = (ViewfinderView) findViewById(R.id.capture_viewfinder_view);
viewfinderView.setCameraManager(cameraManager);
handler = null;
lastResult = null;
// 摄像头预览功能必须借助SurfaceView,因此也需要在一开始对其进行初始化
// 如果需要了解SurfaceView的原理
// 参考:http://blog.csdn.net/luoshengyang/article/details/8661317
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.capture_preview_view); // 预览
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
// The activity was paused but not stopped, so the surface still
// exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(surfaceHolder);
}
else {
// 防止sdk8的设备初始化预览异常
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// Install the callback and wait for surfaceCreated() to init the
// camera.
surfaceHolder.addCallback(this);
}
// 加载声音配置,其实在BeemManager的构造器中也会调用该方法,即在onCreate的时候会调用一次
beepManager.updatePrefs();
// 启动闪光灯调节器
ambientLightManager.start(cameraManager);
// 恢复活动监控器
inactivityTimer.onResume();
source = IntentSource.NONE;
decodeFormats = null;
characterSet = null;
}
@Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
ambientLightManager.stop();
beepManager.close();
// 关闭摄像头
cameraManager.closeDriver();
if (!hasSurface) {
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.capture_preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.removeCallback(this);
}
super.onPause();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if ((source == IntentSource.NONE) && lastResult != null) { // 重新进行扫描
restartPreviewAfterDelay(0L);
return true;
}
break;
case KeyEvent.KEYCODE_FOCUS:
case KeyEvent.KEYCODE_CAMERA:
// Handle these events so they don't launch the Camera app
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
cameraManager.zoomIn();
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
cameraManager.zoomOut();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
final ProgressDialog progressDialog;
switch (requestCode) {
case REQUEST_CODE:
// 获取选中图片的路径
Cursor cursor = getContentResolver().query(
intent.getData(), null, null, null, null);
if (cursor.moveToFirst()) {
photoPath = cursor.getString(cursor
.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("正在扫描...");
progressDialog.setCancelable(false);
progressDialog.show();
new Thread(new Runnable() {
@Override
public void run() {
Bitmap img = BitmapUtils
.getCompressedBitmap(photoPath);
BitmapDecoder decoder = new BitmapDecoder(
CaptureActivity.this);
Result result = decoder.getRawResult(img);
if (result != null) {
Message m = mHandler.obtainMessage();
m.what = PARSE_BARCODE_SUC;
m.obj = ResultParser.parseResult(result)
.toString();
mHandler.sendMessage(m);
}
else {
Message m = mHandler.obtainMessage();
m.what = PARSE_BARCODE_FAIL;
mHandler.sendMessage(m);
}
progressDialog.dismiss();
}
}).start();
break;
}
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG,
"*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
/*hasSurface = false;*/
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
/**
* A valid barcode has been found, so give an indication of success and show
* the results.
*
* @param rawResult
* The contents of the barcode.
* @param scaleFactor
* amount by which thumbnail was scaled
* @param barcode
* A greyscale bitmap of the camera data which was decoded.
*/
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
// 重新计时
inactivityTimer.onActivity();
lastResult = rawResult;
// 把图片画到扫描框
viewfinderView.drawResultBitmap(barcode);
beepManager.playBeepSoundAndVibrate();
Toast.makeText(this,
"识别结果:" + ResultParser.parseResult(rawResult).toString(),
Toast.LENGTH_SHORT).show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
resetStatusView();
}
public ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
public CameraManager getCameraManager() {
return cameraManager;
}
private void resetStatusView() {
viewfinderView.setVisibility(View.VISIBLE);
lastResult = null;
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG,
"initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a
// RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, decodeFormats,
decodeHints, characterSet, cameraManager);
}
decodeOrStoreSavedBitmap(null, null);
}
catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
}
catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
/**
* 向CaptureActivityHandler中发送消息,并展示扫描到的图像
*
* @param bitmap
* @param result
*/
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
// Bitmap isn't used yet -- will be used soon
if (handler == null) {
savedResultToShow = result;
}
else {
if (result != null) {
savedResultToShow = result;
}
if (savedResultToShow != null) {
Message message = Message.obtain(handler,
R.id.decode_succeeded, savedResultToShow);
handler.sendMessage(message);
}
savedResultToShow = null;
}
}
private void displayFrameworkBugMessageAndExit() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.msg_camera_framework_bug));
builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
builder.setOnCancelListener(new FinishListener(this));
builder.show();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.capture_scan_photo: // 图片识别
// 打开手机中的相册
Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
innerIntent.setType("image/*");
Intent wrapperIntent = Intent.createChooser(innerIntent,
"选择二维码图片");
this.startActivityForResult(wrapperIntent, REQUEST_CODE);
break;
case R.id.capture_flashlight:
if (isFlashlightOpen) {
cameraManager.setTorch(false); // 关闭闪光灯
isFlashlightOpen = false;
}
else {
cameraManager.setTorch(true); // 打开闪光灯
isFlashlightOpen = true;
}
break;
default:
break;
}
}
}
================================================
FILE: src/cn/hugo/android/scanner/FinishListener.java
================================================
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner;
import android.app.Activity;
import android.content.DialogInterface;
/**
* Simple listener used to exit the app in a few cases.
*
* @author Sean Owen
*/
public final class FinishListener implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
private final Activity activityToFinish;
public FinishListener(Activity activityToFinish) {
this.activityToFinish = activityToFinish;
}
@Override
public void onCancel(DialogInterface dialogInterface) {
run();
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
run();
}
private void run() {
activityToFinish.finish();
}
}
================================================
FILE: src/cn/hugo/android/scanner/InactivityTimer.java
================================================
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.util.Log;
import cn.hugo.android.scanner.common.Runnable;
/**
* Finishes an activity after a period of inactivity if the device is on battery
* power. <br/>
* <br/>
*
* 该活动监控器全程监控扫描活跃状态,与CaptureActivity生命周期相同
*/
final class InactivityTimer {
private static final String TAG = InactivityTimer.class.getSimpleName();
/**
* 如果在5min内扫描器没有被使用过,则自动finish掉activity
*/
private static final long INACTIVITY_DELAY_MS = 5 * 60 * 1000L;
/**
* 在本app中,此activity即为CaptureActivity
*/
private final Activity activity;
/**
* 接受系统广播:手机是否连通电源
*/
private final BroadcastReceiver powerStatusReceiver;
private boolean registered;
private AsyncTask<?, ?, ?> inactivityTask;
InactivityTimer(Activity activity) {
this.activity = activity;
powerStatusReceiver = new PowerStatusReceiver();
registered = false;
onActivity();
}
/**
* 首先终止之前的监控任务,然后新起一个监控任务
*/
synchronized void onActivity() {
cancel();
inactivityTask = new InactivityAsyncTask();
Runnable.execAsync(inactivityTask);
}
public synchronized void onPause() {
cancel();
if (registered) {
activity.unregisterReceiver(powerStatusReceiver);
registered = false;
}
else {
Log.w(TAG, "PowerStatusReceiver was never registered?");
}
}
public synchronized void onResume() {
if (registered) {
Log.w(TAG, "PowerStatusReceiver was already registered?");
}
else {
activity.registerReceiver(powerStatusReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
registered = true;
}
onActivity();
}
/**
* 取消监控任务
*/
private synchronized void cancel() {
AsyncTask<?, ?, ?> task = inactivityTask;
if (task != null) {
task.cancel(true);
inactivityTask = null;
}
}
void shutdown() {
cancel();
}
/**
* 监听是否连通电源的系统广播。如果连通电源,则停止监控任务,否则重启监控任务
*/
private final class PowerStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
// 0 indicates that we're on battery
boolean onBatteryNow = intent.getIntExtra(
BatteryManager.EXTRA_PLUGGED, -1) <= 0;
if (onBatteryNow) {
InactivityTimer.this.onActivity();
}
else {
InactivityTimer.this.cancel();
}
}
}
}
/**
* 该任务很简单,就是在INACTIVITY_DELAY_MS时间后终结activity
*/
private final class InactivityAsyncTask extends
AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... objects) {
try {
Thread.sleep(INACTIVITY_DELAY_MS);
Log.i(TAG, "Finishing activity due to inactivity");
activity.finish();
}
catch (InterruptedException e) {
// continue without killing
}
return null;
}
}
}
================================================
FILE: src/cn/hugo/android/scanner/IntentSource.java
================================================
/*
* Copyright (C) 2011 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner;
enum IntentSource {
NATIVE_APP_INTENT,
PRODUCT_SEARCH_LINK,
ZXING_LINK,
NONE
}
================================================
FILE: src/cn/hugo/android/scanner/Intents.java
================================================
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner;
/**
* This class provides the constants to use when sending an Intent to Barcode Scanner.
* These strings are effectively API and cannot be changed.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class Intents {
private Intents() {
}
public static final class Scan {
/**
* Send this intent to open the Barcodes app in scanning mode, find a barcode, and return
* the results.
*/
public static final String ACTION = "com.google.zxing.client.android.SCAN";
/**
* By default, sending this will decode all barcodes that we understand. However it
* may be useful to limit scanning to certain formats. Use
* {@link android.content.Intent#putExtra(String, String)} with one of the values below.
*
* Setting this is effectively shorthand for setting explicit formats with {@link #FORMATS}.
* It is overridden by that setting.
*/
public static final String MODE = "SCAN_MODE";
/**
* Decode only UPC and EAN barcodes. This is the right choice for shopping apps which get
* prices, reviews, etc. for products.
*/
public static final String PRODUCT_MODE = "PRODUCT_MODE";
/**
* Decode only 1D barcodes.
*/
public static final String ONE_D_MODE = "ONE_D_MODE";
/**
* Decode only QR codes.
*/
public static final String QR_CODE_MODE = "QR_CODE_MODE";
/**
* Decode only Data Matrix codes.
*/
public static final String DATA_MATRIX_MODE = "DATA_MATRIX_MODE";
/**
* Decode only Aztec.
*/
public static final String AZTEC_MODE = "AZTEC_MODE";
/**
* Decode only PDF417.
*/
public static final String PDF417_MODE = "PDF417_MODE";
/**
* Comma-separated list of formats to scan for. The values must match the names of
* {@link com.google.zxing.BarcodeFormat}s, e.g. {@link com.google.zxing.BarcodeFormat#EAN_13}.
* Example: "EAN_13,EAN_8,QR_CODE". This overrides {@link #MODE}.
*/
public static final String FORMATS = "SCAN_FORMATS";
/**
* Optional parameter to specify the id of the camera from which to recognize barcodes.
* Overrides the default camera that would otherwise would have been selected.
* If provided, should be an int.
*/
public static final String CAMERA_ID = "SCAN_CAMERA_ID";
/**
* @see com.google.zxing.DecodeHintType#CHARACTER_SET
*/
public static final String CHARACTER_SET = "CHARACTER_SET";
/**
* Optional parameters to specify the width and height of the scanning rectangle in pixels.
* The app will try to honor these, but will clamp them to the size of the preview frame.
* You should specify both or neither, and pass the size as an int.
*/
public static final String WIDTH = "SCAN_WIDTH";
public static final String HEIGHT = "SCAN_HEIGHT";
/**
* Desired duration in milliseconds for which to pause after a successful scan before
* returning to the calling intent. Specified as a long, not an integer!
* For example: 1000L, not 1000.
*/
public static final String RESULT_DISPLAY_DURATION_MS = "RESULT_DISPLAY_DURATION_MS";
/**
* Prompt to show on-screen when scanning by intent. Specified as a {@link String}.
*/
public static final String PROMPT_MESSAGE = "PROMPT_MESSAGE";
/**
* If a barcode is found, Barcodes returns {@link android.app.Activity#RESULT_OK} to
* {@link android.app.Activity#onActivityResult(int, int, android.content.Intent)}
* of the app which requested the scan via
* {@link android.app.Activity#startActivityForResult(android.content.Intent, int)}
* The barcodes contents can be retrieved with
* {@link android.content.Intent#getStringExtra(String)}.
* If the user presses Back, the result code will be {@link android.app.Activity#RESULT_CANCELED}.
*/
public static final String RESULT = "SCAN_RESULT";
/**
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_FORMAT}
* to determine which barcode format was found.
* See {@link com.google.zxing.BarcodeFormat} for possible values.
*/
public static final String RESULT_FORMAT = "SCAN_RESULT_FORMAT";
/**
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_UPC_EAN_EXTENSION}
* to return the content of any UPC extension barcode that was also found. Only applicable
* to {@link com.google.zxing.BarcodeFormat#UPC_A} and {@link com.google.zxing.BarcodeFormat#EAN_13}
* formats.
*/
public static final String RESULT_UPC_EAN_EXTENSION = "SCAN_RESULT_UPC_EAN_EXTENSION";
/**
* Call {@link android.content.Intent#getByteArrayExtra(String)} with {@link #RESULT_BYTES}
* to get a {@code byte[]} of raw bytes in the barcode, if available.
*/
public static final String RESULT_BYTES = "SCAN_RESULT_BYTES";
/**
* Key for the value of {@link com.google.zxing.ResultMetadataType#ORIENTATION}, if available.
* Call {@link android.content.Intent#getIntArrayExtra(String)} with {@link #RESULT_ORIENTATION}.
*/
public static final String RESULT_ORIENTATION = "SCAN_RESULT_ORIENTATION";
/**
* Key for the value of {@link com.google.zxing.ResultMetadataType#ERROR_CORRECTION_LEVEL}, if available.
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_ERROR_CORRECTION_LEVEL}.
*/
public static final String RESULT_ERROR_CORRECTION_LEVEL = "SCAN_RESULT_ERROR_CORRECTION_LEVEL";
/**
* Prefix for keys that map to the values of {@link com.google.zxing.ResultMetadataType#BYTE_SEGMENTS},
* if available. The actual values will be set under a series of keys formed by adding 0, 1, 2, ...
* to this prefix. So the first byte segment is under key "SCAN_RESULT_BYTE_SEGMENTS_0" for example.
* Call {@link android.content.Intent#getByteArrayExtra(String)} with these keys.
*/
public static final String RESULT_BYTE_SEGMENTS_PREFIX = "SCAN_RESULT_BYTE_SEGMENTS_";
/**
* Setting this to false will not save scanned codes in the history. Specified as a {@code boolean}.
*/
public static final String SAVE_HISTORY = "SAVE_HISTORY";
private Scan() {
}
}
public static final class History {
public static final String ITEM_NUMBER = "ITEM_NUMBER";
private History() {
}
}
public static final class Encode {
/**
* Send this intent to encode a piece of data as a QR code and display it full screen, so
* that another person can scan the barcode from your screen.
*/
public static final String ACTION = "com.google.zxing.client.android.ENCODE";
/**
* The data to encode. Use {@link android.content.Intent#putExtra(String, String)} or
* {@link android.content.Intent#putExtra(String, android.os.Bundle)},
* depending on the type and format specified. Non-QR Code formats should
* just use a String here. For QR Code, see Contents for details.
*/
public static final String DATA = "ENCODE_DATA";
/**
* The type of data being supplied if the format is QR Code. Use
* {@link android.content.Intent#putExtra(String, String)} with one of {@link Contents.Type}.
*/
public static final String TYPE = "ENCODE_TYPE";
/**
* The barcode format to be displayed. If this isn't specified or is blank,
* it defaults to QR Code. Use {@link android.content.Intent#putExtra(String, String)}, where
* format is one of {@link com.google.zxing.BarcodeFormat}.
*/
public static final String FORMAT = "ENCODE_FORMAT";
/**
* Normally the contents of the barcode are displayed to the user in a TextView. Setting this
* boolean to false will hide that TextView, showing only the encode barcode.
*/
public static final String SHOW_CONTENTS = "ENCODE_SHOW_CONTENTS";
private Encode() {
}
}
public static final class SearchBookContents {
/**
* Use Google Book Search to search the contents of the book provided.
*/
public static final String ACTION = "com.google.zxing.client.android.SEARCH_BOOK_CONTENTS";
/**
* The book to search, identified by ISBN number.
*/
public static final String ISBN = "ISBN";
/**
* An optional field which is the text to search for.
*/
public static final String QUERY = "QUERY";
private SearchBookContents() {
}
}
public static final class WifiConnect {
/**
* Internal intent used to trigger connection to a wi-fi network.
*/
public static final String ACTION = "com.google.zxing.client.android.WIFI_CONNECT";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String SSID = "SSID";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String TYPE = "TYPE";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String PASSWORD = "PASSWORD";
private WifiConnect() {
}
}
public static final class Share {
/**
* Give the user a choice of items to encode as a barcode, then render it as a QR Code and
* display onscreen for a friend to scan with their phone.
*/
public static final String ACTION = "com.google.zxing.client.android.SHARE";
private Share() {
}
}
}
================================================
FILE: src/cn/hugo/android/scanner/camera/AutoFocusManager.java
================================================
/*
* Copyright (C) 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.camera;
import java.util.ArrayList;
import java.util.Collection;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import cn.hugo.android.scanner.common.Runnable;
import cn.hugo.android.scanner.config.Config;
/**
* 由于对焦不是一次性完成的任务(手抖),而系统提供的对焦仅有Camera.autoFocus()方法,
* 因此需要一个线程来不断调用Camera.autoFocus()直到用户满意按下快门为止
*/
final class AutoFocusManager implements Camera.AutoFocusCallback {
private static final String TAG = AutoFocusManager.class.getSimpleName();
private static final long AUTO_FOCUS_INTERVAL_MS = 2000L;
private static final Collection<String> FOCUS_MODES_CALLING_AF;
static {
FOCUS_MODES_CALLING_AF = new ArrayList<String>(2);
FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO);
FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO);
}
private boolean active;
private final boolean useAutoFocus;
private final Camera camera;
private AsyncTask<?, ?, ?> outstandingTask;
AutoFocusManager(Context context, Camera camera) {
this.camera = camera;
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
String currentFocusMode = camera.getParameters().getFocusMode();
useAutoFocus = sharedPrefs.getBoolean(Config.KEY_AUTO_FOCUS, true)
&& FOCUS_MODES_CALLING_AF.contains(currentFocusMode);
Log.i(TAG, "Current focus mode '" + currentFocusMode
+ "'; use auto focus? " + useAutoFocus);
start();
}
@Override
public synchronized void onAutoFocus(boolean success, Camera theCamera) {
if (active) {
outstandingTask = new AutoFocusTask();
Runnable.execAsync(outstandingTask);
}
}
synchronized void start() {
if (useAutoFocus) {
active = true;
try {
camera.autoFocus(this);
}
catch (RuntimeException re) {
// Have heard RuntimeException reported in Android 4.0.x+;
// continue?
Log.w(TAG, "Unexpected exception while focusing", re);
}
}
}
synchronized void stop() {
if (useAutoFocus) {
try {
camera.cancelAutoFocus();
}
catch (RuntimeException re) {
// Have heard RuntimeException reported in Android 4.0.x+;
// continue?
Log.w(TAG, "Unexpected exception while cancelling focusing", re);
}
}
if (outstandingTask != null) {
outstandingTask.cancel(true);
outstandingTask = null;
}
active = false;
}
private final class AutoFocusTask extends AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... voids) {
try {
Thread.sleep(AUTO_FOCUS_INTERVAL_MS);
}
catch (InterruptedException e) {
// continue
}
synchronized (AutoFocusManager.this) {
if (active) {
start();
}
}
return null;
}
}
}
================================================
FILE: src/cn/hugo/android/scanner/camera/CameraConfigurationManager.java
================================================
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.camera;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.hardware.Camera;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import cn.hugo.android.scanner.config.Config;
/**
* A class which deals with reading, parsing, and setting the camera parameters
* which are used to configure the camera hardware.
*
* <br/>
*
* 摄像头参数的设置类
*/
final class CameraConfigurationManager {
private static final String TAG = "CameraConfiguration";
// This is bigger than the size of a small screen, which is still supported.
// The routine
// below will still select the default (presumably 320x240) size for these.
// This prevents
// accidental selection of very low resolution on some devices.
private static final int MIN_PREVIEW_PIXELS = 480 * 320; // normal screen
// private static final float MAX_EXPOSURE_COMPENSATION = 1.5f;
// private static final float MIN_EXPOSURE_COMPENSATION = 0.0f;
private static final double MAX_ASPECT_DISTORTION = 0.15;
private final Context context;
/**
* 屏幕分辨率
*/
private Point screenResolution;
/**
* 相机分辨率
*/
private Point cameraResolution;
CameraConfigurationManager(Context context) {
this.context = context;
}
/**
* Reads, one time, values from the camera that are needed by the app.
*/
void initFromCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point theScreenResolution = new Point();
// sdk8出错
// display.getSize(theScreenResolution);
// 改为此方式
theScreenResolution = getDisplaySize(display);
screenResolution = theScreenResolution;
Log.i(TAG, "Screen resolution: " + screenResolution);
//解决竖屏拉伸
Point screenResolutionForCamera = new Point();
screenResolutionForCamera.x = screenResolution.x;
screenResolutionForCamera.y = screenResolution.y;
// preview size is always something like 480*320, other 320*480
if (screenResolution.x < screenResolution.y) {
screenResolutionForCamera.x = screenResolution.y;
screenResolutionForCamera.y = screenResolution.x;
}
cameraResolution = findBestPreviewSizeValue(parameters,
screenResolutionForCamera);
Log.i(TAG, "Camera resolution: " + cameraResolution);
}
@SuppressLint("NewApi")
private Point getDisplaySize(final Display display) {
final Point point = new Point();
try {
display.getSize(point);
}
catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
return point;
}
void setDesiredCameraParameters(Camera camera, boolean safeMode) {
Camera.Parameters parameters = camera.getParameters();
if (parameters == null) {
Log.w(TAG,
"Device error: no camera parameters are available. Proceeding without configuration.");
return;
}
Log.i(TAG, "Initial camera parameters: " + parameters.flatten());
if (safeMode) {
Log.w(TAG,
"In camera config safe mode -- most settings will not be honored");
}
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
// 初始化闪光灯
initializeTorch(parameters, prefs, safeMode);
// 默认使用自动对焦
String focusMode = findSettableValue(
parameters.getSupportedFocusModes(),
Camera.Parameters.FOCUS_MODE_AUTO);
// Maybe selected auto-focus but not available, so fall through here:
if (!safeMode && focusMode == null) {
focusMode = findSettableValue(parameters.getSupportedFocusModes(),
Camera.Parameters.FOCUS_MODE_MACRO,
Camera.Parameters.FOCUS_MODE_EDOF);
}
if (focusMode != null) {
parameters.setFocusMode(focusMode);
}
if (prefs.getBoolean(Config.KEY_INVERT_SCAN, false)) {
String colorMode = findSettableValue(
parameters.getSupportedColorEffects(),
Camera.Parameters.EFFECT_NEGATIVE);
if (colorMode != null) {
parameters.setColorEffect(colorMode);
}
}
parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
camera.setParameters(parameters);
Camera.Parameters afterParameters = camera.getParameters();
Camera.Size afterSize = afterParameters.getPreviewSize();
if (afterSize != null
&& (cameraResolution.x != afterSize.width || cameraResolution.y != afterSize.height)) {
Log.w(TAG, "Camera said it supported preview size "
+ cameraResolution.x + 'x' + cameraResolution.y
+ ", but after setting it, preview size is "
+ afterSize.width + 'x' + afterSize.height);
cameraResolution.x = afterSize.width;
cameraResolution.y = afterSize.height;
}
camera.setDisplayOrientation(90);
}
Point getCameraResolution() {
return cameraResolution;
}
Point getScreenResolution() {
return screenResolution;
}
boolean getTorchState(Camera camera) {
if (camera != null) {
Camera.Parameters parameters = camera.getParameters();
if (parameters != null) {
String flashMode = camera.getParameters().getFlashMode();
return flashMode != null
&& (Camera.Parameters.FLASH_MODE_ON.equals(flashMode) || Camera.Parameters.FLASH_MODE_TORCH
.equals(flashMode));
}
}
return false;
}
void setTorch(Camera camera, boolean newSetting) {
Camera.Parameters parameters = camera.getParameters();
doSetTorch(parameters, newSetting, false);
camera.setParameters(parameters);
}
private void initializeTorch(Camera.Parameters parameters,
SharedPreferences prefs, boolean safeMode) {
boolean currentSetting = FrontLightMode.readPref(prefs) == FrontLightMode.ON;
doSetTorch(parameters, currentSetting, safeMode);
}
private void doSetTorch(Camera.Parameters parameters, boolean newSetting,
boolean safeMode) {
String flashMode;
if (newSetting) {
flashMode = findSettableValue(parameters.getSupportedFlashModes(),
Camera.Parameters.FLASH_MODE_TORCH,
Camera.Parameters.FLASH_MODE_ON);
}
else {
flashMode = findSettableValue(parameters.getSupportedFlashModes(),
Camera.Parameters.FLASH_MODE_OFF);
}
if (flashMode != null) {
parameters.setFlashMode(flashMode);
}
}
/**
* 从相机支持的分辨率中计算出最适合的预览界面尺寸
*
* @param parameters
* @param screenResolution
* @return
*/
private Point findBestPreviewSizeValue(Camera.Parameters parameters,
Point screenResolution) {
List<Camera.Size> rawSupportedSizes = parameters
.getSupportedPreviewSizes();
if (rawSupportedSizes == null) {
Log.w(TAG,
"Device returned no supported preview sizes; using default");
Camera.Size defaultSize = parameters.getPreviewSize();
return new Point(defaultSize.width, defaultSize.height);
}
// Sort by size, descending
List<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(
rawSupportedSizes);
Collections.sort(supportedPreviewSizes, new Comparator<Camera.Size>() {
@Override
public int compare(Camera.Size a, Camera.Size b) {
int aPixels = a.height * a.width;
int bPixels = b.height * b.width;
if (bPixels < aPixels) {
return -1;
}
if (bPixels > aPixels) {
return 1;
}
return 0;
}
});
if (Log.isLoggable(TAG, Log.INFO)) {
StringBuilder previewSizesString = new StringBuilder();
for (Camera.Size supportedPreviewSize : supportedPreviewSizes) {
previewSizesString.append(supportedPreviewSize.width)
.append('x').append(supportedPreviewSize.height)
.append(' ');
}
Log.i(TAG, "Supported preview sizes: " + previewSizesString);
}
double screenAspectRatio = (double) screenResolution.x
/ (double) screenResolution.y;
// Remove sizes that are unsuitable
Iterator<Camera.Size> it = supportedPreviewSizes.iterator();
while (it.hasNext()) {
Camera.Size supportedPreviewSize = it.next();
int realWidth = supportedPreviewSize.width;
int realHeight = supportedPreviewSize.height;
if (realWidth * realHeight < MIN_PREVIEW_PIXELS) {
it.remove();
continue;
}
boolean isCandidatePortrait = realWidth < realHeight;
int maybeFlippedWidth = isCandidatePortrait ? realHeight
: realWidth;
int maybeFlippedHeight = isCandidatePortrait ? realWidth
: realHeight;
double aspectRatio = (double) maybeFlippedWidth
/ (double) maybeFlippedHeight;
double distortion = Math.abs(aspectRatio - screenAspectRatio);
if (distortion > MAX_ASPECT_DISTORTION) {
it.remove();
continue;
}
if (maybeFlippedWidth == screenResolution.x
&& maybeFlippedHeight == screenResolution.y) {
Point exactPoint = new Point(realWidth, realHeight);
Log.i(TAG, "Found preview size exactly matching screen size: "
+ exactPoint);
return exactPoint;
}
}
// If no exact match, use largest preview size. This was not a great
// idea on older devices because
// of the additional computation needed. We're likely to get here on
// newer Android 4+ devices, where
// the CPU is much more powerful.
if (!supportedPreviewSizes.isEmpty()) {
Camera.Size largestPreview = supportedPreviewSizes.get(0);
Point largestSize = new Point(largestPreview.width,
largestPreview.height);
Log.i(TAG, "Using largest suitable preview size: " + largestSize);
return largestSize;
}
// If there is nothing at all suitable, return current preview size
Camera.Size defaultPreview = parameters.getPreviewSize();
Point defaultSize = new Point(defaultPreview.width,
defaultPreview.height);
Log.i(TAG, "No suitable preview sizes, using default: " + defaultSize);
return defaultSize;
}
/**
* 在supportedValues中寻找desiredValues,找不到则返回null
*
* @param supportedValues
* @param desiredValues
* @return
*/
private static String findSettableValue(Collection<String> supportedValues,
String... desiredValues) {
Log.i(TAG, "Supported values: " + supportedValues);
String result = null;
if (supportedValues != null) {
for (String desiredValue : desiredValues) {
if (supportedValues.contains(desiredValue)) {
result = desiredValue;
break;
}
}
}
Log.i(TAG, "Settable value: " + result);
return result;
}
}
================================================
FILE: src/cn/hugo/android/scanner/camera/CameraManager.java
================================================
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.camera;
import java.io.IOException;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import com.google.zxing.PlanarYUVLuminanceSource;
/**
* This object wraps the Camera service object and expects to be the only one
* talking to it. The implementation encapsulates the steps needed to take
* preview-sized images, which are used for both preview and decoding. <br/>
* <br/>
*
* 该类封装了相机的所有服务并且是该app中唯一与相机打交道的类
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class CameraManager {
private static final String TAG = CameraManager.class.getSimpleName();
private static final int MIN_FRAME_WIDTH = 240;
private static final int MAX_FRAME_WIDTH = 1200; // = 5/8 * 1920
private final Context context;
private final CameraConfigurationManager configManager;
private Camera camera;
private AutoFocusManager autoFocusManager;
private Rect framingRect;
private Rect framingRectInPreview;
private boolean initialized;
private boolean previewing;
private int requestedFramingRectWidth;
private int requestedFramingRectHeight;
/**
* Preview frames are delivered here, which we pass on to the registered
* handler. Make sure to clear the handler so it will only receive one
* message.
*/
private final PreviewCallback previewCallback;
public CameraManager(Context context) {
this.context = context;
this.configManager = new CameraConfigurationManager(context);
previewCallback = new PreviewCallback(configManager);
}
/**
* Opens the camera driver and initializes the hardware parameters.
*
* @param holder
* The surface object which the camera will draw preview frames
* into.
* @throws IOException
* Indicates the camera driver failed to open.
*/
public synchronized void openDriver(SurfaceHolder holder)
throws IOException {
Camera theCamera = camera;
if (theCamera == null) {
// 获取手机背面的摄像头
theCamera = OpenCameraInterface.open();
if (theCamera == null) {
throw new IOException();
}
camera = theCamera;
}
// 设置摄像头预览view
theCamera.setPreviewDisplay(holder);
if (!initialized) {
initialized = true;
configManager.initFromCameraParameters(theCamera);
if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) {
setManualFramingRect(requestedFramingRectWidth,
requestedFramingRectHeight);
requestedFramingRectWidth = 0;
requestedFramingRectHeight = 0;
}
}
Camera.Parameters parameters = theCamera.getParameters();
String parametersFlattened = parameters == null ? null : parameters
.flatten(); // Save
// these,
// temporarily
try {
configManager.setDesiredCameraParameters(theCamera, false);
}
catch (RuntimeException re) {
// Driver failed
Log.w(TAG,
"Camera rejected parameters. Setting only minimal safe-mode parameters");
Log.i(TAG, "Resetting to saved camera params: "
+ parametersFlattened);
// Reset:
if (parametersFlattened != null) {
parameters = theCamera.getParameters();
parameters.unflatten(parametersFlattened);
try {
theCamera.setParameters(parameters);
configManager.setDesiredCameraParameters(theCamera, true);
}
catch (RuntimeException re2) {
// Well, darn. Give up
Log.w(TAG,
"Camera rejected even safe-mode parameters! No configuration");
}
}
}
}
public synchronized boolean isOpen() {
return camera != null;
}
/**
* Closes the camera driver if still in use.
*/
public synchronized void closeDriver() {
if (camera != null) {
camera.release();
camera = null;
// Make sure to clear these each time we close the camera, so that
// any scanning rect
// requested by intent is forgotten.
framingRect = null;
framingRectInPreview = null;
}
}
/**
* Asks the camera hardware to begin drawing preview frames to the screen.
*/
public synchronized void startPreview() {
Camera theCamera = camera;
if (theCamera != null && !previewing) {
// Starts capturing and drawing preview frames to the screen
// Preview will not actually start until a surface is supplied with
// setPreviewDisplay(SurfaceHolder) or
// setPreviewTexture(SurfaceTexture).
theCamera.startPreview();
previewing = true;
autoFocusManager = new AutoFocusManager(context, camera);
}
}
/**
* Tells the camera to stop drawing preview frames.
*/
public synchronized void stopPreview() {
if (autoFocusManager != null) {
autoFocusManager.stop();
autoFocusManager = null;
}
if (camera != null && previewing) {
camera.stopPreview();
previewCallback.setHandler(null, 0);
previewing = false;
}
}
/**
* Convenience method for
* {@link org.madmatrix.zxing.android.CaptureActivity}
*/
public synchronized void setTorch(boolean newSetting) {
if (newSetting != configManager.getTorchState(camera)) {
if (camera != null) {
if (autoFocusManager != null) {
autoFocusManager.stop();
}
configManager.setTorch(camera, newSetting);
if (autoFocusManager != null) {
autoFocusManager.start();
}
}
}
}
/**
* A single preview frame will be returned to the handler supplied. The data
* will arrive as byte[] in the message.obj field, with width and height
* encoded as message.arg1 and message.arg2, respectively. <br/>
*
* 两个绑定操作:<br/>
* 1:将handler与回调函数绑定;<br/>
* 2:将相机与回调函数绑定<br/>
* 综上,该函数的作用是当相机的预览界面准备就绪后就会调用hander向其发送传入的message
*
* @param handler
* The handler to send the message to.
* @param message
* The what field of the message to be sent.
*/
public synchronized void requestPreviewFrame(Handler handler, int message) {
Camera theCamera = camera;
if (theCamera != null && previewing) {
previewCallback.setHandler(handler, message);
// 绑定相机回调函数,当预览界面准备就绪后会回调Camera.PreviewCallback.onPreviewFrame
theCamera.setOneShotPreviewCallback(previewCallback);
}
}
/**
* Calculates the framing rect which the UI should draw to show the user
* where to place the barcode. This target helps with alignment as well as
* forces the user to hold the device far enough away to ensure the image
* will be in focus.
*
* @return The rectangle to draw on screen in window coordinates.
*/
public synchronized Rect getFramingRect() {
if (framingRect == null) {
if (camera == null) {
return null;
}
Point screenResolution = configManager.getScreenResolution();
if (screenResolution == null) {
// Called early, before init even finished
return null;
}
int width = findDesiredDimensionInRange(screenResolution.x,
MIN_FRAME_WIDTH, MAX_FRAME_WIDTH);
// 将扫描框设置成一个正方形
int height = width;
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width,
topOffset + height);
Log.d(TAG, "Calculated framing rect: " + framingRect);
}
return framingRect;
}
/**
* Target 5/8 of each dimension<br/>
* 计算结果在hardMin~hardMax之间
*
* @param resolution
* @param hardMin
* @param hardMax
* @return
*/
private static int findDesiredDimensionInRange(int resolution, int hardMin,
int hardMax) {
int dim = 5 * resolution / 8; // Target 5/8 of each dimension
if (dim < hardMin) {
return hardMin;
}
if (dim > hardMax) {
return hardMax;
}
return dim;
}
/**
* Like {@link #getFramingRect} but coordinates are in terms of the preview
* frame, not UI / screen.
*/
public synchronized Rect getFramingRectInPreview() {
if (framingRectInPreview == null) {
Rect framingRect = getFramingRect();
if (framingRect == null) {
return null;
}
Rect rect = new Rect(framingRect);
Point cameraResolution = configManager.getCameraResolution();
Point screenResolution = configManager.getScreenResolution();
if (cameraResolution == null || screenResolution == null) {
// Called early, before init even finished
return null;
}
rect.left = rect.left * cameraResolution.y / screenResolution.x;
rect.right = rect.right * cameraResolution.y / screenResolution.x;
rect.top = rect.top * cameraResolution.x / screenResolution.y;
rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;
framingRectInPreview = rect;
Log.d(TAG, "Calculated framingRectInPreview rect: "
+ framingRectInPreview);
Log.d(TAG, "cameraResolution: " + cameraResolution);
Log.d(TAG, "screenResolution: " + screenResolution);
}
return framingRectInPreview;
}
/**
* Allows third party apps to specify the scanning rectangle dimensions,
* rather than determine them automatically based on screen resolution.
*
* @param width
* The width in pixels to scan.
* @param height
* The height in pixels to scan.
*/
public synchronized void setManualFramingRect(int width, int height) {
if (initialized) {
Point screenResolution = configManager.getScreenResolution();
if (width > screenResolution.x) {
width = screenResolution.x;
}
if (height > screenResolution.y) {
height = screenResolution.y;
}
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width,
topOffset + height);
Log.d(TAG, "Calculated manual framing rect: " + framingRect);
framingRectInPreview = null;
}
else {
requestedFramingRectWidth = width;
requestedFramingRectHeight = height;
}
}
/**
* A factory method to build the appropriate LuminanceSource object based on
* the format of the preview buffers, as described by Camera.Parameters.
*
* @param data
* A preview frame.
* @param width
* The width of the image.
* @param height
* The height of the image.
* @return A PlanarYUVLuminanceSource instance.
*/
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data,
int width, int height) {
Rect rect = getFramingRectInPreview();
if (rect == null) {
return null;
}
// Go ahead and assume it's YUV rather than die.
return new PlanarYUVLuminanceSource(data, width, height, rect.left,
rect.top, rect.width(), rect.height(), false);
}
/**
* 焦点放小
*/
public void zoomOut() {
if (camera != null && camera.getParameters().isZoomSupported()) {
Camera.Parameters parameters = camera.getParameters();
if (parameters.getZoom() <= 0) {
return;
}
parameters.setZoom(parameters.getZoom() - 1);
camera.setParameters(parameters);
}
}
/**
* 焦点放大
*/
public void zoomIn() {
if (camera != null && camera.getParameters().isZoomSupported()) {
Camera.Parameters parameters = camera.getParameters();
if (parameters.getZoom() >= parameters.getMaxZoom()) {
return;
}
parameters.setZoom(parameters.getZoom() + 1);
camera.setParameters(parameters);
}
}
/*
* 缩放
*
* @param scale
*/
public void setCameraZoom(int scale) {
if (camera != null && camera.getParameters().isZoomSupported()
&& scale <= camera.getParameters().getMaxZoom() && scale >= 0) {
Camera.Parameters parameters = camera.getParameters();
parameters.setZoom(scale);
camera.setParameters(parameters);
}
}
}
================================================
FILE: src/cn/hugo/android/scanner/camera/FrontLightMode.java
================================================
/*
* Copyright (C) 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.camera;
import android.content.SharedPreferences;
import cn.hugo.android.scanner.config.Config;
/**
* Enumerates settings of the prefernce controlling the front light.
*/
public enum FrontLightMode {
/** Always on. */
ON,
/** On only when ambient light is low. */
AUTO,
/** Always off. */
OFF;
private static FrontLightMode parse(String modeString) {
return modeString == null ? OFF : valueOf(modeString);
}
public static FrontLightMode readPref(SharedPreferences sharedPrefs) {
return parse(sharedPrefs.getString(
Config.KEY_FRONT_LIGHT_MODE, null));
}
}
================================================
FILE: src/cn/hugo/android/scanner/camera/OpenCameraInterface.java
================================================
/*
* Copyright (C) 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.camera;
import android.hardware.Camera;
import android.util.Log;
/**
* 该类用于检测手机上摄像头的个数,如果有两个摄像头,则取背面的摄像头
*/
public final class OpenCameraInterface {
private static final String TAG = OpenCameraInterface.class.getName();
private OpenCameraInterface() {
}
/**
* Opens a rear-facing camera with {@link Camera#open(int)}, if one exists,
* or opens camera 0.
*/
public static Camera open() {
int numCameras = Camera.getNumberOfCameras();
if (numCameras == 0) {
Log.w(TAG, "No cameras!");
return null;
}
int index = 0;
while (index < numCameras) {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
Camera.getCameraInfo(index, cameraInfo);
// CAMERA_FACING_BACK:手机背面的摄像头
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
break;
}
index++;
}
Camera camera;
if (index < numCameras) {
Log.i(TAG, "Opening camera #" + index);
camera = Camera.open(index);
} else {
Log.i(TAG, "No camera facing back; returning camera #0");
camera = Camera.open(0);
}
return camera;
}
}
================================================
FILE: src/cn/hugo/android/scanner/camera/PreviewCallback.java
================================================
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.camera;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
* 该类的作用是在预览界面加载好后向ui线程发消息
*/
final class PreviewCallback implements Camera.PreviewCallback {
private static final String TAG = PreviewCallback.class.getSimpleName();
private final CameraConfigurationManager configManager;
private Handler previewHandler;
private int previewMessage;
PreviewCallback(CameraConfigurationManager configManager) {
this.configManager = configManager;
}
/**
* 绑定handler,用于发消息到ui线程
*
* @param previewHandler
* @param previewMessage
*/
void setHandler(Handler previewHandler, int previewMessage) {
this.previewHandler = previewHandler;
this.previewMessage = previewMessage;
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
Point cameraResolution = configManager.getCameraResolution();
Handler thePreviewHandler = previewHandler;
if (cameraResolution != null && thePreviewHandler != null) {
Message message = thePreviewHandler.obtainMessage(previewMessage, cameraResolution.x, cameraResolution.y,
data);
message.sendToTarget();
previewHandler = null;
} else {
Log.d(TAG, "Got preview callback, but no handler or resolution available");
}
}
}
================================================
FILE: src/cn/hugo/android/scanner/common/BitmapUtils.java
================================================
package cn.hugo.android.scanner.common;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class BitmapUtils {
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap getCompressedBitmap(String path) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, 480, 800);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
}
================================================
FILE: src/cn/hugo/android/scanner/common/Runnable.java
================================================
package cn.hugo.android.scanner.common;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;
/**
* 兼容低版本的子线程开启任务
*
* @author hugo
*
*/
public class Runnable {
@SuppressLint("NewApi")
@SuppressWarnings("unchecked")
public static void execAsync(AsyncTask<?, ?, ?> task) {
if (Build.VERSION.SDK_INT >= 11) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else {
task.execute();
}
}
}
================================================
FILE: src/cn/hugo/android/scanner/config/Config.java
================================================
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.config;
/**
* The main settings activity.
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/
public final class Config {
public static final String KEY_DECODE_1D = "preferences_decode_1D";
public static final String KEY_DECODE_1D_PRODUCT = "preferences_decode_1D_product";
public static final String KEY_DECODE_1D_INDUSTRIAL = "preferences_decode_1D_industrial";
public static final String KEY_DECODE_QR = "preferences_decode_QR";
public static final String KEY_DECODE_DATA_MATRIX = "preferences_decode_Data_Matrix";
public static final String KEY_DECODE_AZTEC = "preferences_decode_Aztec";
public static final String KEY_DECODE_PDF417 = "preferences_decode_PDF417";
public static final String KEY_CUSTOM_PRODUCT_SEARCH = "preferences_custom_product_search";
public static final String KEY_PLAY_BEEP = "preferences_play_beep";
public static final String KEY_VIBRATE = "preferences_vibrate";
public static final String KEY_COPY_TO_CLIPBOARD = "preferences_copy_to_clipboard";
public static final String KEY_FRONT_LIGHT_MODE = "preferences_front_light_mode";
public static final String KEY_BULK_MODE = "preferences_bulk_mode";
public static final String KEY_REMEMBER_DUPLICATES = "preferences_remember_duplicates";
public static final String KEY_SUPPLEMENTAL = "preferences_supplemental";
public static final String KEY_AUTO_FOCUS = "preferences_auto_focus";
public static final String KEY_INVERT_SCAN = "preferences_invert_scan";
public static final String KEY_SEARCH_COUNTRY = "preferences_search_country";
public static final String KEY_DISABLE_AUTO_ORIENTATION = "preferences_orientation";
public static final String KEY_DISABLE_CONTINUOUS_FOCUS = "preferences_disable_continuous_focus";
public static final String KEY_DISABLE_EXPOSURE = "preferences_disable_exposure";
public static final String KEY_DISABLE_METERING = "preferences_disable_metering";
public static final String KEY_DISABLE_BARCODE_SCENE_MODE = "preferences_disable_barcode_scene_mode";
public static final String KEY_AUTO_OPEN_WEB = "preferences_auto_open_web";
}
================================================
FILE: src/cn/hugo/android/scanner/decode/BitmapDecoder.java
================================================
package cn.hugo.android.scanner.decode;
import java.util.Hashtable;
import java.util.Vector;
import android.content.Context;
import android.graphics.Bitmap;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
/**
* 从bitmap解码
*
* @author hugo
*
*/
public class BitmapDecoder {
MultiFormatReader multiFormatReader;
public BitmapDecoder(Context context) {
multiFormatReader = new MultiFormatReader();
// 解码的参数
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(
2);
// 可以解析的编码类型
Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();
if (decodeFormats == null || decodeFormats.isEmpty()) {
decodeFormats = new Vector<BarcodeFormat>();
// 这里设置可扫描的类型,我这里选择了都支持
decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
}
hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
// 设置继续的字符编码格式为UTF8
hints.put(DecodeHintType.CHARACTER_SET, "UTF8");
// 设置解析配置参数
multiFormatReader.setHints(hints);
}
/**
* 获取解码结果
*
* @param bitmap
* @return
*/
public Result getRawResult(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
try {
return multiFormatReader.decodeWithState(new BinaryBitmap(
new HybridBinarizer(new BitmapLuminanceSource(bitmap))));
}
catch (NotFoundException e) {
e.printStackTrace();
}
return null;
}
}
================================================
FILE: src/cn/hugo/android/scanner/decode/BitmapLuminanceSource.java
================================================
package cn.hugo.android.scanner.decode;
import android.graphics.Bitmap;
import com.google.zxing.LuminanceSource;
public class BitmapLuminanceSource extends LuminanceSource {
private byte bitmapPixels[];
protected BitmapLuminanceSource(Bitmap bitmap) {
super(bitmap.getWidth(), bitmap.getHeight());
// 首先,要取得该图片的像素数组内容
int[] data = new int[bitmap.getWidth() * bitmap.getHeight()];
this.bitmapPixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(data, 0, getWidth(), 0, 0, getWidth(), getHeight());
// 将int数组转换为byte数组,也就是取像素值中蓝色值部分作为辨析内容
for (int i = 0; i < data.length; i++) {
this.bitmapPixels[i] = (byte) data[i];
}
}
@Override
public byte[] getMatrix() {
// 返回我们生成好的像素数据
return bitmapPixels;
}
@Override
public byte[] getRow(int y, byte[] row) {
// 这里要得到指定行的像素数据
System.arraycopy(bitmapPixels, y * getWidth(), row, 0, getWidth());
return row;
}
}
================================================
FILE: src/cn/hugo/android/scanner/decode/CaptureActivityHandler.java
================================================
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.decode;
import java.util.Collection;
import java.util.Map;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Browser;
import android.util.Log;
import cn.hugo.android.scanner.CaptureActivity;
import cn.hugo.android.scanner.R;
import cn.hugo.android.scanner.camera.CameraManager;
import cn.hugo.android.scanner.view.ViewfinderResultPointCallback;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
/**
* This class handles all the messaging which comprises the state machine for
* capture.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class CaptureActivityHandler extends Handler {
private static final String TAG = CaptureActivityHandler.class
.getSimpleName();
private final CaptureActivity activity;
/**
* 真正负责扫描任务的核心线程
*/
private final DecodeThread decodeThread;
private State state;
private final CameraManager cameraManager;
/**
* 当前扫描的状态
*/
private enum State {
/**
* 预览
*/
PREVIEW,
/**
* 扫描成功
*/
SUCCESS,
/**
* 结束扫描
*/
DONE
}
public CaptureActivityHandler(CaptureActivity activity,
Collection<BarcodeFormat> decodeFormats,
Map<DecodeHintType, ?> baseHints, String characterSet,
CameraManager cameraManager) {
this.activity = activity;
// 启动扫描线程
decodeThread = new DecodeThread(activity, decodeFormats, baseHints,
characterSet, new ViewfinderResultPointCallback(
activity.getViewfinderView()));
decodeThread.start();
state = State.SUCCESS;
// Start ourselves capturing previews and decoding.
this.cameraManager = cameraManager;
// 开启相机预览界面
cameraManager.startPreview();
restartPreviewAndDecode();
}
@Override
public void handleMessage(Message message) {
switch (message.what) {
case R.id.restart_preview: // 准备进行下一次扫描
Log.d(TAG, "Got restart preview message");
restartPreviewAndDecode();
break;
case R.id.decode_succeeded:
Log.d(TAG, "Got decode succeeded message");
state = State.SUCCESS;
Bundle bundle = message.getData();
Bitmap barcode = null;
float scaleFactor = 1.0f;
if (bundle != null) {
byte[] compressedBitmap = bundle
.getByteArray(DecodeThread.BARCODE_BITMAP);
if (compressedBitmap != null) {
barcode = BitmapFactory.decodeByteArray(
compressedBitmap, 0, compressedBitmap.length,
null);
// Mutable copy:
barcode = barcode.copy(Bitmap.Config.ARGB_8888, true);
}
scaleFactor = bundle
.getFloat(DecodeThread.BARCODE_SCALED_FACTOR);
}
activity.handleDecode((Result) message.obj, barcode,
scaleFactor);
break;
case R.id.decode_failed:
// We're decoding as fast as possible, so when one decode fails,
// start another.
state = State.PREVIEW;
cameraManager.requestPreviewFrame(decodeThread.getHandler(),
R.id.decode);
break;
case R.id.return_scan_result:
Log.d(TAG, "Got return scan result message");
activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
activity.finish();
break;
case R.id.launch_product_query:
Log.d(TAG, "Got product query message");
String url = (String) message.obj;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setData(Uri.parse(url));
/**
* 这段代码是zxing项目组想要用chrome打开浏览器浏览url
*/
ResolveInfo resolveInfo = activity.getPackageManager()
.resolveActivity(intent,
PackageManager.MATCH_DEFAULT_ONLY);
String browserPackageName = null;
if (resolveInfo != null && resolveInfo.activityInfo != null) {
browserPackageName = resolveInfo.activityInfo.packageName;
Log.d(TAG, "Using browser in package " + browserPackageName);
}
// Needed for default Android browser / Chrome only apparently
if ("com.android.browser".equals(browserPackageName)
|| "com.android.chrome".equals(browserPackageName)) {
intent.setPackage(browserPackageName);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Browser.EXTRA_APPLICATION_ID,
browserPackageName);
}
try {
activity.startActivity(intent);
}
catch (ActivityNotFoundException ignored) {
Log.w(TAG, "Can't find anything to handle VIEW of URI "
+ url);
}
break;
}
}
public void quitSynchronously() {
state = State.DONE;
cameraManager.stopPreview();
Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit);
quit.sendToTarget();
try {
// Wait at most half a second; should be enough time, and onPause()
// will timeout quickly
decodeThread.join(500L);
}
catch (InterruptedException e) {
// continue
}
// Be absolutely sure we don't send any queued up messages
removeMessages(R.id.decode_succeeded);
removeMessages(R.id.decode_failed);
}
/**
* 完成一次扫描后,只需要再调用此方法即可
*/
private void restartPreviewAndDecode() {
if (state == State.SUCCESS) {
state = State.PREVIEW;
// 向decodeThread绑定的handler(DecodeHandler)发送解码消息
cameraManager.requestPreviewFrame(decodeThread.getHandler(),
R.id.decode);
activity.drawViewfinder();
}
}
}
================================================
FILE: src/cn/hugo/android/scanner/decode/DecodeFormatManager.java
================================================
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.decode;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.regex.Pattern;
import android.content.Intent;
import android.net.Uri;
import cn.hugo.android.scanner.Intents;
import com.google.zxing.BarcodeFormat;
final class DecodeFormatManager {
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
static final Collection<BarcodeFormat> PRODUCT_FORMATS;
static final Collection<BarcodeFormat> ONE_D_FORMATS;
static final Collection<BarcodeFormat> QR_CODE_FORMATS = EnumSet
.of(BarcodeFormat.QR_CODE);
static final Collection<BarcodeFormat> DATA_MATRIX_FORMATS = EnumSet
.of(BarcodeFormat.DATA_MATRIX);
static {
PRODUCT_FORMATS = EnumSet.of(BarcodeFormat.UPC_A, BarcodeFormat.UPC_E,
BarcodeFormat.EAN_13, BarcodeFormat.EAN_8,
BarcodeFormat.RSS_14, BarcodeFormat.RSS_EXPANDED);
ONE_D_FORMATS = EnumSet.of(BarcodeFormat.CODE_39,
BarcodeFormat.CODE_93, BarcodeFormat.CODE_128,
BarcodeFormat.ITF, BarcodeFormat.CODABAR);
ONE_D_FORMATS.addAll(PRODUCT_FORMATS);
}
private DecodeFormatManager() {
}
static Collection<BarcodeFormat> parseDecodeFormats(Intent intent) {
Iterable<String> scanFormats = null;
CharSequence scanFormatsString = intent
.getStringExtra(Intents.Scan.FORMATS);
if (scanFormatsString != null) {
scanFormats = Arrays.asList(COMMA_PATTERN.split(scanFormatsString));
}
return parseDecodeFormats(scanFormats,
intent.getStringExtra(Intents.Scan.MODE));
}
static Collection<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
List<String> formats = inputUri
.getQueryParameters(Intents.Scan.FORMATS);
if (formats != null && formats.size() == 1 && formats.get(0) != null) {
formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
}
return parseDecodeFormats(formats,
inputUri.getQueryParameter(Intents.Scan.MODE));
}
private static Collection<BarcodeFormat> parseDecodeFormats(
Iterable<String> scanFormats, String decodeMode) {
if (scanFormats != null) {
Collection<BarcodeFormat> formats = EnumSet
.noneOf(BarcodeFormat.class);
try {
for (String format : scanFormats) {
formats.add(BarcodeFormat.valueOf(format));
}
return formats;
}
catch (IllegalArgumentException iae) {
// ignore it then
}
}
if (decodeMode != null) {
if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
return PRODUCT_FORMATS;
}
if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
return QR_CODE_FORMATS;
}
if (Intents.Scan.DATA_MATRIX_MODE.equals(decodeMode)) {
return DATA_MATRIX_FORMATS;
}
if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
return ONE_D_FORMATS;
}
}
return null;
}
}
================================================
FILE: src/cn/hugo/android/scanner/decode/DecodeHandler.java
================================================
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.decode;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import cn.hugo.android.scanner.CaptureActivity;
import cn.hugo.android.scanner.R;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
final class DecodeHandler extends Handler {
private static final String TAG = DecodeHandler.class.getSimpleName();
private final CaptureActivity activity;
private final MultiFormatReader multiFormatReader;
private boolean running = true;
DecodeHandler(CaptureActivity activity, Map<DecodeHintType, Object> hints) {
multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(hints);
this.activity = activity;
}
@Override
public void handleMessage(Message message) {
if (!running) {
return;
}
switch (message.what) {
case R.id.decode:
decode((byte[]) message.obj, message.arg1, message.arg2);
break;
case R.id.quit:
running = false;
Looper.myLooper().quit();
break;
}
}
/**
* Decode the data within the viewfinder rectangle, and time how long it
* took. For efficiency, reuse the same reader objects from one decode to
* the next.
*
* @param data
* The YUV preview frame.
* @param width
* The width of the preview frame.
* @param height
* The height of the preview frame.
*/
private void decode(byte[] data, int width, int height) {
long start = System.currentTimeMillis();
Result rawResult = null;
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[x * height + height - y - 1] = data[x + y * width];
}
int tmp = width;
width = height;
height = tmp;
PlanarYUVLuminanceSource source = activity.getCameraManager()
.buildLuminanceSource(rotatedData, width, height);
if (source != null) {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
// 预览界面最终取到的是个bitmap,然后对其进行解码
rawResult = multiFormatReader.decodeWithState(bitmap);
}
catch (ReaderException re) {
// continue
}
finally {
multiFormatReader.reset();
}
}
Handler handler = activity.getHandler();
if (rawResult != null) {
// Don't log the barcode contents for security.
long end = System.currentTimeMillis();
Log.d(TAG, "Found barcode in " + (end - start) + " ms");
if (handler != null) {
Message message = Message.obtain(handler,
R.id.decode_succeeded, rawResult);
Bundle bundle = new Bundle();
bundleThumbnail(source, bundle);
message.setData(bundle);
message.sendToTarget();
}
}
else {
if (handler != null) {
Message message = Message.obtain(handler, R.id.decode_failed);
message.sendToTarget();
}
}
}
private static void bundleThumbnail(PlanarYUVLuminanceSource source,
Bundle bundle) {
int[] pixels = source.renderThumbnail();
int width = source.getThumbnailWidth();
int height = source.getThumbnailHeight();
Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height,
Bitmap.Config.ARGB_8888);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
bundle.putByteArray(DecodeThread.BARCODE_BITMAP, out.toByteArray());
bundle.putFloat(DecodeThread.BARCODE_SCALED_FACTOR, (float) width
/ source.getWidth());
}
}
================================================
FILE: src/cn/hugo/android/scanner/decode/DecodeThread.java
================================================
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.decode;
import java.util.Collection;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import cn.hugo.android.scanner.CaptureActivity;
import cn.hugo.android.scanner.config.Config;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.ResultPointCallback;
/**
* This thread does all the heavy lifting of decoding the images.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
final class DecodeThread extends Thread {
public static final String BARCODE_BITMAP = "barcode_bitmap";
public static final String BARCODE_SCALED_FACTOR = "barcode_scaled_factor";
private final CaptureActivity activity;
private final Map<DecodeHintType, Object> hints;
private Handler handler;
private final CountDownLatch handlerInitLatch;
DecodeThread(CaptureActivity activity,
Collection<BarcodeFormat> decodeFormats,
Map<DecodeHintType, ?> baseHints, String characterSet,
ResultPointCallback resultPointCallback) {
this.activity = activity;
handlerInitLatch = new CountDownLatch(1);
hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
if (baseHints != null) {
hints.putAll(baseHints);
}
// The prefs can't change while the thread is running, so pick them up
// once here.
if (decodeFormats == null || decodeFormats.isEmpty()) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(activity);
decodeFormats = EnumSet.noneOf(BarcodeFormat.class);
if (prefs.getBoolean(Config.KEY_DECODE_1D, false)) {
decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
}
if (prefs.getBoolean(Config.KEY_DECODE_QR, false)) {
decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
}
if (prefs.getBoolean(Config.KEY_DECODE_DATA_MATRIX,
false)) {
decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
}
}
hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
if (characterSet != null) {
hints.put(DecodeHintType.CHARACTER_SET, characterSet);
}
hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK,
resultPointCallback);
Log.i("DecodeThread", "Hints: " + hints);
}
Handler getHandler() {
try {
handlerInitLatch.await();
}
catch (InterruptedException ie) {
// continue?
}
return handler;
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity, hints);
handlerInitLatch.countDown();
Looper.loop();
}
}
================================================
FILE: src/cn/hugo/android/scanner/view/ViewfinderResultPointCallback.java
================================================
/*
* Copyright (C) 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hugo.android.scanner.view;
import com.google.zxing.ResultPoint;
import com.google.zxing.ResultPointCallback;
public final class ViewfinderResultPointCallback implements ResultPointCallback {
private final ViewfinderView viewfinderView;
public ViewfinderResultPointCallback(ViewfinderView viewfinderView) {
this.viewfinderView = viewfinderView;
}
@Override
public void foundPossibleResultPoint(ResultPoint point) {
viewfinderView.addPossibleResultPoint(point);
}
}
================================================
FILE: src/cn/hugo/android/scanner/view/ViewfinderView.java
================================================
package cn.hugo.android.scanner.view;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;
import cn.hugo.android.scanner.R;
import cn.hugo.android.scanner.camera.CameraManager;
import com.google.zxing.ResultPoint;
/**
* This view is overlaid on top of the camera preview. It adds the viewfinder
* rectangle and partial transparency outside it, as well as the laser scanner
* animation and result points.
*
* <br/>
* <br/>
* 该视图是覆盖在相机的预览视图之上的一层视图。扫描区构成原理,其实是在预览视图上画四块遮罩层,
* 中间留下的部分保持透明,并画上一条激光线,实际上该线条就是展示而已,与扫描功能没有任何关系。
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class ViewfinderView extends View {
/**
* 刷新界面的时间
*/
private static final long ANIMATION_DELAY = 10L;
private static final int OPAQUE = 0xFF;
private int CORNER_PADDING;
/**
* 扫描框中的中间线的宽度
*/
private static int MIDDLE_LINE_WIDTH;
/**
* 扫描框中的中间线的与扫描框左右的间隙
*/
private static int MIDDLE_LINE_PADDING;
/**
* 中间那条线每次刷新移动的距离
*/
private static final int SPEEN_DISTANCE = 10;
/**
* 画笔对象的引用
*/
private Paint paint;
/**
* 中间滑动线的最顶端位置
*/
private int slideTop;
/**
* 中间滑动线的最底端位置
*/
private int slideBottom;
private static final int MAX_RESULT_POINTS = 20;
private Bitmap resultBitmap;
/**
* 遮掩层的颜色
*/
private final int maskColor;
private final int resultColor;
private final int resultPointColor;
private List<ResultPoint> possibleResultPoints;
private List<ResultPoint> lastPossibleResultPoints;
/**
* 第一次绘制控件
*/
boolean isFirst = true;
private CameraManager cameraManager;
// This constructor is used when the class is built from an XML resource.
public ViewfinderView(Context context, AttributeSet attrs) {
super(context, attrs);
CORNER_PADDING = dip2px(context, 0.0F);
MIDDLE_LINE_PADDING = dip2px(context, 20.0F);
MIDDLE_LINE_WIDTH = dip2px(context, 3.0F);
paint = new Paint(Paint.ANTI_ALIAS_FLAG); // 开启反锯齿
Resources resources = getResources();
maskColor = resources.getColor(R.color.viewfinder_mask); // 遮掩层颜色
resultColor = resources.getColor(R.color.result_view);
resultPointColor = resources.getColor(R.color.possible_result_points);
possibleResultPoints = new ArrayList<ResultPoint>(5);
lastPossibleResultPoints = null;
}
public void setCameraManager(CameraManager cameraManager) {
this.cameraManager = cameraManager;
}
@Override
public void onDraw(Canvas canvas) {
if (cameraManager == null) {
return; // not ready yet, early draw before done configuring
}
Rect frame = cameraManager.getFramingRect();
if (frame == null) {
return;
}
// 绘制遮掩层
drawCover(canvas, frame);
if (resultBitmap != null) { // 绘制扫描结果的图
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(0xA0);
canvas.drawBitmap(resultBitmap, null, frame, paint);
}
else {
// 画扫描框边上的角
drawRectEdges(canvas, frame);
// 绘制扫描线
drawScanningLine(canvas, frame);
List<ResultPoint> currentPossible = possibleResultPoints;
Collection<ResultPoint> currentLast = lastPossibleResultPoints;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
}
else {
possibleResultPoints = new ArrayList<ResultPoint>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(OPAQUE);
paint.setColor(resultPointColor);
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frame.left + point.getX(), frame.top
+ point.getY(), 6.0f, paint);
}
}
if (currentLast != null) {
paint.setAlpha(OPAQUE / 2);
paint.setColor(resultPointColor);
for (ResultPoint point : currentLast) {
canvas.drawCircle(frame.left + point.getX(), frame.top
+ point.getY(), 3.0f, paint);
}
}
// 只刷新扫描框的内容,其他地方不刷新
postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,
frame.right, frame.bottom);
}
}
/**
* 绘制扫描线
*
* @param canvas
* @param frame
* 扫描框
*/
private void drawScanningLine(Canvas canvas, Rect frame) {
// 初始化中间线滑动的最上边和最下边
if (isFirst) {
isFirst = false;
slideTop = frame.top;
slideBottom = frame.bottom;
}
// 绘制中间的线,每次刷新界面,中间的线往下移动SPEEN_DISTANCE
slideTop += SPEEN_DISTANCE;
if (slideTop >= slideBottom) {
slideTop = frame.top;
}
// 从图片资源画扫描线
Rect lineRect = new Rect();
lineRect.left = frame.left + MIDDLE_LINE_PADDING;
lineRect.right = frame.right - MIDDLE_LINE_PADDING;
lineRect.top = slideTop;
lineRect.bottom = (slideTop + MIDDLE_LINE_WIDTH);
canvas.drawBitmap(((BitmapDrawable) (BitmapDrawable) getResources()
.getDrawable(R.drawable.scan_laser)).getBitmap(), null,
lineRect, paint);
}
/**
* 绘制遮掩层
*
* @param canvas
* @param frame
*/
private void drawCover(Canvas canvas, Rect frame) {
// 获取屏幕的宽和高
int width = canvas.getWidth();
int height = canvas.getHeight();
// Draw the exterior (i.e. outside the framing rect) darkened
paint.setColor(resultBitmap != null ? resultColor : maskColor);
// 画出扫描框外面的阴影部分,共四个部分,扫描框的上面到屏幕上面,扫描框的下面到屏幕下面
// 扫描框的左边面到屏幕左边,扫描框的右边到屏幕右边
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1,
paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
}
/**
* 描绘方形的四个角
*
* @param canvas
* @param frame
*/
private void drawRectEdges(Canvas canvas, Rect frame) {
paint.setColor(Color.WHITE);
paint.setAlpha(OPAQUE);
Resources resources = getResources();
/**
* 这些资源可以用缓存进行管理,不需要每次刷新都新建
*/
Bitmap bitmapCornerTopleft = BitmapFactory.decodeResource(resources,
R.drawable.scan_corner_top_left);
Bitmap bitmapCornerTopright = BitmapFactory.decodeResource(resources,
R.drawable.scan_corner_top_right);
Bitmap bitmapCornerBottomLeft = BitmapFactory.decodeResource(resources,
R.drawable.scan_corner_bottom_left);
Bitmap bitmapCornerBottomRight = BitmapFactory.decodeResource(
resources, R.drawable.scan_corner_bottom_right);
canvas.drawBitmap(bitmapCornerTopleft, frame.left + CORNER_PADDING,
frame.top + CORNER_PADDING, paint);
canvas.drawBitmap(bitmapCornerTopright, frame.right - CORNER_PADDING
- bitmapCornerTopright.getWidth(), frame.top + CORNER_PADDING,
paint);
canvas.drawBitmap(bitmapCornerBottomLeft, frame.left + CORNER_PADDING,
2 + (frame.bottom - CORNER_PADDING - bitmapCornerBottomLeft
.getHeight()), paint);
canvas.drawBitmap(bitmapCornerBottomRight, frame.right - CORNER_PADDING
- bitmapCornerBottomRight.getWidth(), 2 + (frame.bottom
- CORNER_PADDING - bitmapCornerBottomRight.getHeight()), paint);
bitmapCornerTopleft.recycle();
bitmapCornerTopleft = null;
bitmapCornerTopright.recycle();
bitmapCornerTopright = null;
bitmapCornerBottomLeft.recycle();
bitmapCornerBottomLeft = null;
bitmapCornerBottomRight.recycle();
bitmapCornerBottomRight = null;
}
public void drawViewfinder() {
Bitmap resultBitmap = this.resultBitmap;
this.resultBitmap = null;
if (resultBitmap != null) {
resultBitmap.recycle();
}
invalidate();
}
/**
* Draw a bitmap with the result points highlighted instead of the live
* scanning display.
*
* @param barcode
* An image of the decoded barcode.
*/
public void drawResultBitmap(Bitmap barcode) {
resultBitmap = barcode;
invalidate();
}
public void addPossibleResultPoint(ResultPoint point) {
List<ResultPoint> points = possibleResultPoints;
synchronized (points) {
points.add(point);
int size = points.size();
if (size > MAX_RESULT_POINTS) {
// trim it
points.subList(0, size - MAX_RESULT_POINTS / 2).clear();
}
}
}
/**
* dp转px
*
* @param context
* @param dipValue
* @return
*/
public int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
}
gitextract_xyz60noi/
├── .classpath
├── .gitignore
├── .project
├── AndroidManifest.xml
├── LICENSE
├── README.md
├── doc/
│ └── readme.txt
├── libs/
│ ├── android-core-3.1.1-SNAPSHOT.jar
│ ├── android-support-v4.jar
│ └── core-3.1.1-SNAPSHOT.jar
├── lint.xml
├── proguard-project.txt
├── project.properties
├── res/
│ ├── drawable/
│ │ ├── scan_flashlight.xml
│ │ ├── scan_history.xml
│ │ ├── scan_photo.xml
│ │ ├── seekbar_bg.xml
│ │ └── seekbar_style.xml
│ ├── layout/
│ │ └── capture.xml
│ ├── raw/
│ │ └── beep.ogg
│ ├── values/
│ │ ├── colors.xml
│ │ ├── ids.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ ├── values-v11/
│ │ └── styles.xml
│ └── values-v14/
│ └── styles.xml
└── src/
└── cn/
└── hugo/
└── android/
└── scanner/
├── AmbientLightManager.java
├── BeepManager.java
├── CaptureActivity.java
├── FinishListener.java
├── InactivityTimer.java
├── IntentSource.java
├── Intents.java
├── camera/
│ ├── AutoFocusManager.java
│ ├── CameraConfigurationManager.java
│ ├── CameraManager.java
│ ├── FrontLightMode.java
│ ├── OpenCameraInterface.java
│ └── PreviewCallback.java
├── common/
│ ├── BitmapUtils.java
│ └── Runnable.java
├── config/
│ └── Config.java
├── decode/
│ ├── BitmapDecoder.java
│ ├── BitmapLuminanceSource.java
│ ├── CaptureActivityHandler.java
│ ├── DecodeFormatManager.java
│ ├── DecodeHandler.java
│ └── DecodeThread.java
└── view/
├── ViewfinderResultPointCallback.java
└── ViewfinderView.java
SYMBOL INDEX (165 symbols across 24 files)
FILE: src/cn/hugo/android/scanner/AmbientLightManager.java
class AmbientLightManager (line 36) | final class AmbientLightManager implements SensorEventListener {
method AmbientLightManager (line 49) | AmbientLightManager(Context context) {
method start (line 53) | void start(CameraManager cameraManager) {
method stop (line 68) | void stop() {
method onSensorChanged (line 81) | @Override
method onAccuracyChanged (line 94) | @Override
FILE: src/cn/hugo/android/scanner/BeepManager.java
class BeepManager (line 35) | final class BeepManager implements MediaPlayer.OnCompletionListener,
method BeepManager (line 52) | BeepManager(Activity activity) {
method updatePrefs (line 61) | synchronized void updatePrefs() {
method playBeepSoundAndVibrate (line 78) | synchronized void playBeepSoundAndVibrate() {
method shouldBeep (line 89) | private static boolean shouldBeep(SharedPreferences prefs, Context act...
method buildMediaPlayer (line 102) | private MediaPlayer buildMediaPlayer(Context activity) {
method onCompletion (line 124) | @Override
method onError (line 130) | @Override
method close (line 150) | public synchronized void close() {
FILE: src/cn/hugo/android/scanner/CaptureActivity.java
class CaptureActivity (line 49) | public final class CaptureActivity extends Activity implements
class MyHandler (line 126) | static class MyHandler extends Handler {
method MyHandler (line 130) | public MyHandler(Activity activity) {
method handleMessage (line 134) | @Override
method onCreate (line 158) | @Override
method onResume (line 178) | @Override
method onPause (line 236) | @Override
method onDestroy (line 256) | @Override
method onKeyDown (line 262) | @Override
method onActivityResult (line 288) | @Override
method surfaceCreated (line 347) | @Override
method surfaceChanged (line 359) | @Override
method surfaceDestroyed (line 365) | @Override
method handleDecode (line 381) | public void handleDecode(Result rawResult, Bitmap barcode, float scale...
method restartPreviewAfterDelay (line 399) | public void restartPreviewAfterDelay(long delayMS) {
method getViewfinderView (line 406) | public ViewfinderView getViewfinderView() {
method getHandler (line 410) | public Handler getHandler() {
method getCameraManager (line 414) | public CameraManager getCameraManager() {
method resetStatusView (line 418) | private void resetStatusView() {
method drawViewfinder (line 423) | public void drawViewfinder() {
method initCamera (line 427) | private void initCamera(SurfaceHolder surfaceHolder) {
method decodeOrStoreSavedBitmap (line 465) | private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
method displayFrameworkBugMessageAndExit (line 483) | private void displayFrameworkBugMessageAndExit() {
method onClick (line 492) | @Override
FILE: src/cn/hugo/android/scanner/FinishListener.java
class FinishListener (line 27) | public final class FinishListener implements DialogInterface.OnClickList...
method FinishListener (line 31) | public FinishListener(Activity activityToFinish) {
method onCancel (line 35) | @Override
method onClick (line 40) | @Override
method run (line 45) | private void run() {
FILE: src/cn/hugo/android/scanner/InactivityTimer.java
class InactivityTimer (line 36) | final class InactivityTimer {
method InactivityTimer (line 56) | InactivityTimer(Activity activity) {
method onActivity (line 66) | synchronized void onActivity() {
method onPause (line 72) | public synchronized void onPause() {
method onResume (line 83) | public synchronized void onResume() {
method cancel (line 98) | private synchronized void cancel() {
method shutdown (line 106) | void shutdown() {
class PowerStatusReceiver (line 113) | private final class PowerStatusReceiver extends BroadcastReceiver {
method onReceive (line 114) | @Override
class InactivityAsyncTask (line 133) | private final class InactivityAsyncTask extends
method doInBackground (line 135) | @Override
FILE: src/cn/hugo/android/scanner/IntentSource.java
type IntentSource (line 19) | enum IntentSource {
FILE: src/cn/hugo/android/scanner/Intents.java
class Intents (line 25) | public final class Intents {
method Intents (line 26) | private Intents() {
class Scan (line 29) | public static final class Scan {
method Scan (line 173) | private Scan() {
class History (line 177) | public static final class History {
method History (line 181) | private History() {
class Encode (line 185) | public static final class Encode {
method Encode (line 219) | private Encode() {
class SearchBookContents (line 223) | public static final class SearchBookContents {
method SearchBookContents (line 239) | private SearchBookContents() {
class WifiConnect (line 243) | public static final class WifiConnect {
method WifiConnect (line 264) | private WifiConnect() {
class Share (line 268) | public static final class Share {
method Share (line 275) | private Share() {
FILE: src/cn/hugo/android/scanner/camera/AutoFocusManager.java
class AutoFocusManager (line 35) | final class AutoFocusManager implements Camera.AutoFocusCallback {
method AutoFocusManager (line 52) | AutoFocusManager(Context context, Camera camera) {
method onAutoFocus (line 64) | @Override
method start (line 72) | synchronized void start() {
method stop (line 86) | synchronized void stop() {
class AutoFocusTask (line 104) | private final class AutoFocusTask extends AsyncTask<Object, Object, Ob...
method doInBackground (line 105) | @Override
FILE: src/cn/hugo/android/scanner/camera/CameraConfigurationManager.java
class CameraConfigurationManager (line 45) | final class CameraConfigurationManager {
method CameraConfigurationManager (line 70) | CameraConfigurationManager(Context context) {
method initFromCameraParameters (line 77) | void initFromCameraParameters(Camera camera) {
method getDisplaySize (line 109) | @SuppressLint("NewApi")
method setDesiredCameraParameters (line 122) | void setDesiredCameraParameters(Camera camera, boolean safeMode) {
method getCameraResolution (line 186) | Point getCameraResolution() {
method getScreenResolution (line 190) | Point getScreenResolution() {
method getTorchState (line 194) | boolean getTorchState(Camera camera) {
method setTorch (line 207) | void setTorch(Camera camera, boolean newSetting) {
method initializeTorch (line 213) | private void initializeTorch(Camera.Parameters parameters,
method doSetTorch (line 219) | private void doSetTorch(Camera.Parameters parameters, boolean newSetting,
method findBestPreviewSizeValue (line 243) | private Point findBestPreviewSizeValue(Camera.Parameters parameters,
method findSettableValue (line 348) | private static String findSettableValue(Collection<String> supportedVa...
FILE: src/cn/hugo/android/scanner/camera/CameraManager.java
class CameraManager (line 41) | public final class CameraManager {
method CameraManager (line 76) | public CameraManager(Context context) {
method openDriver (line 91) | public synchronized void openDriver(SurfaceHolder holder)
method isOpen (line 149) | public synchronized boolean isOpen() {
method closeDriver (line 156) | public synchronized void closeDriver() {
method startPreview (line 171) | public synchronized void startPreview() {
method stopPreview (line 188) | public synchronized void stopPreview() {
method setTorch (line 204) | public synchronized void setTorch(boolean newSetting) {
method requestPreviewFrame (line 233) | public synchronized void requestPreviewFrame(Handler handler, int mess...
method getFramingRect (line 251) | public synchronized Rect getFramingRect() {
method findDesiredDimensionInRange (line 287) | private static int findDesiredDimensionInRange(int resolution, int har...
method getFramingRectInPreview (line 303) | public synchronized Rect getFramingRectInPreview() {
method setManualFramingRect (line 340) | public synchronized void setManualFramingRect(int width, int height) {
method buildLuminanceSource (line 374) | public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data,
method zoomOut (line 388) | public void zoomOut() {
method zoomIn (line 405) | public void zoomIn() {
method setCameraZoom (line 424) | public void setCameraZoom(int scale) {
FILE: src/cn/hugo/android/scanner/camera/FrontLightMode.java
type FrontLightMode (line 25) | public enum FrontLightMode {
method parse (line 34) | private static FrontLightMode parse(String modeString) {
method readPref (line 38) | public static FrontLightMode readPref(SharedPreferences sharedPrefs) {
FILE: src/cn/hugo/android/scanner/camera/OpenCameraInterface.java
class OpenCameraInterface (line 25) | public final class OpenCameraInterface {
method OpenCameraInterface (line 29) | private OpenCameraInterface() {
method open (line 36) | public static Camera open() {
FILE: src/cn/hugo/android/scanner/camera/PreviewCallback.java
class PreviewCallback (line 28) | final class PreviewCallback implements Camera.PreviewCallback {
method PreviewCallback (line 36) | PreviewCallback(CameraConfigurationManager configManager) {
method setHandler (line 46) | void setHandler(Handler previewHandler, int previewMessage) {
method onPreviewFrame (line 51) | @Override
FILE: src/cn/hugo/android/scanner/common/BitmapUtils.java
class BitmapUtils (line 7) | public class BitmapUtils {
method decodeSampledBitmapFromResource (line 9) | public static Bitmap decodeSampledBitmapFromResource(Resources res,
method calculateInSampleSize (line 26) | public static int calculateInSampleSize(BitmapFactory.Options options,
method getCompressedBitmap (line 51) | public static Bitmap getCompressedBitmap(String path) {
FILE: src/cn/hugo/android/scanner/common/Runnable.java
class Runnable (line 13) | public class Runnable {
method execAsync (line 15) | @SuppressLint("NewApi")
FILE: src/cn/hugo/android/scanner/config/Config.java
class Config (line 25) | public final class Config {
FILE: src/cn/hugo/android/scanner/decode/BitmapDecoder.java
class BitmapDecoder (line 23) | public class BitmapDecoder {
method BitmapDecoder (line 27) | public BitmapDecoder(Context context) {
method getRawResult (line 60) | public Result getRawResult(Bitmap bitmap) {
FILE: src/cn/hugo/android/scanner/decode/BitmapLuminanceSource.java
class BitmapLuminanceSource (line 7) | public class BitmapLuminanceSource extends LuminanceSource {
method BitmapLuminanceSource (line 11) | protected BitmapLuminanceSource(Bitmap bitmap) {
method getMatrix (line 25) | @Override
method getRow (line 31) | @Override
FILE: src/cn/hugo/android/scanner/decode/CaptureActivityHandler.java
class CaptureActivityHandler (line 50) | public final class CaptureActivityHandler extends Handler {
type State (line 69) | private enum State {
method CaptureActivityHandler (line 84) | public CaptureActivityHandler(CaptureActivity activity,
method handleMessage (line 107) | @Override
method quitSynchronously (line 188) | public void quitSynchronously() {
method restartPreviewAndDecode (line 211) | private void restartPreviewAndDecode() {
FILE: src/cn/hugo/android/scanner/decode/DecodeFormatManager.java
class DecodeFormatManager (line 31) | final class DecodeFormatManager {
method DecodeFormatManager (line 51) | private DecodeFormatManager() {
method parseDecodeFormats (line 54) | static Collection<BarcodeFormat> parseDecodeFormats(Intent intent) {
method parseDecodeFormats (line 65) | static Collection<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
method parseDecodeFormats (line 75) | private static Collection<BarcodeFormat> parseDecodeFormats(
FILE: src/cn/hugo/android/scanner/decode/DecodeHandler.java
class DecodeHandler (line 39) | final class DecodeHandler extends Handler {
method DecodeHandler (line 49) | DecodeHandler(CaptureActivity activity, Map<DecodeHintType, Object> hi...
method handleMessage (line 55) | @Override
method decode (line 83) | private void decode(byte[] data, int width, int height) {
method bundleThumbnail (line 134) | private static void bundleThumbnail(PlanarYUVLuminanceSource source,
FILE: src/cn/hugo/android/scanner/decode/DecodeThread.java
class DecodeThread (line 42) | final class DecodeThread extends Thread {
method DecodeThread (line 56) | DecodeThread(CaptureActivity activity,
method getHandler (line 96) | Handler getHandler() {
method run (line 106) | @Override
FILE: src/cn/hugo/android/scanner/view/ViewfinderResultPointCallback.java
class ViewfinderResultPointCallback (line 22) | public final class ViewfinderResultPointCallback implements ResultPointC...
method ViewfinderResultPointCallback (line 26) | public ViewfinderResultPointCallback(ViewfinderView viewfinderView) {
method foundPossibleResultPoint (line 30) | @Override
FILE: src/cn/hugo/android/scanner/view/ViewfinderView.java
class ViewfinderView (line 35) | public final class ViewfinderView extends View {
method ViewfinderView (line 98) | public ViewfinderView(Context context, AttributeSet attrs) {
method setCameraManager (line 117) | public void setCameraManager(CameraManager cameraManager) {
method onDraw (line 121) | @Override
method drawScanningLine (line 185) | private void drawScanningLine(Canvas canvas, Rect frame) {
method drawCover (line 218) | private void drawCover(Canvas canvas, Rect frame) {
method drawRectEdges (line 242) | private void drawRectEdges(Canvas canvas, Rect frame) {
method drawViewfinder (line 283) | public void drawViewfinder() {
method drawResultBitmap (line 299) | public void drawResultBitmap(Bitmap barcode) {
method addPossibleResultPoint (line 304) | public void addPossibleResultPoint(ResultPoint point) {
method dip2px (line 323) | public int dip2px(Context context, float dipValue) {
Condensed preview — 50 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (146K chars).
[
{
"path": ".classpath",
"chars": 466,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<classpath>\n\t<classpathentry kind=\"con\" path=\"com.android.ide.eclipse.adt.ANDROID"
},
{
"path": ".gitignore",
"chars": 271,
"preview": "# 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\nbi"
},
{
"path": ".project",
"chars": 817,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<projectDescription>\n\t<name>BarcodeScanner</name>\n\t<comment></comment>\n\t<projects"
},
{
"path": "AndroidManifest.xml",
"chars": 1481,
"preview": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"cn.hugo.android.scanner\"\n android:v"
},
{
"path": "LICENSE",
"chars": 11323,
"preview": "Apache License\n Version 2.0, January 2004\n http://www.apache.org/licens"
},
{
"path": "README.md",
"chars": 500,
"preview": "BarcodeScanner\n==============\n\nAndroid手机客户端关于二维码扫描的源码,使用了zxing 3.1.1代码并对其进行了精简,支持低版本的sdk,实现了二维码和一维码的扫描、从图片解析一维码和二维码,闪光灯、"
},
{
"path": "doc/readme.txt",
"chars": 48,
"preview": "参考文档\nhttp://my.oschina.net/madmatrix/blog/189031"
},
{
"path": "lint.xml",
"chars": 53,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<lint>\n</lint>"
},
{
"path": "proguard-project.txt",
"chars": 781,
"preview": "# To enable ProGuard in your project, edit project.properties\n# to define the proguard.config property as described in t"
},
{
"path": "project.properties",
"chars": 563,
"preview": "# This file is automatically generated by Android Tools.\n# Do not modify this file -- YOUR CHANGES WILL BE ERASED!\n#\n# T"
},
{
"path": "res/drawable/scan_flashlight.xml",
"chars": 292,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n <item "
},
{
"path": "res/drawable/scan_history.xml",
"chars": 274,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n <item "
},
{
"path": "res/drawable/scan_photo.xml",
"chars": 270,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n <item "
},
{
"path": "res/drawable/seekbar_bg.xml",
"chars": 511,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n\n <it"
},
{
"path": "res/drawable/seekbar_style.xml",
"chars": 960,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n\n <it"
},
{
"path": "res/layout/capture.xml",
"chars": 4109,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n andro"
},
{
"path": "res/values/colors.xml",
"chars": 839,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<resources>\n\n <color name=\"contents_text\">#ff000000</color>\n <color name=\"e"
},
{
"path": "res/values/ids.xml",
"chars": 1106,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n Copyright (C) 2008 ZXing authors\n\n Licensed under the Apache License, Versi"
},
{
"path": "res/values/strings.xml",
"chars": 575,
"preview": "<resources>\n\n <string name=\"app_name\">二维条形码扫描</string>\n <string name=\"placeHolder\">placeHolder</string>\n <strin"
},
{
"path": "res/values/styles.xml",
"chars": 680,
"preview": "<resources>\n\n <!--\n Base application theme, dependent on API level. This theme is replaced\n by AppBaseT"
},
{
"path": "res/values-v11/styles.xml",
"chars": 324,
"preview": "<resources>\n\n <!--\n Base application theme for API 11+. This theme completely replaces\n AppBaseTheme fr"
},
{
"path": "res/values-v14/styles.xml",
"chars": 381,
"preview": "<resources>\n\n <!--\n Base application theme for API 14+. This theme completely replaces\n AppBaseTheme fr"
},
{
"path": "src/cn/hugo/android/scanner/AmbientLightManager.java",
"chars": 2832,
"preview": "/*\n * Copyright (C) 2012 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/BeepManager.java",
"chars": 4322,
"preview": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/CaptureActivity.java",
"chars": 13350,
"preview": "package cn.hugo.android.scanner;\n\nimport java.io.IOException;\nimport java.lang.ref.WeakReference;\nimport java.util.Colle"
},
{
"path": "src/cn/hugo/android/scanner/FinishListener.java",
"chars": 1296,
"preview": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/InactivityTimer.java",
"chars": 3599,
"preview": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/IntentSource.java",
"chars": 726,
"preview": "/*\n * Copyright (C) 2011 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/Intents.java",
"chars": 10128,
"preview": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/camera/AutoFocusManager.java",
"chars": 3456,
"preview": "/*\n * Copyright (C) 2012 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/camera/CameraConfigurationManager.java",
"chars": 11103,
"preview": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/camera/CameraManager.java",
"chars": 12107,
"preview": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/camera/FrontLightMode.java",
"chars": 1217,
"preview": "/*\n * Copyright (C) 2012 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/camera/OpenCameraInterface.java",
"chars": 1699,
"preview": "/*\n * Copyright (C) 2012 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/camera/PreviewCallback.java",
"chars": 1940,
"preview": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/common/BitmapUtils.java",
"chars": 1947,
"preview": "package cn.hugo.android.scanner.common;\n\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport an"
},
{
"path": "src/cn/hugo/android/scanner/common/Runnable.java",
"chars": 463,
"preview": "package cn.hugo.android.scanner.common;\n\nimport android.annotation.SuppressLint;\nimport android.os.AsyncTask;\nimport and"
},
{
"path": "src/cn/hugo/android/scanner/config/Config.java",
"chars": 2725,
"preview": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/decode/BitmapDecoder.java",
"chars": 1716,
"preview": "package cn.hugo.android.scanner.decode;\n\nimport java.util.Hashtable;\nimport java.util.Vector;\n\nimport android.content.Co"
},
{
"path": "src/cn/hugo/android/scanner/decode/BitmapLuminanceSource.java",
"chars": 918,
"preview": "package cn.hugo.android.scanner.decode;\n\nimport android.graphics.Bitmap;\n\nimport com.google.zxing.LuminanceSource;\n\npubl"
},
{
"path": "src/cn/hugo/android/scanner/decode/CaptureActivityHandler.java",
"chars": 6153,
"preview": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/decode/DecodeFormatManager.java",
"chars": 3372,
"preview": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/decode/DecodeHandler.java",
"chars": 4371,
"preview": "/*\n * Copyright (C) 2010 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/decode/DecodeThread.java",
"chars": 3316,
"preview": "/*\n * Copyright (C) 2008 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/view/ViewfinderResultPointCallback.java",
"chars": 1094,
"preview": "/*\n * Copyright (C) 2009 ZXing authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may "
},
{
"path": "src/cn/hugo/android/scanner/view/ViewfinderView.java",
"chars": 8327,
"preview": "package cn.hugo.android.scanner.view;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\n"
}
]
// ... and 4 more files (download for full content)
About this extraction
This page contains the full source code of the ThinWonton/BarcodeScanner GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 50 files (125.8 KB), approximately 32.9k tokens, and a symbol index with 165 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.