================================================
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
================================================
# MNMLKitScanner 基于Google MLKit 快速集成二维码扫描,速度比zxing快
## 基于Google MLKit 快速集成二维码扫描,速度比zxing快,可配置相册,闪光灯,相机可以调整焦距放大缩小,自定义扫描线颜色,自定义背景颜色,自定义遮罩层,支持同时扫多个二维码和条形码
[](https://jitpack.io/#maning0303/MNMLKitScanner)
## 功能:
1:二维码扫描,手势缩放,无拉伸,样式自定义
2:相册中选取图片识别
3: 相机可以调整焦距放大缩小
4: 完全自定义遮罩层
5: 支持微信多个二维码/条形码同时扫描
6: 可调整扫描框大小
## 截图:
## 如何添加
### Gradle添加:
#### 1.在Project的build.gradle中添加仓库地址
``` gradle
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
```
#### 2.在Module目录下的build.gradle中添加依赖
``` gradle
dependencies {
implementation 'com.github.maning0303:MNMLKitScanner:V1.0.4'
//下面版本自己控制,barcode-scanning>=17.0.2
implementation 'com.google.mlkit:barcode-scanning:17.0.2'
implementation "androidx.camera:camera-core:1.0.2"
implementation "androidx.camera:camera-camera2:1.0.2"
implementation "androidx.camera:camera-lifecycle:1.0.2"
implementation "androidx.camera:camera-view:1.0.0-alpha25"
}
```
#### 3.如果想加入二维码生成功能
``` gradle
dependencies {
implementation 'com.google.zxing:core:3.3.3'
}
```
com.maning.mlkitscanner.scan.utils.ZXingUtils 有具体的方法,详细可以查看Demo
## 使用方法:
### 进入需要提前申请相机权限;进入需要提前申请相机权限;进入需要提前申请相机权限;
``` java
1:开始扫描:
//默认扫描
MNScanManager.startScan(this, new MNScanCallback() {
@Override
public void onActivityResult(int resultCode, Intent data) {
switch (resultCode) {
case MNScanManager.RESULT_SUCCESS:
ArrayList results = data.getStringArrayListExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS);
break;
case MNScanManager.RESULT_FAIL:
String resultError = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR);
break;
case MNScanManager.RESULT_CANCLE:
showToast("取消扫码");
break;
}
}
});
//自定义扫描
MNScanConfig scanConfig = new MNScanConfig.Builder()
//设置完成震动
.isShowVibrate(true)
//扫描完成声音
.isShowBeep(true)
//显示相册功能
.isShowPhotoAlbum(true)
//显示闪光灯
.isShowLightController(true)
//打开扫描页面的动画
.setActivityOpenAnime(R.anim.activity_anmie_in)
//退出扫描页面动画
.setActivityExitAnime(R.anim.activity_anmie_out)
//自定义文案
.setScanHintText("xxxx")
.setScanHintTextColor("#FF0000")
.setScanHintTextSize(14)
//扫描线的颜色
.setScanColor("#FF0000")
//是否支持手势缩放
.setSupportZoom(true)
//扫描线样式
.setLaserStyle(MNScanConfig.LaserStyle.Grid/MNScanConfig.LaserStyle.Line)
//背景颜色
.setBgColor("")
//网格扫描线的列数
.setGridScanLineColumn(30)
//网格高度
.setGridScanLineHeight(300)
//是否全屏扫描,默认全屏
.setFullScreenScan(true)
//单位dp
.setResultPointConfigs(36, 12, 3, colorResultPointStroke, colorResultPoint)
//状态栏设置
.setStatusBarConfigs(colorStatusBar, true)
//扫描框宽度大小比例,非全屏模式下生效,默认0.7,范围0.5-0.9
.setScanFrameSizeScale(0.7f)
//自定义遮罩
.setCustomShadeViewLayoutID(R.layout.layout_custom_view, new MNCustomViewBindCallback() {
@Override
public void onBindView(View customView) {
//TODO:通过findviewById 获取View
}
})
.builder();
MNScanManager.startScan(this, scanConfig, new MNScanCallback() {
@Override
public void onActivityResult(int resultCode, Intent data) {
switch (resultCode) {
case MNScanManager.RESULT_SUCCESS:
String resultSuccess = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS);
break;
case MNScanManager.RESULT_FAIL:
String resultError = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR);
break;
case MNScanManager.RESULT_CANCLE:
showToast("取消扫码");
break;
}
}
});
2.提供扫描界面相关方法(自定义遮罩层会使用):
/**
* 关闭当前页面
*/
MNScanManager.closeScanPage();
/**
* 打开相册扫描图片
*/
MNScanManager.openAlbumPage();
/**
* 打开手电筒
*/
MNScanManager.openScanLight();
/**
* 关闭手电筒
*/
MNScanManager.closeScanLight();
/**
* 手电筒是否开启
*/
MNScanManager.isLightOn();
```
## 感谢:
[googlesamples/mlkit](https://github.com/googlesamples/mlkit)
[jenly1314/MLKit](https://github.com/jenly1314/MLKit)
[Ye-Miao/StatusBarUtil](https://github.com/Ye-Miao/StatusBarUtil)
感谢所有开源的人;
## 推荐:
Name | Describe |
--- | --- |
[GankMM](https://github.com/maning0303/GankMM) | (Material Design & MVP & Retrofit + OKHttp & RecyclerView ...)Gank.io Android客户端:每天一张美女图片,一个视频短片,若干Android,iOS等程序干货,周一到周五每天更新,数据全部由 干货集中营 提供,持续更新。 |
[MNUpdateAPK](https://github.com/maning0303/MNUpdateAPK) | Android APK 版本更新的下载和安装,适配7.0,简单方便。 |
[MNImageBrowser](https://github.com/maning0303/MNImageBrowser) | 交互特效的图片浏览框架,微信向下滑动动态关闭 |
[MNZXingCode](https://github.com/maning0303/MNZXingCode) | 快速集成二维码扫描和生成二维码 |
[MNMLKitScanner](https://github.com/maning0303/MNMLKitScanner) | 基于Google MLKit 快速集成二维码扫描,速度比zxing快 |
[MNPasswordEditText](https://github.com/maning0303/MNPasswordEditText) | 类似微信支付宝的密码输入框。 |
[MClearEditText](https://github.com/maning0303/MClearEditText) | 带有删除功能的EditText |
[MNCrashMonitor](https://github.com/maning0303/MNCrashMonitor) | Debug监听程序崩溃日志,展示崩溃日志列表,方便自己平时调试。 |
[MNProgressHUD](https://github.com/maning0303/MNProgressHUD) | MNProgressHUD是对常用的自定义弹框封装,加载ProgressDialog,状态显示的StatusDialog和自定义Toast,支持背景颜色,圆角,边框和文字的自定义。 |
[SwitcherView](https://github.com/maning0303/SwitcherView) | 垂直滚动的广告栏文字展示。 |
[MNVideoPlayer](https://github.com/maning0303/MNVideoPlayer) | SurfaceView + MediaPlayer 实现的视频播放器,支持横竖屏切换,手势快进快退、调节音量,亮度等。------代码简单,新手可以看一看。 |
[MNChangeSkin](https://github.com/maning0303/MNChangeSkin) | Android夜间模式,通过Theme实现 |
[MNXUtilsDB](https://github.com/maning0303/MNXUtilsDB) | xUtils3 数据库模块单独抽取出来,方便使用。 |
[MNCalendar](https://github.com/maning0303/MNCalendar) | 简单的日历控件练习,水平方向日历支持手势滑动切换,跳转月份;垂直方向日历选取区间范围。 |
[MNSwipeToLoadDemo](https://github.com/maning0303/MNSwipeToLoadDemo) | 利用SwipeToLoadLayout实现的各种下拉刷新效果(饿了吗,京东,百度外卖,美团外卖,天猫下拉刷新等)。 |
================================================
FILE: app/.gitignore
================================================
/build
================================================
FILE: app/build.gradle
================================================
apply plugin: 'com.android.application'
def versions = rootProject.ext.versions
def appId = rootProject.ext.appId
def dependenciesGoogle = rootProject.ext.dependenciesGoogle
def dependenciesOther = rootProject.ext.dependenciesOther
android {
compileSdkVersion versions.compileSdkVersion
ndkVersion "20.1.5948944"
defaultConfig {
applicationId appId.app
minSdkVersion versions.minSdkVersion
targetSdkVersion versions.targetSdkVersion
versionCode versions.versionCode
versionName versions.versionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
// 循环引入库
dependenciesGoogle.each { k, v -> api v }
dependenciesOther.each { k, v -> api v }
dependenciesDebug.each { k, v -> debugImplementation v }
//扫码核心库
implementation project(path: ':mlkit-scanner')
// implementation 'com.github.maning0303:MNMLKitScanner:V1.0.4'
implementation 'com.google.mlkit:barcode-scanning:17.0.2'
implementation 'androidx.camera:camera-core:1.0.2'
implementation 'androidx.camera:camera-camera2:1.0.2'
implementation 'androidx.camera:camera-lifecycle:1.0.2'
implementation 'androidx.camera:camera-view:1.0.0-alpha25'
implementation 'com.google.zxing:core:3.3.3'
}
================================================
FILE: app/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# 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: app/src/androidTest/java/com/maning/mlkitscanner/ExampleInstrumentedTest.java
================================================
package com.maning.mlkitscanner;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see Testing documentation
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.maning.mlkitscanner", appContext.getPackageName());
}
}
================================================
FILE: app/src/main/AndroidManifest.xml
================================================
================================================
FILE: app/src/main/java/com/maning/mlkitscanner/demo/CustomConfigActivity.java
================================================
package com.maning.mlkitscanner.demo;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.maning.mlkitscanner.scan.MNScanManager;
import com.maning.mlkitscanner.scan.callback.MNCustomViewBindCallback;
import com.maning.mlkitscanner.scan.callback.act.MNScanCallback;
import com.maning.mlkitscanner.scan.model.MNScanConfig;
import java.util.ArrayList;
import top.defaults.colorpicker.ColorPickerPopup;
public class CustomConfigActivity extends AppCompatActivity implements View.OnClickListener {
/**
* 是否显示相册功能
*/
private CheckBox mCbPhoto;
/**
* 是否显示闪光灯
*/
private CheckBox mCbLight;
/**
* 是否需要全屏扫描识别(默认)
*/
private CheckBox mCbFullscreenScan;
/**
* 是否开启扫描完成震动提醒
*/
private CheckBox mCbVibrate;
/**
* 是否开启扫描完成声音提醒
*/
private CheckBox mCbBeep;
/**
* 是否完全自定义遮罩层
*/
private CheckBox mCbCustomView;
/**
* 输入自定义提示文案
*/
private EditText mEtHintText;
/**
* 文字大小(sp)
*/
private EditText mEtHintTextSize;
/**
* 网格扫描高度
*/
private EditText mEtGridlineHeight;
/**
* 网格扫描列数
*/
private EditText mEtGridlineNum;
private TextView mBtnColorPickerText;
private TextView mBtnColorPickerLine;
private TextView mBtnColorPickerBg;
/**
* 线性
*/
private RadioButton mRbScanlineLine;
/**
* 网格
*/
private RadioButton mRbScanlineGrid;
private String colorText = "#22CE6B";
private String colorLine = "#22CE6B";
private String colorBackground = "#22FF0000";
private String colorStatusBar = "#00000000";
private String colorResultPoint = "#CC22CE6B";
private String colorResultPointStroke = "#FFFFFFFF";
/**
* 是否支持手势缩放
*/
private CheckBox mCbSupportZoom;
/**
* 是否状态栏黑色字体
*/
private CheckBox mCbStatusDark;
private TextView mBtnColorStatusbarBg;
private SeekBar mSbarFrameSize;
private TextView mTvFrameSize;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_config);
initView();
}
private void initView() {
mCbPhoto = (CheckBox) findViewById(R.id.cb_photo);
mCbLight = (CheckBox) findViewById(R.id.cb_light);
mCbFullscreenScan = (CheckBox) findViewById(R.id.cb_fullscreen_scan);
mCbVibrate = (CheckBox) findViewById(R.id.cb_vibrate);
mCbBeep = (CheckBox) findViewById(R.id.cb_beep);
mCbCustomView = (CheckBox) findViewById(R.id.cb_custom_view);
mEtHintText = (EditText) findViewById(R.id.et_hint_text);
mEtHintTextSize = (EditText) findViewById(R.id.et_hint_text_size);
mEtGridlineHeight = (EditText) findViewById(R.id.et_gridline_height);
mEtGridlineNum = (EditText) findViewById(R.id.et_gridline_num);
mBtnColorPickerText = (TextView) findViewById(R.id.btn_color_picker_text);
mBtnColorPickerText.setOnClickListener(this);
mBtnColorPickerLine = (TextView) findViewById(R.id.btn_color_picker_line);
mBtnColorPickerLine.setOnClickListener(this);
mBtnColorPickerBg = (TextView) findViewById(R.id.btn_color_picker_bg);
mBtnColorPickerBg.setOnClickListener(this);
mRbScanlineLine = (RadioButton) findViewById(R.id.rb_scanline_line);
mRbScanlineGrid = (RadioButton) findViewById(R.id.rb_scanline_grid);
mCbSupportZoom = (CheckBox) findViewById(R.id.cb_support_zoom);
mCbStatusDark = (CheckBox) findViewById(R.id.cb_status_dark);
mBtnColorStatusbarBg = (TextView) findViewById(R.id.btn_color_statusbar_bg);
mBtnColorStatusbarBg.setOnClickListener(this);
mTvFrameSize = (TextView) findViewById(R.id.tv_frameSize);
mSbarFrameSize = (SeekBar) findViewById(R.id.sbar_frameSize);
mSbarFrameSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (mSbarFrameSize.getProgress() < 50) {
mSbarFrameSize.setProgress(50);
}
if (mSbarFrameSize.getProgress() > 90) {
mSbarFrameSize.setProgress(90);
}
mTvFrameSize.setText("扫描框大小比例:" + (mSbarFrameSize.getProgress() / 100f) + "\n(非全屏模式生效,范围0.5-0.9)");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_color_picker_text:
new ColorPickerPopup.Builder(this)
.initialColor(Color.parseColor(colorText))
.enableBrightness(true)
.enableAlpha(false)
.okTitle("选择颜色")
.cancelTitle("取消")
.showIndicator(true)
.showValue(true)
.build()
.show(mBtnColorPickerText, new ColorPickerPopup.ColorPickerObserver() {
@Override
public void onColorPicked(int color) {
colorText = getHexString(color);
mBtnColorPickerText.setBackgroundColor(color);
}
});
break;
case R.id.btn_color_picker_line:
new ColorPickerPopup.Builder(this)
.initialColor(Color.parseColor(colorLine))
.enableBrightness(true)
.enableAlpha(false)
.okTitle("选择颜色")
.cancelTitle("取消")
.showIndicator(true)
.showValue(true)
.build()
.show(mBtnColorPickerLine, new ColorPickerPopup.ColorPickerObserver() {
@Override
public void onColorPicked(int color) {
colorLine = getHexString(color);
mBtnColorPickerLine.setBackgroundColor(color);
}
});
break;
case R.id.btn_color_picker_bg:
new ColorPickerPopup.Builder(this)
.initialColor(Color.parseColor(colorBackground))
.enableBrightness(true)
.enableAlpha(true)
.okTitle("选择颜色")
.cancelTitle("取消")
.showIndicator(true)
.showValue(true)
.build()
.show(mBtnColorPickerBg, new ColorPickerPopup.ColorPickerObserver() {
@Override
public void onColorPicked(int color) {
colorBackground = getHexString(color);
mBtnColorPickerBg.setBackgroundColor(color);
}
});
break;
case R.id.btn_color_statusbar_bg:
new ColorPickerPopup.Builder(this)
.initialColor(Color.parseColor(colorStatusBar))
.enableBrightness(true)
.enableAlpha(true)
.okTitle("选择颜色")
.cancelTitle("取消")
.showIndicator(true)
.showValue(true)
.build()
.show(mBtnColorStatusbarBg, new ColorPickerPopup.ColorPickerObserver() {
@Override
public void onColorPicked(int color) {
colorStatusBar = getHexString(color);
mBtnColorStatusbarBg.setBackgroundColor(color);
}
});
break;
default:
break;
}
}
private String getHexString(int color) {
String format = String.format("#%X", color);
Log.e("=====", "format:" + format);
if ("#0".equals(format)) {
format = "#00000000";
Log.e("=====", "format:" + format);
}
return format;
}
public void scanCode(View view) {
//需要判断有没有权限
MNScanConfig scanConfig = new MNScanConfig.Builder()
//设置完成震动
.isShowVibrate(mCbVibrate.isChecked())
//扫描完成声音
.isShowBeep(mCbBeep.isChecked())
//显示相册功能
.isShowPhotoAlbum(mCbPhoto.isChecked())
//显示闪光灯
.isShowLightController(mCbLight.isChecked())
//打开扫描页面的动画
.setActivityOpenAnime(R.anim.activity_anmie_in)
//退出扫描页面动画
.setActivityExitAnime(R.anim.activity_anmie_out)
//自定义文案
.setScanHintText(mEtHintText.getText().toString())
.setScanHintTextColor(colorText)
.setScanHintTextSize(TextUtils.isEmpty(mEtHintTextSize.getText().toString()) ? 14 : Integer.parseInt(mEtHintTextSize.getText().toString()))
//扫描线的颜色
.setScanColor(colorLine)
//是否支持手势缩放
.setSupportZoom(mCbSupportZoom.isChecked())
//扫描线样式
.setLaserStyle(mRbScanlineGrid.isChecked() ? MNScanConfig.LaserStyle.Grid : MNScanConfig.LaserStyle.Line)
//背景颜色
.setBgColor(colorBackground)
//网格扫描线的列数
.setGridScanLineColumn(TextUtils.isEmpty(mEtGridlineNum.getText().toString()) ? 30 : Integer.parseInt(mEtGridlineNum.getText().toString()))
//网格高度
.setGridScanLineHeight(TextUtils.isEmpty(mEtGridlineHeight.getText().toString()) ? 0 : Integer.parseInt(mEtGridlineHeight.getText().toString()))
//是否全屏扫描,默认全屏
.setFullScreenScan(mCbFullscreenScan.isChecked())
//单位dp
.setResultPointConfigs(36, 12, 3, colorResultPointStroke, colorResultPoint)
//状态栏设置
.setStatusBarConfigs(colorStatusBar, mCbStatusDark.isChecked())
//扫描框宽度大小比例,非全屏模式下生效,默认0.7,范围0.5-0.9
.setScanFrameSizeScale(mSbarFrameSize.getProgress() / 100f)
//自定义遮罩
.setCustomShadeViewLayoutID(mCbCustomView.isChecked() ? R.layout.layout_custom_view : 0, new MNCustomViewBindCallback() {
@Override
public void onBindView(View customView) {
if (customView == null) {
return;
}
ImageView iv_back = customView.findViewById(R.id.iv_back);
ImageView iv_photo = customView.findViewById(R.id.iv_photo);
LinearLayout btn_scan_light = customView.findViewById(R.id.btn_scan_light);
final ImageView iv_scan_light = customView.findViewById(R.id.iv_scan_light);
final TextView tv_scan_light = customView.findViewById(R.id.tv_scan_light);
LinearLayout btn_my_card = customView.findViewById(R.id.btn_my_card);
LinearLayout btn_scan_record = customView.findViewById(R.id.btn_scan_record);
iv_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//关闭扫描页面
MNScanManager.closeScanPage();
}
});
btn_scan_light.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//手电筒
if (MNScanManager.isLightOn()) {
MNScanManager.closeScanLight();
iv_scan_light.setImageResource(R.drawable.icon_custom_light_close);
tv_scan_light.setText("开启手电筒");
} else {
MNScanManager.openScanLight();
iv_scan_light.setImageResource(R.drawable.icon_custom_light_open);
tv_scan_light.setText("关闭手电筒");
}
}
});
iv_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//打开相册扫描
MNScanManager.openAlbumPage();
}
});
btn_my_card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//我的名片
showToast("我的名片");
}
});
btn_scan_record.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//扫码记录
showToast("扫码记录");
}
});
}
})
.builder();
MNScanManager.startScan(this, scanConfig, new MNScanCallback() {
@Override
public void onActivityResult(int resultCode, Intent data) {
handlerResult(resultCode, data);
}
});
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
private void handlerResult(int resultCode, Intent data) {
switch (resultCode) {
case MNScanManager.RESULT_SUCCESS:
ArrayList results = data.getStringArrayListExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS);
StringBuilder resultStr = new StringBuilder();
for (int i = 0; i < results.size(); i++) {
resultStr.append("第" + (i + 1) + "条:");
resultStr.append(results.get(i));
resultStr.append("\n");
}
showToast(resultStr.toString());
break;
case MNScanManager.RESULT_FAIL:
String resultError = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR);
showToast(resultError);
break;
case MNScanManager.RESULT_CANCLE:
showToast("取消扫码");
break;
}
}
}
================================================
FILE: app/src/main/java/com/maning/mlkitscanner/demo/MainActivity.java
================================================
package com.maning.mlkitscanner.demo;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.maning.mlkitscanner.scan.MNScanManager;
import com.maning.mlkitscanner.scan.callback.act.MNScanCallback;
import com.maning.mlkitscanner.scan.utils.ZXingUtils;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnScanDefault;
private Button btnScanCustom;
private TextView tvResults;
private ImageView imageView;
private EditText editText;
private CheckBox checkbox;
private CheckBox checkbox2;
private Spinner mSpColorBlack;
private Spinner mSpColorWhite;
private Spinner mSpMargin;
private String error_correction_level;
private int margin = 0;
private int color_black = Color.BLACK;
private int color_white = Color.WHITE;
private Spinner mSpErrorCorrectionLevel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
requestCameraPerm();
}
private void initView() {
btnScanDefault = (Button) findViewById(R.id.btn_scan_default);
btnScanCustom = (Button) findViewById(R.id.btn_scan_custom);
btnScanDefault.setOnClickListener(this);
btnScanCustom.setOnClickListener(this);
tvResults = (TextView) findViewById(R.id.tv_results);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editText);
checkbox = (CheckBox) findViewById(R.id.checkbox);
checkbox2 = (CheckBox) findViewById(R.id.checkbox2);
mSpColorBlack = (Spinner) findViewById(R.id.sp_color_black);
mSpColorWhite = (Spinner) findViewById(R.id.sp_color_white);
mSpMargin = (Spinner) findViewById(R.id.sp_margin);
mSpMargin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
margin = Integer.parseInt(getResources().getStringArray(R.array.spinarr_margin)[position]);
}
@Override
public void onNothingSelected(AdapterView> parent) {
}
});
mSpColorBlack.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
String str_color_black = getResources().getStringArray(R.array.spinarr_color_black)[position];
if (str_color_black.equals("黑色")) {
color_black = Color.BLACK;
} else if (str_color_black.equals("白色")) {
color_black = Color.WHITE;
} else if (str_color_black.equals("蓝色")) {
color_black = Color.BLUE;
} else if (str_color_black.equals("绿色")) {
color_black = Color.GREEN;
} else if (str_color_black.equals("黄色")) {
color_black = Color.YELLOW;
} else if (str_color_black.equals("红色")) {
color_black = Color.RED;
} else {
color_black = Color.BLACK;
}
}
@Override
public void onNothingSelected(AdapterView> parent) {
}
});
mSpColorWhite.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
String str_color_white = getResources().getStringArray(R.array.spinarr_color_white)[position];
if (str_color_white.equals("黑色")) {
color_white = Color.BLACK;
} else if (str_color_white.equals("白色")) {
color_white = Color.WHITE;
} else if (str_color_white.equals("蓝色")) {
color_white = Color.BLUE;
} else if (str_color_white.equals("绿色")) {
color_white = Color.GREEN;
} else if (str_color_white.equals("黄色")) {
color_white = Color.YELLOW;
} else if (str_color_white.equals("红色")) {
color_white = Color.RED;
} else {
color_white = Color.WHITE;
}
}
@Override
public void onNothingSelected(AdapterView> parent) {
}
});
mSpErrorCorrectionLevel = (Spinner) findViewById(R.id.sp_error_correction_level);
mSpErrorCorrectionLevel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
error_correction_level = getResources().getStringArray(R.array.spinarr_error_correction)[position];
}
@Override
public void onNothingSelected(AdapterView> parent) {
}
});
}
public void requestCameraPerm() {
//判断权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 10010);
}
}
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.btn_scan_default) {
MNScanManager.startScan(this, new MNScanCallback() {
@Override
public void onActivityResult(int resultCode, Intent data) {
handlerResult(resultCode, data);
}
});
}else if (view.getId() == R.id.btn_scan_custom) {
//跳转到自定义界面
startActivity(new Intent(this, CustomConfigActivity.class));
}
}
private void handlerResult(int resultCode, Intent data) {
if (data == null) {
return;
}
switch (resultCode) {
default:
break;
case MNScanManager.RESULT_SUCCESS:
ArrayList results = data.getStringArrayListExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS);
StringBuilder resultStr = new StringBuilder();
for (int i = 0; i < results.size(); i++) {
resultStr.append("第" + (i + 1) + "条:");
resultStr.append(results.get(i));
resultStr.append("\n");
}
tvResults.setText(resultStr.toString());
break;
case MNScanManager.RESULT_FAIL:
String resultError = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR);
showToast(resultError);
break;
case MNScanManager.RESULT_CANCLE:
showToast("取消扫码");
break;
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
public void createQRImage(View view) {
String str = editText.getText().toString();
if (TextUtils.isEmpty(str)) {
Toast.makeText(this, "字符串不能为空", Toast.LENGTH_SHORT).show();
return;
}
Bitmap qrImage;
Bitmap logo = null;
Bitmap foreground_bitmap = null;
if (checkbox.isChecked()) {
logo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_wx);
}
if (checkbox2.isChecked()) {
foreground_bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tmp);
}
qrImage = ZXingUtils.createQRCodeImage(str, 500, margin, color_black, color_white, error_correction_level, logo, foreground_bitmap);
if (qrImage != null) {
imageView.setImageBitmap(qrImage);
} else {
Toast.makeText(this, "生成失败", Toast.LENGTH_SHORT).show();
}
}
}
================================================
FILE: app/src/main/res/anim/activity_anmie_in.xml
================================================
================================================
FILE: app/src/main/res/anim/activity_anmie_out.xml
================================================
================================================
FILE: app/src/main/res/drawable/ic_launcher_background.xml
================================================
================================================
FILE: app/src/main/res/drawable-v24/ic_launcher_foreground.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_custom_config.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: app/src/main/res/layout/layout_custom_view.xml
================================================
================================================
FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
================================================
================================================
FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
================================================
================================================
FILE: app/src/main/res/values/array.xml
================================================
L M QH01234黑色白色蓝色绿色黄色红色白色黑色蓝色绿色黄色红色
================================================
FILE: app/src/main/res/values/colors.xml
================================================
#6200EE#3700B3#03DAC5
================================================
FILE: app/src/main/res/values/strings.xml
================================================
MLKit扫码
================================================
FILE: app/src/main/res/values/styles.xml
================================================
================================================
FILE: app/src/test/java/com/maning/mlkitscanner/ExampleUnitTest.java
================================================
package com.maning.mlkitscanner;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see Testing documentation
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply from: "config.gradle"
buildscript {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.0"
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.0'
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
================================================
FILE: config.gradle
================================================
/**
* 全局统一配置
*/
ext {
/**
* 版本统一管理
*/
versions = [
versionCode : 101, //版本号
versionName : "1.0.1", //版本名称
compileSdkVersion: 29,
minSdkVersion : 21,
targetSdkVersion : 28,
]
appId = [
"app": "com.maning.mlkitscanner.demo",
]
dependenciesGoogle = [
annotation : 'androidx.annotation:annotation:1.1.0',
supportv4 : 'androidx.legacy:legacy-support-v4:1.0.0',
appcompat : 'androidx.appcompat:appcompat:1.2.0',
design : 'com.google.android.material:material:1.0.0',
recyclerView : 'androidx.recyclerview:recyclerview:1.0.0',
constraintlayout: 'androidx.constraintlayout:constraintlayout:1.1.3',
multidex : 'androidx.multidex:multidex:2.0.0',
]
dependenciesOther = [
//颜色选择器
"colorpicker": 'com.github.duanhong169:colorpicker:1.1.6',
"xpopup" : 'com.lxj:xpopup:2.2.19'
]
dependenciesDebug = [
"leakcanary": "com.squareup.leakcanary:leakcanary-android:2.5",
]
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Fri Aug 20 09:04:58 CST 2021
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: mlkit-scanner/.gitignore
================================================
/build
================================================
FILE: mlkit-scanner/build.gradle
================================================
apply plugin: 'com.android.library'
def versions = rootProject.ext.versions
android {
compileSdkVersion versions.compileSdkVersion
defaultConfig {
minSdkVersion versions.minSdkVersion
targetSdkVersion versions.targetSdkVersion
versionCode versions.versionCode
versionName versions.versionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
compileOnly 'androidx.appcompat:appcompat:1.1.0'
compileOnly 'com.google.mlkit:barcode-scanning:17.0.2'
compileOnly "androidx.camera:camera-core:1.0.2"
compileOnly "androidx.camera:camera-camera2:1.0.2"
compileOnly "androidx.camera:camera-lifecycle:1.0.2"
compileOnly "androidx.camera:camera-view:1.0.0-alpha25"
compileOnly 'com.google.zxing:core:3.3.3'
}
================================================
FILE: mlkit-scanner/consumer-rules.pro
================================================
================================================
FILE: mlkit-scanner/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# 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: mlkit-scanner/src/main/AndroidManifest.xml
================================================
================================================
FILE: mlkit-scanner/src/main/java/com/maning/mlkitscanner/scan/MNScanManager.java
================================================
package com.maning.mlkitscanner.scan;
import android.app.Activity;
import android.content.Intent;
import com.maning.mlkitscanner.scan.callback.act.ActResultRequest;
import com.maning.mlkitscanner.scan.callback.act.MNScanCallback;
import com.maning.mlkitscanner.scan.model.MNScanConfig;
import com.maning.mlkitscanner.scan.ui.ScanPreviewActivity;
/**
* Created by maning on 2017/12/7.
* 启动扫描的主类
*/
public class MNScanManager {
//常量
public static final int RESULT_SUCCESS = 0;
public static final int RESULT_FAIL = 1;
public static final int RESULT_CANCLE = 2;
public static final String INTENT_KEY_RESULT_SUCCESS = "INTENT_KEY_RESULT_SUCCESS";
public static final String INTENT_KEY_RESULT_ERROR = "INTENT_KEY_RESULT_ERROR";
//是否是调试模式
public static final boolean isDebugMode = false;
//跳转传入的数据
public static final String INTENT_KEY_CONFIG_MODEL = "INTENT_KEY_CONFIG_MODEL";
public static void startScan(Activity activity, MNScanCallback scanCallback) {
startScan(activity, null, scanCallback);
}
public static void startScan(Activity activity, MNScanConfig mnScanConfig, MNScanCallback scanCallback) {
if (mnScanConfig == null) {
mnScanConfig = new MNScanConfig.Builder().builder();
}
Intent intent = new Intent(activity.getApplicationContext(), ScanPreviewActivity.class);
//传递数据
intent.putExtra(MNScanManager.INTENT_KEY_CONFIG_MODEL, mnScanConfig);
ActResultRequest actResultRequest = new ActResultRequest(activity);
actResultRequest.startForResult(intent, scanCallback);
activity.overridePendingTransition(mnScanConfig.getActivityOpenAnime(), android.R.anim.fade_out);
}
/**
* 关闭当前页面
*/
public static void closeScanPage() {
ScanPreviewActivity.closeScanPage();
}
/**
* 打开相册扫描图片
*/
public static void openAlbumPage() {
ScanPreviewActivity.openAlbumPage();
}
/**
* 打开手电筒
*/
public static void openScanLight() {
ScanPreviewActivity.openScanLight();
}
/**
* 关闭手电筒
*/
public static void closeScanLight() {
ScanPreviewActivity.closeScanLight();
}
/**
* 手电筒是否开启
*/
public static boolean isLightOn() {
return ScanPreviewActivity.isLightOn();
}
}
================================================
FILE: mlkit-scanner/src/main/java/com/maning/mlkitscanner/scan/analyser/BarcodeAnalyser.java
================================================
package com.maning.mlkitscanner.scan.analyser;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.view.PreviewView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.mlkit.vision.barcode.BarcodeScanner;
import com.google.mlkit.vision.barcode.BarcodeScannerOptions;
import com.google.mlkit.vision.barcode.BarcodeScanning;
import com.google.mlkit.vision.barcode.common.Barcode;
import com.google.mlkit.vision.common.InputImage;
import com.maning.mlkitscanner.scan.callback.OnCameraAnalyserCallback;
import com.maning.mlkitscanner.scan.utils.ImageUtils;
import java.util.List;
/**
* @author : maning
* @date : 8/18/21
* @desc :
*/
public class BarcodeAnalyser implements ImageAnalysis.Analyzer {
private OnCameraAnalyserCallback onCameraAnalyserCallback;
private final BarcodeScanner barcodeScanner;
/**
* 是否分析
*/
private volatile boolean isAnalyze = true;
private Context context;
private PreviewView mPreviewView;
public BarcodeScanner getBarcodeScanner() {
return barcodeScanner;
}
public void setAnalyze(boolean analyze) {
isAnalyze = analyze;
}
public void setOnCameraAnalyserCallback(OnCameraAnalyserCallback onCameraAnalyserCallback) {
this.onCameraAnalyserCallback = onCameraAnalyserCallback;
}
public BarcodeAnalyser() {
BarcodeScannerOptions options = new BarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_ALL_FORMATS)
.build();
barcodeScanner = BarcodeScanning.getClient(options);
}
public void setPreviewView(PreviewView mPreviewView) {
this.mPreviewView = mPreviewView;
}
private Bitmap cropBitmap(Bitmap bitmap, int cropWidth, int cropHeight) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
return Bitmap.createBitmap(bitmap, (w - cropWidth) / 2, (h - cropHeight) / 2, cropWidth, cropHeight, null, false);
}
@Override
public void analyze(@NonNull final ImageProxy imageProxy) {
Bitmap bitmap = null;
try {
bitmap = ImageUtils.imageProxyToBitmap(imageProxy, imageProxy.getImageInfo().getRotationDegrees());
} catch (Exception e) {
e.printStackTrace();
}
if (mPreviewView != null) {
//bitmap转为16:9
int height = mPreviewView.getHeight();
int width = mPreviewView.getWidth();
if (bitmap.getHeight() / (float) bitmap.getWidth() > mPreviewView.getHeight() / (float) mPreviewView.getWidth()) {
int newHeight = bitmap.getWidth() * height / width;
bitmap = cropBitmap(bitmap, bitmap.getWidth(), newHeight);
} else if (bitmap.getHeight() / (float) bitmap.getWidth() < mPreviewView.getHeight() / (float) mPreviewView.getWidth()) {
int newWith = bitmap.getHeight() * width / height;
bitmap = cropBitmap(bitmap, newWith, bitmap.getHeight());
}
//大小控制和预览一样
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
}
InputImage inputImage = InputImage.fromBitmap(bitmap, 0);
//InputImage inputImage = InputImage.fromMediaImage(imageProxy.getImage(), imageProxy.getImageInfo().getRotationDegrees());
final Bitmap finalBitmap = bitmap;
barcodeScanner.process(inputImage)
.addOnSuccessListener(new OnSuccessListener>() {
@Override
public void onSuccess(@NonNull List barcodes) {
if (barcodes.size() == 0) {
return;
}
if (!isAnalyze) {
return;
}
isAnalyze = false;
for (Barcode barcode : barcodes) {
Log.i("======", "barcode-getDisplayValue:" + barcode.getDisplayValue());
Log.i("======", "barcode-getRawValue:" + barcode.getRawValue());
}
if (onCameraAnalyserCallback != null) {
onCameraAnalyserCallback.onSuccess(finalBitmap, barcodes);
}
}
})
.addOnCompleteListener(new OnCompleteListener>() {
@Override
public void onComplete(@NonNull Task> task) {
imageProxy.close();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("======", "onFailure---:" + e.toString());
}
});
}
}
================================================
FILE: mlkit-scanner/src/main/java/com/maning/mlkitscanner/scan/callback/MNCustomViewBindCallback.java
================================================
package com.maning.mlkitscanner.scan.callback;
import android.view.View;
/**
* 自定义View回调
*/
public interface MNCustomViewBindCallback {
void onBindView(View customView);
}
================================================
FILE: mlkit-scanner/src/main/java/com/maning/mlkitscanner/scan/callback/OnCameraAnalyserCallback.java
================================================
package com.maning.mlkitscanner.scan.callback;
import android.graphics.Bitmap;
import com.google.mlkit.vision.barcode.common.Barcode;
import java.util.List;
/**
* @author : maning
* @date : 8/19/21
* @desc : 扫码分析结果回调
*/
public interface OnCameraAnalyserCallback {
void onSuccess(Bitmap bitmap, List barcodes);
}
================================================
FILE: mlkit-scanner/src/main/java/com/maning/mlkitscanner/scan/callback/act/ActResultRequest.java
================================================
package com.maning.mlkitscanner.scan.callback.act;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
/**
*