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
================================================
================================================
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
================================================
BarcodeScannercom.android.ide.eclipse.adt.ResourceManagerBuildercom.android.ide.eclipse.adt.PreCompilerBuilderorg.eclipse.jdt.core.javabuildercom.android.ide.eclipse.adt.ApkBuildercom.android.ide.eclipse.adt.AndroidNatureorg.eclipse.jdt.core.javanature
================================================
FILE: AndroidManifest.xml
================================================
================================================
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
================================================
================================================
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
================================================
================================================
FILE: res/drawable/scan_history.xml
================================================
================================================
FILE: res/drawable/scan_photo.xml
================================================
================================================
FILE: res/drawable/seekbar_bg.xml
================================================
================================================
FILE: res/drawable/seekbar_style.xml
================================================
================================================
FILE: res/layout/capture.xml
================================================
================================================
FILE: res/values/colors.xml
================================================
#ff000000#ffffffff#c0ffbd21#ffc0c0c0#c099cc00#ffffffff#b0000000#ffffffff#00000000#ffcc0000#00000000#99535353#fff6f6f6
================================================
FILE: res/values/ids.xml
================================================
================================================
FILE: res/values/strings.xml
================================================
二维条形码扫描placeHolder+-生成扫描失败建议与镜头保持10CM距离,尽量避免逆光和阴影将条形码或二维码置于取景框内系统会自动扫描取消抱歉,Android相机出现问题。您可能需要重启设备。确定
================================================
FILE: res/values/styles.xml
================================================
================================================
FILE: res/values-v11/styles.xml
================================================
================================================
FILE: res/values-v14/styles.xml
================================================
================================================
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 decodeFormats;
/**
* 【辅助解码的参数(用作MultiFormatReader的参数)】 该参数最终会传入MultiFormatReader,
* 上面的decodeFormats和characterSet最终会先加入到decodeHints中 最终被设置到MultiFormatReader中
* 参考DecodeHandler构造器中如下代码:multiFormatReader.setHints(hints);
*/
private Map 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 activityReference;
public MyHandler(Activity activity) {
activityReference = new WeakReference(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.
*
*
* 该活动监控器全程监控扫描活跃状态,与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