Repository: maning0303/MNMLKitScanner Branch: master Commit: 05fc2a8129f5 Files: 76 Total size: 224.3 KB Directory structure: gitextract_hdq0awll/ ├── .gitignore ├── .idea/ │ ├── codeStyles/ │ │ └── Project.xml │ ├── compiler.xml │ ├── encodings.xml │ ├── gradle.xml │ ├── inspectionProfiles/ │ │ └── Project_Default.xml │ ├── jarRepositories.xml │ ├── misc.xml │ └── vcs.xml ├── LICENSE ├── README.md ├── apk/ │ └── demo.apk ├── app/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── maning/ │ │ └── mlkitscanner/ │ │ └── ExampleInstrumentedTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── maning/ │ │ │ └── mlkitscanner/ │ │ │ └── demo/ │ │ │ ├── CustomConfigActivity.java │ │ │ └── MainActivity.java │ │ └── res/ │ │ ├── anim/ │ │ │ ├── activity_anmie_in.xml │ │ │ └── activity_anmie_out.xml │ │ ├── drawable/ │ │ │ └── ic_launcher_background.xml │ │ ├── drawable-v24/ │ │ │ └── ic_launcher_foreground.xml │ │ ├── layout/ │ │ │ ├── activity_custom_config.xml │ │ │ ├── activity_main.xml │ │ │ └── layout_custom_view.xml │ │ ├── mipmap-anydpi-v26/ │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ └── values/ │ │ ├── array.xml │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test/ │ └── java/ │ └── com/ │ └── maning/ │ └── mlkitscanner/ │ └── ExampleUnitTest.java ├── build.gradle ├── config.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── mlkit-scanner/ │ ├── .gitignore │ ├── build.gradle │ ├── consumer-rules.pro │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── maning/ │ │ └── mlkitscanner/ │ │ └── scan/ │ │ ├── MNScanManager.java │ │ ├── analyser/ │ │ │ └── BarcodeAnalyser.java │ │ ├── callback/ │ │ │ ├── MNCustomViewBindCallback.java │ │ │ ├── OnCameraAnalyserCallback.java │ │ │ └── act/ │ │ │ ├── ActResultRequest.java │ │ │ ├── MNScanCallback.java │ │ │ └── OnActResultEventDispatcherFragment.java │ │ ├── camera/ │ │ │ ├── CameraManager.java │ │ │ └── CameraSizeUtils.java │ │ ├── model/ │ │ │ └── MNScanConfig.java │ │ ├── ui/ │ │ │ └── ScanPreviewActivity.java │ │ ├── utils/ │ │ │ ├── AmbientLightManager.java │ │ │ ├── BeepManager.java │ │ │ ├── CommonUtils.java │ │ │ ├── ImageUtils.java │ │ │ ├── StatusBarUtil.java │ │ │ └── ZXingUtils.java │ │ └── view/ │ │ ├── ScanActionMenuView.java │ │ ├── ScanResultPointView.java │ │ └── ViewfinderView.java │ └── res/ │ ├── anim/ │ │ ├── mn_scan_activity_bottom_in.xml │ │ └── mn_scan_activity_bottom_out.xml │ ├── drawable/ │ │ └── mn_scan_result_point_default.xml │ ├── layout/ │ │ ├── mn_scan_action_menu.xml │ │ ├── mn_scan_activity_scan_preview.xml │ │ ├── mn_scan_result_point_item_view.xml │ │ └── mn_scan_result_point_view.xml │ ├── raw/ │ │ └── mn_scan_beep.ogg │ └── values/ │ ├── colors.xml │ └── styles.xml └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /.idea/caches /.idea/libraries /.idea/modules.xml /.idea/workspace.xml /.idea/navEditor.xml /.idea/assetWizardSettings.xml .DS_Store /build /captures .externalNativeBuild .cxx ================================================ FILE: .idea/codeStyles/Project.xml ================================================
xmlns:android ^$
xmlns:.* ^$ BY_NAME
.*:id http://schemas.android.com/apk/res/android
.*:name http://schemas.android.com/apk/res/android
name ^$
style ^$
.* ^$ BY_NAME
.* http://schemas.android.com/apk/res/android ANDROID_ATTRIBUTE_ORDER
.* .* BY_NAME
================================================ FILE: .idea/compiler.xml ================================================ ================================================ FILE: .idea/encodings.xml ================================================ ================================================ FILE: .idea/gradle.xml ================================================ ================================================ FILE: .idea/inspectionProfiles/Project_Default.xml ================================================ ================================================ FILE: .idea/jarRepositories.xml ================================================ ================================================ FILE: .idea/misc.xml ================================================ ================================================ 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/v/maning0303/MNMLKitScanner.svg)](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 ================================================