================================================
FILE: .idea/vcs.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
================================================
# YZxing
一款仿微信扫一扫界面,基于zxing实现的扫码库。
### **实现效果** ###
 
### **使用方式** ###
~~首先通过在build.gradle文件中添加如下编译语句将YZxing-lib库添加到项目中。
compile 'com.yangy:YZxing-lib:1.1'~~
(或者在直接把本仓库里面的YZxing库下载下来,添加到项目中。)
然后在点击跳转到扫码界面的点击事件中,调用如下方法:
Intent intent = new Intent(this, ScannerActivity.class);
//这里可以用intent传递一些参数,比如扫码聚焦框尺寸大小,支持的扫码类型。
// //设置扫码框的宽
// intent.putExtra(Constant.EXTRA_SCANNER_FRAME_WIDTH, 400);
// //设置扫码框的高
// intent.putExtra(Constant.EXTRA_SCANNER_FRAME_HEIGHT, 400);
// //设置扫码框距顶部的位置
// intent.putExtra(Constant.EXTRA_SCANNER_FRAME_TOP_PADDING, 100);
// Bundle bundle = new Bundle();
// //设置支持的扫码类型
// bundle.putSerializable(Constant.EXTRA_SCAN_CODE_TYPE, mHashMap);
// intent.putExtras(bundle);
startActivityForResult(intent, RESULT_REQUEST_CODE);
这里可以使用intent传递一些配置参数。支持有设置扫码框的大小,及位置;设置支持的扫码类型。目前支持的自定义配置不多,后续有机会再扩充。 跳转的时候要有startActivityForResult来跳转,这样在扫码成功之后,返回的结果可以在onActivityResult方法中处理代码如下:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RESULT_REQUEST_CODE:
if (data == null) return;
String type = data.getStringExtra(Constant.EXTRA_RESULT_CODE_TYPE);
String content = data.getStringExtra(Constant.EXTRA_RESULT_CONTENT);
Toast.makeText(MainActivity.this,"codeType:" + type
+ "-----content:" + content,Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
----------------------------------------
## **YZxing版本更新说明** ##
目前最新版为v2.2!!
-------------
目前YZxing已经更新到了v2.1 ,更新内容有:
1.修改空指针导致的的闪退bug。
2.添加从相册获取二维码功能(用户可以选择是否使用该功能)。
首先通过在build.gradle文件中添加如下编译语句将YZxing-lib库添加到项目中。
compile 'com.yangy:YZxing-lib:2.1'
(或者在直接把本仓库里面的YZxing库下载下来,添加到项目中。)
使用方式与1.1版本一致,注意的是如需使用**从相册获取二维码功能**则需要在intent中添加是否启用scan_from_pic,默认是FALSE:
**// //设置是否启用从相册获取二维码。
// intent.putExtra(Constant.EXTRA_IS_ENABLE_SCAN_FROM_PIC,true);**
### **从照片获取二维码的效果如下:** ###

## **觉得还不错的就动动手指给个star吧(*^__^*)** ##
## **关于二维码功能的分析请移步至文章** ##
https://blog.csdn.net/qq_34902522/column/info/28769
================================================
FILE: YZxing-lib/.gitignore
================================================
/build
================================================
FILE: YZxing-lib/build.gradle
================================================
apply plugin: 'com.android.library'
apply plugin: 'com.jfrog.bintray'
apply plugin: 'com.github.dcendents.android-maven'
def siteUrl = 'https://github.com/MRYangY/YZxing' // 项目的主页
def gitUrl = 'https://github.com/MRYangY/YZxing.git' // Git仓库的url
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
version = "2.2" //发布版本号
group = "com.yangy" //最终引用形式,如compile 'com.yangy.lfilepicker:1.0.0',其中lfilepicker在后面配置
android {
compileSdkVersion 26
buildToolsVersion "25.0.3"
defaultConfig {
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.google.zxing:core:3.3.0'
}
bintray {
user = properties.getProperty("bintray.user")
key = properties.getProperty("bintray.apikey")
pkg {
repo = 'YZXing'//自己创建的仓库名字
name = 'yzxing'//上传到JCenter的名字,最终引用的名字
websiteUrl = siteUrl
vcsUrl = gitUrl
licenses = ['Apache-2.0']//不能随便写,只能是仓库创建时选择的license type
userOrg = 'yangyulibrary' //自己创建的organization名称
publish = true // 是否是公开项目,公开别人可以引用
version {
name = '2.2'
desc = '基于zxing的扫码库,样式类似于微信扫一扫'//描述,自己定义
released = new Date()
vcsTag = 'v2.2'
attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin']
}
}
configurations = ['archives']
}
install {
repositories.mavenInstaller {
// This generates POM.xml with proper parameters
pom {
project {
packaging 'aar'
// Add your description here
name 'yangy Android'
description 'yangy open library.'
url siteUrl
// Set your license
licenses {
license {
name 'Apache-2.0' //和之前自己定义的协议一致
url 'https://raw.githubusercontent.com/minggo620/Pluto-Android/master/LICENSE'
}
}
developers {
developer {
id 'mryangy423' //填写bintray或者github的用户名
name 'mryangy423' //姓名
email 'mryangy423@gmail.com'//邮箱
}
}
scm {
connection gitUrl
developerConnection gitUrl
url siteUrl
}
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
task javadoc(type: Javadoc) {
failOnError false //必须添加以免出错
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives javadocJar
archives sourcesJar
}
javadoc {
options{
//如果你的项目里面有中文注释的话,必须将格式设置为UTF-8,不然会出现乱码
encoding "UTF-8"
charSet 'UTF-8'
author true
version true
links "http://docs.oracle.com/javase/7/docs/api"
}
}
}
}
================================================
FILE: YZxing-lib/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/yangyu/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# 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 *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
================================================
FILE: YZxing-lib/src/androidTest/java/com/example/qrcode/ExampleInstrumentedTest.java
================================================
package com.example.qrcode;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see Testing documentation
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.qrcode.test", appContext.getPackageName());
}
}
================================================
FILE: YZxing-lib/src/main/AndroidManifest.xml
================================================
================================================
FILE: YZxing-lib/src/main/java/com/example/qrcode/BarcodeActivity.java
================================================
package com.example.qrcode;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import java.util.EnumMap;
import java.util.Map;
/**
* Create by rain
*
* DATE:18-10-26
*
* Describe:
**/
public class BarcodeActivity extends Activity {
private static final String TAG = "BarcodeActivity";
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
private static final int CODE_TYPE_QR_CODE = 0x11;
private static final int CODE_TYPE_CODE_128 = 0x12;
private int mType = CODE_TYPE_QR_CODE;
private EditText mInputContentView;
private Button mEncodeView;
private ImageView mBarcodeImageView;
private RadioGroup mRgCodeType;
private RadioButton mRbQrCode;
private RadioButton mRb128Code;
private Bitmap bitmap;
private Handler mHandler = new Handler(Looper.getMainLooper());
private int smallerDimension;
private int barcodeImageWidth;
private int barcodeImageHeight;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_barcode);
mInputContentView = findViewById(R.id.et_input_content);
mEncodeView = findViewById(R.id.bt_encode);
mEncodeView.setOnClickListener(mEncodeListener);
mBarcodeImageView = findViewById(R.id.barcode_image);
mRgCodeType = findViewById(R.id.rg_code_type);
mRbQrCode = findViewById(R.id.rb_qr_code);
mRb128Code = findViewById(R.id.rb_code_128);
mRgCodeType.setOnCheckedChangeListener(onCheckedChangeListener);
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
int width = displaySize.x;
int height = displaySize.y;
smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 7 / 8;
barcodeImageWidth = smallerDimension;
barcodeImageHeight = smallerDimension;
Log.e(TAG, "onCreate: smallerDimension = " + smallerDimension);
}
private RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
barcodeImageWidth = smallerDimension;
if (checkedId == R.id.rb_qr_code) {
mType = CODE_TYPE_QR_CODE;
barcodeImageHeight = smallerDimension;
} else if (checkedId == R.id.rb_code_128) {
mType = CODE_TYPE_CODE_128;
barcodeImageHeight = smallerDimension / 2;
}
}
};
private View.OnClickListener mEncodeListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = mInputContentView.getText().toString();
if (TextUtils.isEmpty(text)) {
Toast.makeText(BarcodeActivity.this, "请先输入条形码内容!!", Toast.LENGTH_SHORT).show();
return;
}
encode(text);
}
};
private void encode(String content) {
Log.e(TAG, "encode: content = " + content);
if (content == null) {
return;
}
Map hints = null;
String encoding = guessAppropriateEncoding(content);
if (encoding != null) {
hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
BitMatrix result;
try {
result = new MultiFormatWriter().encode(content, getWantedCodeType(mType)
, barcodeImageWidth, barcodeImageHeight, hints);
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
mHandler.post(mUpdateImageRunnable);
} catch (Exception iae) {
// Unsupported format
Log.e(TAG, "encode: " + iae.getMessage());
}
}
private Runnable mUpdateImageRunnable = new Runnable() {
@Override
public void run() {
mBarcodeImageView.setImageBitmap(bitmap);
}
};
/**
* get apposite barcode type
*
* @param type
* @return
*/
private BarcodeFormat getWantedCodeType(int type) {
switch (type) {
case CODE_TYPE_QR_CODE:
return BarcodeFormat.QR_CODE;
case CODE_TYPE_CODE_128:
return BarcodeFormat.CODE_128;
default:
return BarcodeFormat.QR_CODE;
}
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
}
================================================
FILE: YZxing-lib/src/main/java/com/example/qrcode/BeepManager.java
================================================
package com.example.qrcode;
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 java.io.Closeable;
import java.io.IOException;
/**
* Created by yangyu on 17/10/19.
*/
public final class BeepManager implements MediaPlayer.OnErrorListener, Closeable {
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();
}
synchronized void updatePrefs() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
playBeep = shouldBeep(prefs, activity);
vibrate = prefs.getBoolean(Constant.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(Constant.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();
try (AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep)) {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(false);
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
return mediaPlayer;
} catch (IOException ioe) {
Log.w(TAG, ioe);
mediaPlayer.release();
return null;
}
}
@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
close();
updatePrefs();
}
return true;
}
@Override
public synchronized void close() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
================================================
FILE: YZxing-lib/src/main/java/com/example/qrcode/Constant.java
================================================
package com.example.qrcode;
/**
* Created by yangyu on 17/10/29.
*/
public class Constant {
public static final int MESSAGE_SCANNER_DECODE = 0;
public static final int MESSAGE_SCANNER_DECODE_SUCCEEDED = 1;
public static final int MESSAGE_SCANNER_DECODE_FAIL = 2;
public static final int MESSAGE_SCANNER_QUIT = 3;
public static final String KEY_AUTO_FOCUS = "auto_focus";
public static final String KEY_DISABLE_CONTINUOUS_FOCUS = "continuous_focus";
public static final String KEY_VIBRATE = "beep_vibrate";
public static final String KEY_PLAY_BEEP = "beep_play";
public static final String EXTRA_SCANNER_FRAME_WIDTH = "scan_frame_width";
public static final String EXTRA_SCANNER_FRAME_HEIGHT = "scan_frame_height";
public static final String EXTRA_SCANNER_FRAME_TOP_PADDING = "scan_frame_top_padding";
public static final String EXTRA_SCAN_CODE_TYPE = "scan_code_type";
public static final String EXTRA_IS_ENABLE_SCAN_FROM_PIC = "is_enable_scan_from_pic";
public static final String EXTRA_RESULT_CODE_TYPE = "result_code_type";
public static final String EXTRA_RESULT_CONTENT = "result_content";
public static final String EXTRA_RESULT_TEXT_FROM_PIC = "text_from_pic";
}
================================================
FILE: YZxing-lib/src/main/java/com/example/qrcode/ScannerActivity.java
================================================
package com.example.qrcode;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import com.example.qrcode.camera.CameraManager;
import com.example.qrcode.decode.InactivityTimer;
import com.example.qrcode.decode.ScannerHandler;
import com.example.qrcode.utils.CommonUtils;
import com.example.qrcode.utils.DecodeUtils;
import com.example.qrcode.utils.UriUtils;
import com.example.qrcode.view.ScannerView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Set;
/**
* Created by yangyu on 17/10/18.
*/
public class ScannerActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private static final String TAG = "ScannerActivity";
public static final String BARCODE_FORMAT = "support_barcode_format";
public final int PERMISSION_REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 0X11;
public final int REQUEST_CODE_GET_PIC_URI = 0X12;
private final int MESSAGE_DECODE_FROM_BITMAP = 0;
private Toolbar mToolBar;
private ScannerView mScannerView;
private SurfaceView mSurfaceView;
private InactivityTimer mInactivityTimer;
private BeepManager beepManager;
private com.example.qrcode.camera.CameraManager cameraManager;
private ScannerHandler handler;
private Collection decodeFormats;
private int mScanFocusWidth;
private int mScanFocusHeight;
private int mScanFocusTopPadding;
private boolean isEnableScanFromPicture;
private boolean hasSurface;
private MyHandler mHandler;
private static class MyHandler extends Handler {
private WeakReference activity;
MyHandler(ScannerActivity mainActivityWeakReference) {
activity = new WeakReference(mainActivityWeakReference);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
ScannerActivity activity = this.activity.get();
if (activity != null) {
if (msg.what == activity.MESSAGE_DECODE_FROM_BITMAP) {
Bitmap bm = (Bitmap) msg.obj;
DecodeUtils.DecodeAsyncTask decodeAsyncTask = new DecodeUtils.DecodeAsyncTask(activity);
decodeAsyncTask.execute(bm);
}
}
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_scanner);
initView();
hasSurface = false;
Intent intent = getIntent();
if (intent != null) {
mScanFocusWidth = intent.getIntExtra(Constant.EXTRA_SCANNER_FRAME_WIDTH, -1);
mScanFocusHeight = intent.getIntExtra(Constant.EXTRA_SCANNER_FRAME_HEIGHT, -1);
mScanFocusTopPadding = intent.getIntExtra(Constant.EXTRA_SCANNER_FRAME_TOP_PADDING, -1);
isEnableScanFromPicture = intent.getBooleanExtra(Constant.EXTRA_IS_ENABLE_SCAN_FROM_PIC, false);
Bundle b = intent.getExtras();
if (b != null) {
HashMap formats = (HashMap) b.getSerializable(Constant.EXTRA_SCAN_CODE_TYPE);
if (formats != null) {
decodeFormats = formats.get(BARCODE_FORMAT);
} else {
decodeFormats = EnumSet.of(BarcodeFormat.QR_CODE
, BarcodeFormat.CODE_128);
}
} else {
decodeFormats = EnumSet.of(BarcodeFormat.QR_CODE
, BarcodeFormat.CODE_128);
}
}
Log.e(TAG, "onCreate:decodeFormats :" + decodeFormats.size() + "--" + decodeFormats.toString());
mInactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
mHandler = new MyHandler(this);
}
@Override
protected void onResume() {
super.onResume();
cameraManager = new CameraManager(this);
cameraManager.setManualFramingRect(mScanFocusWidth, mScanFocusHeight, mScanFocusTopPadding);
mScannerView.setCameraManager(cameraManager);
SurfaceHolder holder = mSurfaceView.getHolder();
if (hasSurface) {
initCamera(holder);
} else {
holder.addCallback(this);
}
mInactivityTimer.onResume();
beepManager.updatePrefs();
}
@Override
protected void onPause() {
super.onPause();
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
cameraManager.closeDriver();
mInactivityTimer.onPause();
beepManager.close();
}
@Override
protected void onDestroy() {
cameraManager.clearFramingRect();
mInactivityTimer.shutdown();
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
//关闭灯光
cameraManager.setTorch(false);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
//开启闪光灯
cameraManager.setTorch(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (isEnableScanFromPicture) {
getMenuInflater().inflate(R.menu.menu_scan, menu);
return true;
} else {
return super.onCreateOptionsMenu(menu);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.scan_from_picture) {
//先申请权限
int checked = ContextCompat.checkSelfPermission(ScannerActivity.this
, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (checked == PackageManager.PERMISSION_GRANTED) {
goPicture();
} else {
ActivityCompat.requestPermissions(ScannerActivity.this
, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
}
} else if (itemId == R.id.encode_barcode) {
startActivity(new Intent(ScannerActivity.this, BarcodeActivity.class));
}
return true;
}
private void goPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_GET_PIC_URI);
}
private void initView() {
mToolBar = (Toolbar) findViewById(R.id.tool_bar);
mToolBar.setTitle("二维码/条形码");
mToolBar.setTitleTextColor(Color.WHITE);
setSupportActionBar(mToolBar);
mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mScannerView = (ScannerView) findViewById(R.id.scan_view);
}
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);
if (handler == null) {
handler = new ScannerHandler(this, decodeFormats, "utf-8", cameraManager);
}
} catch (IOException ioe) {
Log.w(TAG, ioe);
} catch (RuntimeException e) {
Log.w(TAG, "Unexpected error initializing camera", e);
}
}
@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) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
//在这里处理扫码结果
public void handDecode(final Result result) {
mInactivityTimer.onActivity();
beepManager.playBeepSoundAndVibrate();
// AlertDialog.Builder mScannerDialogBuilder = new AlertDialog.Builder(this);
// mScannerDialogBuilder.setMessage("codeType:" + result.getBarcodeFormat() + "-----content:" + result.getText());
// mScannerDialogBuilder.setCancelable(false);
// mScannerDialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// ScannerActivity.this.finish();
// }
// });
// mScannerDialogBuilder.create().show();
Intent data = new Intent();
BarcodeFormat format = result.getBarcodeFormat();
String type = format.toString();
data.putExtra(Constant.EXTRA_RESULT_CODE_TYPE, type);
data.putExtra(Constant.EXTRA_RESULT_CONTENT, result.getText());
setResult(RESULT_OK, data);
finish();
}
public CameraManager getCameraManager() {
return cameraManager;
}
public Handler getHandler() {
return handler;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_GET_PIC_URI:
Uri uri = data.getData();
String imagePath = UriUtils.getPicturePathFromUri(ScannerActivity.this, uri);
//对获取到的二维码照片进行压缩
Bitmap bitmap = CommonUtils.compressPicture(imagePath);
Message message = mHandler.obtainMessage(MESSAGE_DECODE_FROM_BITMAP, bitmap);
mHandler.sendMessage(message);
Log.e(TAG, "onActivityResult: uri:" + uri.toString());
break;
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE_WRITE_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
goPicture();
return;
}
}
}
}
================================================
FILE: YZxing-lib/src/main/java/com/example/qrcode/ShowResultActivity.java
================================================
package com.example.qrcode;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
* Created by yangyu on 2017/11/28.
*/
public class ShowResultActivity extends AppCompatActivity {
private static final String TAG = "ShowResultActivity";
private WebView webView;
private TextView tv;
private ProgressBar pb;
private String resultText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_show_result);
webView = (WebView) findViewById(R.id.web_content);
tv = (TextView) findViewById(R.id.tv);
pb = (ProgressBar) findViewById(R.id.progress);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webView.setWebChromeClient(webChromeClient);
webView.setWebViewClient(webViewClient);
Intent intent = getIntent();
if (intent != null) {
resultText = intent.getStringExtra(Constant.EXTRA_RESULT_TEXT_FROM_PIC);
if (Patterns.WEB_URL.matcher(resultText).matches()) {
//是一个web url
tv.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
webView.loadUrl(resultText);
} else {
//不是web url
tv.setVisibility(View.VISIBLE);
webView.setVisibility(View.GONE);
pb.setVisibility(View.GONE);
tv.setText(resultText);
}
}
}
private WebViewClient webViewClient = new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
};
private WebChromeClient webChromeClient = new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress == 100) {
pb.setVisibility(View.GONE);
} else {
pb.setVisibility(View.VISIBLE);
pb.setProgress(newProgress);
}
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
Log.e(TAG, "onReceivedTitle: " + title);
}
};
}
================================================
FILE: YZxing-lib/src/main/java/com/example/qrcode/callback/PreviewCallback.java
================================================
package com.example.qrcode.callback;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.example.qrcode.camera.CameraConfigurationManager;
/**
* Created by yangyu on 17/10/19.
*/
public class PreviewCallback implements Camera.PreviewCallback {
private static final String TAG = PreviewCallback.class.getSimpleName();
private final CameraConfigurationManager configManager;
private Handler previewHandler;
private int previewMessage;
public PreviewCallback(CameraConfigurationManager configManager) {
this.configManager = configManager;
}
public 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: YZxing-lib/src/main/java/com/example/qrcode/camera/AutoFocusManager.java
================================================
package com.example.qrcode.camera;
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 com.example.qrcode.Constant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.RejectedExecutionException;
/**
* Created by yangyu on 17/10/19.
*/
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 FOCUS_MODES_CALLING_AF;
static {
FOCUS_MODES_CALLING_AF = new ArrayList<>(2);
FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO);
FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO);
}
private boolean stopped;
private boolean focusing;
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(Constant.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) {
focusing = false;
autoFocusAgainLater();
}
private synchronized void autoFocusAgainLater() {
if (!stopped && outstandingTask == null) {
AutoFocusTask newTask = new AutoFocusTask();
try {
newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
outstandingTask = newTask;
} catch (RejectedExecutionException ree) {
Log.w(TAG, "Could not request auto focus", ree);
}
}
}
synchronized void start() {
if (useAutoFocus) {
outstandingTask = null;
if (!stopped && !focusing) {
try {
camera.autoFocus(this);
focusing = true;
} catch (RuntimeException re) {
// Have heard RuntimeException reported in Android 4.0.x+; continue?
Log.w(TAG, "Unexpected exception while focusing", re);
// Try again later to keep cycle going
autoFocusAgainLater();
}
}
}
}
private synchronized void cancelOutstandingTask() {
if (outstandingTask != null) {
if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) {
outstandingTask.cancel(true);
}
outstandingTask = null;
}
}
synchronized void stop() {
stopped = true;
if (useAutoFocus) {
cancelOutstandingTask();
// Doesn't hurt to call this even if not focusing
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);
}
}
}
private final class AutoFocusTask extends AsyncTask