├── ZabarDemo ├── app │ ├── .gitignore │ ├── src │ │ ├── main │ │ │ ├── res │ │ │ │ ├── values │ │ │ │ │ ├── strings.xml │ │ │ │ │ ├── colors.xml │ │ │ │ │ └── styles.xml │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ │ ├── ic_launcher.xml │ │ │ │ │ └── ic_launcher_round.xml │ │ │ │ ├── layout │ │ │ │ │ ├── activity_main.xml │ │ │ │ │ └── activity_result.xml │ │ │ │ ├── drawable-v24 │ │ │ │ │ └── ic_launcher_foreground.xml │ │ │ │ └── drawable │ │ │ │ │ └── ic_launcher_background.xml │ │ │ ├── AndroidManifest.xml │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── carinsur │ │ │ │ └── zqf │ │ │ │ └── zabardemo │ │ │ │ ├── MainActivity.java │ │ │ │ └── ResultsActivity.java │ │ ├── test │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── carinsur │ │ │ │ └── zqf │ │ │ │ └── zabardemo │ │ │ │ └── ExampleUnitTest.java │ │ └── androidTest │ │ │ └── java │ │ │ └── com │ │ │ └── carinsur │ │ │ └── zqf │ │ │ └── zabardemo │ │ │ └── ExampleInstrumentedTest.java │ ├── proguard-rules.pro │ └── build.gradle ├── zbarcode │ ├── .gitignore │ ├── libs │ │ └── zbardecoder.jar │ ├── src │ │ ├── main │ │ │ ├── res │ │ │ │ ├── raw │ │ │ │ │ └── qrcode.mp3 │ │ │ │ ├── drawable-xhdpi │ │ │ │ │ ├── shadow.png │ │ │ │ │ ├── back_blue.png │ │ │ │ │ ├── scan_line.png │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── qr_code_bg.9.png │ │ │ │ ├── drawable-hdpi │ │ │ │ │ └── ic_launcher.png │ │ │ │ ├── drawable-mdpi │ │ │ │ │ └── ic_launcher.png │ │ │ │ ├── drawable-xxhdpi │ │ │ │ │ └── ic_launcher.png │ │ │ │ ├── values │ │ │ │ │ ├── scan_result_list.xml │ │ │ │ │ ├── dimens.xml │ │ │ │ │ ├── strings.xml │ │ │ │ │ ├── styles.xml │ │ │ │ │ └── ids.xml │ │ │ │ ├── values-ja │ │ │ │ │ └── strings.xml │ │ │ │ ├── values-ko │ │ │ │ │ └── strings.xml │ │ │ │ ├── values-en │ │ │ │ │ └── strings.xml │ │ │ │ └── layout │ │ │ │ │ ├── activity_result1.xml │ │ │ │ │ └── activity_capture.xml │ │ │ ├── jniLibs │ │ │ │ ├── mips │ │ │ │ │ └── libZBarDecoder.so │ │ │ │ ├── x86 │ │ │ │ │ └── libZBarDecoder.so │ │ │ │ ├── armeabi │ │ │ │ │ └── libZBarDecoder.so │ │ │ │ └── armeabi-v7a │ │ │ │ │ └── libZBarDecoder.so │ │ │ ├── AndroidManifest.xml │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── znq │ │ │ │ └── zbarcode │ │ │ │ ├── camera │ │ │ │ ├── PreviewCallback.java │ │ │ │ ├── CameraPreview.java │ │ │ │ ├── AutoFocusManager.java │ │ │ │ ├── CameraManager.java │ │ │ │ └── CameraConfigurationManager.java │ │ │ │ ├── decode │ │ │ │ ├── DecodeThread.java │ │ │ │ ├── MainHandler.java │ │ │ │ └── DecodeHandler.java │ │ │ │ ├── utils │ │ │ │ ├── BeepManager.java │ │ │ │ └── Config.java │ │ │ │ ├── view │ │ │ │ └── ScanLineView.java │ │ │ │ └── CaptureActivity.java │ │ ├── test │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── znq │ │ │ │ └── zbarcode │ │ │ │ └── ExampleUnitTest.java │ │ └── androidTest │ │ │ └── java │ │ │ └── com │ │ │ └── znq │ │ │ └── zbarcode │ │ │ └── ApplicationTest.java │ ├── proguard-rules.pro │ └── build.gradle ├── settings.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── .gitignore ├── .idea │ ├── runConfigurations.xml │ ├── gradle.xml │ ├── modules.xml │ └── misc.xml ├── build.gradle ├── gradle.properties ├── gradlew.bat └── gradlew ├── image ├── GIF.gif ├── ndk.png └── demo.png ├── README.md.bak ├── README.md └── LICENSE.txt /ZabarDemo/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /ZabarDemo/settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app',':zbarcode' 2 | -------------------------------------------------------------------------------- /image/GIF.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/image/GIF.gif -------------------------------------------------------------------------------- /image/ndk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/image/ndk.png -------------------------------------------------------------------------------- /image/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/image/demo.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ZabarDemo 3 | 4 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/libs/zbardecoder.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/libs/zbardecoder.jar -------------------------------------------------------------------------------- /ZabarDemo/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/raw/qrcode.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/res/raw/qrcode.mp3 -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/jniLibs/mips/libZBarDecoder.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/jniLibs/mips/libZBarDecoder.so -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/jniLibs/x86/libZBarDecoder.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/jniLibs/x86/libZBarDecoder.so -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/shadow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/shadow.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/back_blue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/back_blue.png -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/scan_line.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/scan_line.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/jniLibs/armeabi/libZBarDecoder.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/jniLibs/armeabi/libZBarDecoder.so -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/qr_code_bg.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/res/drawable-xhdpi/qr_code_bg.9.png -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/jniLibs/armeabi-v7a/libZBarDecoder.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zybieku/ZbarCode/HEAD/ZabarDemo/zbarcode/src/main/jniLibs/armeabi-v7a/libZBarDecoder.so -------------------------------------------------------------------------------- /ZabarDemo/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/values/scan_result_list.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | http://gopopon.com/book/cover/1 6 | 7 | 8 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /ZabarDemo/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri May 18 10:23:03 CST 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip 7 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/test/java/com/znq/zbarcode/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.znq.zbarcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect() throws Exception { 13 | assertEquals(4, 2 + 2); 14 | } 15 | } -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/androidTest/java/com/znq/zbarcode/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.znq.zbarcode; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /ZabarDemo/app/src/test/java/com/carinsur/zqf/zabardemo/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.carinsur.zqf.zabardemo; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/values-ja/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | QRCode 3 | OK 4 | Setting 5 | Cancel 6 | Allow popon to access your %1$s from device menu: 7 | “Settings” ->popon->“Privacy” ->%2$s 8 | \n%1$s 9 | camera 10 | loading… 11 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/values-ko/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | QRCode 3 | OK 4 | Setting 5 | Cancel 6 | Allow popon to access your %1$s from device menu: 7 | “Settings” ->popon->“Privacy” ->%2$s 8 | \n%1$s 9 | camera 10 | loading… 11 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/values-en/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | QRCode 3 | OK 4 | Setting 5 | Cancel 6 | Allow popon to access your %1$s from device menu: 7 | “Settings” ->popon->“Privacy” ->%2$s 8 | \n%1$s 9 | camera 10 | loading… 11 | 12 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 二维码 3 | 我知道了 4 | 设置 5 | 取消 6 | 抱歉,你的%1$s权限没有打开,无法正常服务 7 | \n请点击”设置”->在应用程序中找到”popon”->权限管理->%2$s->”允许”即可 8 | \n 或者点击”手机管家”->权限管理->%1$s->”允许”即可 9 | 摄像头(相机) 10 | 加载中… 11 | 12 | -------------------------------------------------------------------------------- /ZabarDemo/.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /ZabarDemo/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | 5 | repositories { 6 | google() 7 | jcenter() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.0.1' 11 | 12 | 13 | // NOTE: Do not place your application dependencies here; they belong 14 | // in the individual module build.gradle files 15 | } 16 | } 17 | 18 | allprojects { 19 | repositories { 20 | google() 21 | jcenter() 22 | } 23 | } 24 | 25 | task clean(type: Delete) { 26 | delete rootProject.buildDir 27 | } 28 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 9 | 12 | 13 | 14 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Tools\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /ZabarDemo/.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /ZabarDemo/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /ZabarDemo/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 14 | 15 | 16 | 19 | 20 | -------------------------------------------------------------------------------- /ZabarDemo/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/androidTest/java/com/carinsur/zqf/zabardemo/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.carinsur.zqf.zabardemo; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.carinsur.zqf.zabardemo", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/values/ids.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /ZabarDemo/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 27 5 | defaultConfig { 6 | applicationId "com.carinsur.zqf.zabardemo" 7 | minSdkVersion 17 8 | targetSdkVersion 27 9 | versionCode 1 10 | versionName "1.0" 11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | implementation fileTree(include: ['*.jar'], dir: 'libs') 23 | implementation 'com.android.support:appcompat-v7:27.1.1' 24 | implementation 'com.android.support.constraint:constraint-layout:1.1.0' 25 | testImplementation 'junit:junit:4.12' 26 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 27 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 28 | implementation project(':zbarcode') 29 | } 30 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 26 5 | buildToolsVersion "26.0.2" 6 | defaultConfig { 7 | minSdkVersion 14 8 | targetSdkVersion 26 9 | versionCode 1 10 | versionName "1.0" 11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 12 | 13 | ndk { 14 | //设置支持的SO库架构 15 | abiFilters 'armeabi' , 'armeabi-v7a'//, 'x86', 'armeabi-v7a', 'x86_64' 16 | } 17 | 18 | } 19 | 20 | buildTypes { 21 | release { 22 | minifyEnabled false 23 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 24 | } 25 | } 26 | } 27 | 28 | dependencies { 29 | compile fileTree(dir: 'libs', include: ['*.jar']) 30 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 31 | exclude group: 'com.android.support', module: 'support-annotations' 32 | }) 33 | compile 'com.android.support:appcompat-v7:26.1.0' 34 | testCompile 'junit:junit:4.12' 35 | } 36 | 37 | -------------------------------------------------------------------------------- /README.md.bak: -------------------------------------------------------------------------------- 1 | # ZbarCode 2 | 用Zbar库实现的Android扫一扫 3 | - **集成**: 4 | 5 | 下载打开源码项目,大佬可以先运行看下效果,如果需集成,就使用箭头得扫一扫Module 6 | 7 |  8 | 9 | 大佬进入自己的Android studio项目,直接点击``File``->``New``->``Import Module`` 选择Demo文件导入即可. 10 | 记得在``App`` 的`` gradle``添加依赖. `` compile project(':zbarcode')`` 11 | 12 |  13 | 14 | 15 | ---------- 16 | 17 | 18 | 19 | ###使用代码 20 | 进入扫一扫 21 | ``` java 22 | Intent intent1 = new Intent(MainActivity.this, CaptureActivity.class); 23 | startActivityForResult(intent1, QR_CODE); 24 | ``` 25 | 获取返回的结果 26 | ``` java 27 | 28 | @Override 29 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 30 | super.onActivityResult(requestCode, resultCode, data); 31 | if (requestCode == QR_CODE) { 32 | Bundle b=data.getExtras(); 33 | String result = b.getString(CaptureActivity.EXTRA_STRING); 34 | Toast.makeText(this, result + "", Toast.LENGTH_SHORT).show(); 35 | } 36 | ``` 37 | > **注:** 请根据大佬自己项目的需求,配置右边SO库架构,对应删掉左边多余的文件夹 38 | 39 |  40 | ---------- 41 | - **效果图** 42 |  43 | 44 | ---------- 45 | 46 | > **注:** 喜欢的大佬别忘了点个star 47 | 48 | ---------- 49 | #博客 www.znq123.cn -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ZbarCode 2 | 用Zbar库实现的Android扫一扫 3 | - **集成**: 4 | 5 | 下载打开源码项目,大佬可以先运行看下效果,如果需集成,就使用箭头得扫一扫Module 6 | 7 |  8 | 9 | 大佬进入自己的Android studio项目,直接点击``File``->``New``->``Import Module`` 选择Demo文件导入即可. 10 | 记得在``App`` 的`` gradle``添加依赖. `` compile project(':zbarcode')`` 11 | 12 |  13 | 14 | 15 | ---------- 16 | 17 | 18 | 19 | ###使用代码 20 | 进入扫一扫 21 | ``` java 22 | Intent intent1 = new Intent(MainActivity.this, CaptureActivity.class); 23 | startActivityForResult(intent1, QR_CODE); 24 | ``` 25 | 获取返回的结果 26 | ``` java 27 | 28 | @Override 29 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 30 | super.onActivityResult(requestCode, resultCode, data); 31 | if (requestCode == QR_CODE) { 32 | if(null==data) return; 33 | Bundle b=data.getExtras(); 34 | String result = b.getString(CaptureActivity.EXTRA_STRING); 35 | Toast.makeText(this, result + "", Toast.LENGTH_SHORT).show(); 36 | } 37 | ``` 38 | > **注:** 请根据大佬自己项目的需求,配置右边SO库架构,对应删掉左边多余的文件夹 39 | 40 |  41 | ---------- 42 | - **效果图** 43 |  44 | 45 | ---------- 46 | 47 | > **注:** 喜欢的大佬别忘了点个star 48 | 49 | ---------- 50 | #博客 www.znq123.cn -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/java/com/carinsur/zqf/zabardemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.carinsur.zqf.zabardemo; 2 | 3 | import android.content.Intent; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.os.Bundle; 6 | import android.view.View; 7 | import android.widget.Toast; 8 | 9 | import com.znq.zbarcode.CaptureActivity; 10 | 11 | public class MainActivity extends AppCompatActivity { 12 | private int QR_CODE =1; 13 | @Override 14 | protected void onCreate(Bundle savedInstanceState) { 15 | super.onCreate(savedInstanceState); 16 | setContentView(R.layout.activity_main); 17 | } 18 | 19 | public void button(View view){ 20 | Intent intent1 = new Intent(MainActivity.this, CaptureActivity.class); 21 | startActivityForResult(intent1, QR_CODE); 22 | } 23 | 24 | @Override 25 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 26 | super.onActivityResult(requestCode, resultCode, data); 27 | if (requestCode == QR_CODE&&resultCode==RESULT_OK) { 28 | if(null==data) return; 29 | Bundle b=data.getExtras(); 30 | String result = b.getString(CaptureActivity.EXTRA_STRING); 31 | Toast.makeText(this, result + "", Toast.LENGTH_SHORT).show(); 32 | 33 | Intent in =new Intent(this,ResultsActivity.class); 34 | in.putExtra(CaptureActivity.EXTRA_STRING, result); 35 | startActivity(in); 36 | 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/camera/PreviewCallback.java: -------------------------------------------------------------------------------- 1 | package com.znq.zbarcode.camera; 2 | 3 | import android.graphics.Point; 4 | import android.graphics.Rect; 5 | import android.hardware.Camera; 6 | import android.os.Handler; 7 | import android.os.HandlerThread; 8 | import android.os.Message; 9 | import android.util.Log; 10 | 11 | import com.dtr.zbar.build.ZBarDecoder; 12 | 13 | /** 14 | * desc:二维码解码的回调类 15 | * Author: znq 16 | * Date: 2016-11-03 16:24 17 | */ 18 | 19 | public class PreviewCallback implements Camera.PreviewCallback { 20 | private static final String TAG = "PreviewCallback"; 21 | private Handler childHandler; 22 | private int messageWhat; 23 | 24 | public PreviewCallback() { 25 | } 26 | 27 | public void setHandler(Handler childHandler, int messageWhat) { 28 | this.messageWhat = messageWhat; 29 | this.childHandler = childHandler; 30 | } 31 | 32 | @Override 33 | public void onPreviewFrame(final byte[] data, Camera camera) { 34 | Handler theChildHandler = childHandler; 35 | Camera.Size size = null; 36 | try { 37 | size = camera.getParameters().getPreviewSize(); 38 | } catch (Exception ex) { 39 | ex.printStackTrace(); 40 | } 41 | if (size != null && theChildHandler != null) { 42 | Message message = theChildHandler.obtainMessage(messageWhat, size.width, size.height, data); 43 | message.sendToTarget(); 44 | childHandler = null; 45 | } 46 | 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/decode/DecodeThread.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 ZXing authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.znq.zbarcode.decode; 18 | 19 | import android.os.Handler; 20 | import android.os.Looper; 21 | 22 | import com.znq.zbarcode.CaptureActivity; 23 | 24 | import java.util.concurrent.CountDownLatch; 25 | 26 | /** 27 | * This thread does all the heavy lifting of decoding the images. 28 | * 29 | * @author dswitkin@google.com (Daniel Switkin) 30 | */ 31 | final class DecodeThread extends Thread { 32 | 33 | 34 | private final CaptureActivity activity; 35 | 36 | 37 | private Handler handler; 38 | 39 | private final CountDownLatch handlerInitLatch; 40 | 41 | DecodeThread(CaptureActivity activity) { 42 | this.activity = activity; 43 | handlerInitLatch = new CountDownLatch(1); 44 | 45 | 46 | } 47 | 48 | Handler getHandler() { 49 | try { 50 | handlerInitLatch.await(); 51 | } 52 | catch (InterruptedException ie) { 53 | ie.printStackTrace(); 54 | } 55 | return handler; 56 | } 57 | 58 | @Override 59 | public void run() { 60 | Looper.prepare(); 61 | handler = new DecodeHandler(activity); 62 | handlerInitLatch.countDown(); 63 | Looper.loop(); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /ZabarDemo/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 1.8 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/layout/activity_result.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 14 | 15 | 25 | 26 | 34 | 35 | 41 | 42 | 43 | 49 | 50 | 55 | 56 | 57 | 65 | 66 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/layout/activity_result1.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 14 | 15 | 25 | 26 | 34 | 35 | 41 | 42 | 43 | 49 | 50 | 55 | 56 | 57 | 65 | 66 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/utils/BeepManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 ZXing authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.znq.zbarcode.utils; 18 | 19 | import android.content.Context; 20 | import android.media.MediaPlayer; 21 | 22 | import com.znq.zbarcode.R; 23 | 24 | /** 25 | * Desc: 扫描滴滴声 26 | * Update by znq on 2016/11/8. 27 | */ 28 | public class BeepManager implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener { 29 | private MediaPlayer mMediaPlayer; 30 | private boolean isComplete = false; 31 | 32 | public BeepManager(Context context) { 33 | mMediaPlayer = MediaPlayer.create(context, R.raw.qrcode); 34 | mMediaPlayer.setLooping(false); 35 | mMediaPlayer.setOnCompletionListener(this); 36 | mMediaPlayer.setOnErrorListener(this); 37 | } 38 | 39 | public void startRing() { 40 | if (null != mMediaPlayer) { 41 | mMediaPlayer.start(); 42 | } 43 | } 44 | 45 | 46 | public void releaseRing() { 47 | if (null != mMediaPlayer) { 48 | mMediaPlayer.release(); 49 | mMediaPlayer = null; 50 | } 51 | } 52 | 53 | public boolean isComplete() { 54 | return isComplete; 55 | } 56 | public int getTimeDuration(){ 57 | return mMediaPlayer.getDuration(); 58 | } 59 | 60 | @Override 61 | public void onCompletion(MediaPlayer mp) { 62 | if (null != mMediaPlayer) { 63 | mMediaPlayer.stop(); 64 | mMediaPlayer.release(); 65 | } 66 | isComplete = true; 67 | } 68 | 69 | @Override 70 | public boolean onError(MediaPlayer mp, int what, int extra) { 71 | if (null != mMediaPlayer) { 72 | mMediaPlayer.release(); 73 | mMediaPlayer = null; 74 | } 75 | isComplete = true; 76 | return false; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /ZabarDemo/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/utils/Config.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 ZXing authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.znq.zbarcode.utils; 18 | 19 | /** 20 | * The main settings activity. 21 | * 22 | * @author dswitkin@google.com (Daniel Switkin) 23 | * @author Sean Owen 24 | */ 25 | public final class Config { 26 | public static final String KEY_DECODE_1D = "preferences_decode_1D"; 27 | public static final String KEY_DECODE_1D_PRODUCT = "preferences_decode_1D_product"; 28 | public static final String KEY_DECODE_1D_INDUSTRIAL = "preferences_decode_1D_industrial"; 29 | public static final String KEY_DECODE_QR = "preferences_decode_QR"; 30 | public static final String KEY_DECODE_DATA_MATRIX = "preferences_decode_Data_Matrix"; 31 | public static final String KEY_DECODE_AZTEC = "preferences_decode_Aztec"; 32 | public static final String KEY_DECODE_PDF417 = "preferences_decode_PDF417"; 33 | 34 | public static final String KEY_CUSTOM_PRODUCT_SEARCH = "preferences_custom_product_search"; 35 | 36 | public static final String KEY_PLAY_BEEP = "preferences_play_beep"; 37 | public static final String KEY_VIBRATE = "preferences_vibrate"; 38 | public static final String KEY_COPY_TO_CLIPBOARD = "preferences_copy_to_clipboard"; 39 | public static final String KEY_FRONT_LIGHT_MODE = "preferences_front_light_mode"; 40 | public static final String KEY_BULK_MODE = "preferences_bulk_mode"; 41 | public static final String KEY_REMEMBER_DUPLICATES = "preferences_remember_duplicates"; 42 | public static final String KEY_SUPPLEMENTAL = "preferences_supplemental"; 43 | public static final String KEY_AUTO_FOCUS = "preferences_auto_focus"; 44 | public static final String KEY_INVERT_SCAN = "preferences_invert_scan"; 45 | public static final String KEY_SEARCH_COUNTRY = "preferences_search_country"; 46 | public static final String KEY_DISABLE_AUTO_ORIENTATION = "preferences_orientation"; 47 | 48 | public static final String KEY_DISABLE_CONTINUOUS_FOCUS = "preferences_disable_continuous_focus"; 49 | public static final String KEY_DISABLE_EXPOSURE = "preferences_disable_exposure"; 50 | public static final String KEY_DISABLE_METERING = "preferences_disable_metering"; 51 | public static final String KEY_DISABLE_BARCODE_SCENE_MODE = "preferences_disable_barcode_scene_mode"; 52 | public static final String KEY_AUTO_OPEN_WEB = "preferences_auto_open_web"; 53 | 54 | } 55 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/decode/MainHandler.java: -------------------------------------------------------------------------------- 1 | package com.znq.zbarcode.decode; 2 | 3 | import android.os.Handler; 4 | import android.os.Message; 5 | import android.text.TextUtils; 6 | import android.util.Log; 7 | 8 | import com.znq.zbarcode.CaptureActivity; 9 | import com.znq.zbarcode.R; 10 | import com.znq.zbarcode.camera.CameraManager; 11 | 12 | /** 13 | * desc:主线程的Handler 14 | * Author: znq 15 | * Date: 2016-11-03 15:55 16 | */ 17 | public class MainHandler extends Handler { 18 | private static final String TAG = "MainHandler"; 19 | 20 | private final CaptureActivity activity; 21 | 22 | /** 23 | * 真正负责扫描任务的核心线程 24 | */ 25 | private final DecodeThread decodeThread; 26 | 27 | private State state; 28 | 29 | private final CameraManager cameraManager; 30 | 31 | public MainHandler(CaptureActivity activity, CameraManager cameraManager) { 32 | this.activity = activity; 33 | // 启动扫描线程 34 | decodeThread = new DecodeThread(activity); 35 | decodeThread.start(); 36 | state = State.SUCCESS; 37 | this.cameraManager = cameraManager; 38 | 39 | // 开启相机预览界面.并且自动聚焦 40 | cameraManager.startPreview(); 41 | 42 | restartPreviewAndDecode(); 43 | } 44 | 45 | /** 46 | * 当前扫描的状态 47 | */ 48 | private enum State { 49 | /** 50 | * 预览 51 | */ 52 | PREVIEW, 53 | /** 54 | * 扫描成功 55 | */ 56 | SUCCESS, 57 | /** 58 | * 结束扫描 59 | */ 60 | DONE 61 | } 62 | 63 | 64 | @Override 65 | public void handleMessage(Message msg) { 66 | if (msg.what == R.id.decode_succeeded) { 67 | String result = (String) msg.obj; 68 | if (!TextUtils.isEmpty(result)) { 69 | activity.checkResult(result); 70 | } 71 | } else if (msg.what == R.id.restart_preview) { 72 | restartPreviewAndDecode(); 73 | } else if (msg.what == R.id.decode_failed) { 74 | // We're decoding as fast as possible, so when one decode fails, 75 | // start another. 76 | state = State.PREVIEW; 77 | cameraManager.requestPreviewFrame(decodeThread.getHandler(), 78 | R.id.decode); 79 | } 80 | } 81 | 82 | /** 83 | * 完成一次扫描后,只需要再调用此方法即可 84 | */ 85 | private void restartPreviewAndDecode() { 86 | if (state == State.SUCCESS) { 87 | state = State.PREVIEW; 88 | // 向decodeThread绑定的handler(DecodeHandler)发送解码消息 89 | cameraManager.requestPreviewFrame(decodeThread.getHandler(), 90 | R.id.decode); 91 | } 92 | } 93 | 94 | public void quitSynchronously() { 95 | state = State.DONE; 96 | cameraManager.stopPreview(); 97 | Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit); 98 | quit.sendToTarget(); 99 | 100 | try { 101 | // Wait at most half a second; should be enough time, and onPause() 102 | // will timeout quickly 103 | decodeThread.join(500L); 104 | } catch (InterruptedException e) { 105 | // continue 106 | } 107 | 108 | // Be absolutely sure we don't send any queued up messages 109 | removeMessages(R.id.decode_succeeded); 110 | removeMessages(R.id.decode_failed); 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/decode/DecodeHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 ZXing authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.znq.zbarcode.decode; 18 | 19 | import android.graphics.Rect; 20 | import android.hardware.Camera; 21 | import android.os.Handler; 22 | import android.os.Looper; 23 | import android.os.Message; 24 | import android.util.Log; 25 | 26 | 27 | import com.dtr.zbar.build.ZBarDecoder; 28 | import com.znq.zbarcode.CaptureActivity; 29 | import com.znq.zbarcode.R; 30 | 31 | final class DecodeHandler extends Handler { 32 | 33 | private static final String TAG = DecodeHandler.class.getSimpleName(); 34 | 35 | private final CaptureActivity activity; 36 | private ZBarDecoder zBarDecoder; 37 | 38 | private boolean running = true; 39 | 40 | DecodeHandler(CaptureActivity activity) { 41 | zBarDecoder = new ZBarDecoder(); 42 | this.activity = activity; 43 | } 44 | 45 | @Override 46 | public void handleMessage(Message message) { 47 | if (!running) { 48 | return; 49 | } 50 | if (message.what == R.id.decode) { 51 | decode((byte[]) message.obj, message.arg1, message.arg2); 52 | 53 | } else if (message.what == R.id.quit) { 54 | running = false; 55 | Looper.myLooper().quit(); 56 | } 57 | } 58 | 59 | 60 | /** 61 | * 解码 62 | */ 63 | 64 | private void decode(byte[] data, int width, int height) { 65 | // long start = System.currentTimeMillis(); 66 | // 这里需要将获取的data翻转一下,因为相机默认拿的的横屏的数据 67 | byte[] rotatedData = new byte[data.length]; 68 | for (int y = 0; y < height; y++) { 69 | for (int x = 0; x < width; x++) 70 | rotatedData[x * height + height - y - 1] = data[x + y * width]; 71 | } 72 | 73 | // 宽高也要调整 74 | int tmp = width; 75 | width = height; 76 | height = tmp; 77 | Rect mCropRect = activity.initCrop(); 78 | String result =null; 79 | if (zBarDecoder != null) { 80 | try { 81 | result = zBarDecoder.decodeCrop(rotatedData, width, height, mCropRect.left, mCropRect.top, mCropRect.width(), mCropRect.height()); 82 | }catch (Exception ex){ 83 | ex.printStackTrace(); 84 | zBarDecoder=null; 85 | } 86 | Handler handler = activity.getHandler(); 87 | if (result != null) { 88 | // long end = System.currentTimeMillis(); 89 | if (handler != null) { 90 | Message message = Message.obtain(handler, 91 | R.id.decode_succeeded, result); 92 | message.sendToTarget(); 93 | } 94 | } else { 95 | if (handler != null) { 96 | Message message = Message.obtain(handler, R.id.decode_failed); 97 | message.sendToTarget(); 98 | } 99 | } 100 | } 101 | } 102 | 103 | 104 | } 105 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/camera/CameraPreview.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Barebones implementation of displaying camera preview. 3 | * 4 | * Created by lisah0 on 2012-02-24 5 | */ 6 | package com.znq.zbarcode.camera; 7 | 8 | import android.content.Context; 9 | import android.hardware.Camera; 10 | import android.hardware.Camera.AutoFocusCallback; 11 | import android.hardware.Camera.PreviewCallback; 12 | import android.util.Log; 13 | import android.view.SurfaceHolder; 14 | import android.view.SurfaceView; 15 | 16 | import java.io.IOException; 17 | 18 | /** 19 | * A basic Camera preview class 20 | */ 21 | public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { 22 | private SurfaceHolder mHolder; 23 | private Camera mCamera; 24 | private PreviewCallback previewCallback; 25 | private AutoFocusCallback autoFocusCallback; 26 | 27 | @SuppressWarnings("deprecation") 28 | public CameraPreview(Context context, Camera camera, PreviewCallback previewCb, AutoFocusCallback autoFocusCb) { 29 | super(context); 30 | mCamera = camera; 31 | previewCallback = previewCb; 32 | autoFocusCallback = autoFocusCb; 33 | 34 | /* 35 | * Set camera to continuous focus if supported, otherwise use software 36 | * auto-focus. Only works for API level >=9. 37 | */ 38 | 39 | Camera.Parameters parameters = camera.getParameters(); 40 | for (String f: parameters.getSupportedFocusModes()) { 41 | if (f == Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) { 42 | parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); 43 | autoFocusCallback = null; 44 | break; 45 | } 46 | } 47 | 48 | 49 | // Install a SurfaceHolder.Callback so we get notified when the 50 | // underlying surface is created and destroyed. 51 | mHolder = getHolder(); 52 | mHolder.addCallback(this); 53 | 54 | // deprecated setting, but required on Android versions prior to 3.0 55 | mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 56 | } 57 | 58 | public void surfaceCreated(SurfaceHolder holder) { 59 | // The Surface has been created, now tell the camera where to draw the 60 | // preview. 61 | try { 62 | mCamera.setPreviewDisplay(holder); 63 | } catch (IOException e) { 64 | Log.d("DBG", "Error setting camera preview: " + e.getMessage()); 65 | } 66 | } 67 | 68 | public void surfaceDestroyed(SurfaceHolder holder) { 69 | // Camera preview released in activity 70 | } 71 | 72 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 73 | /* 74 | * If your preview can change or rotate, take care of those events here. 75 | * Make sure to stop the preview before resizing or reformatting it. 76 | */ 77 | if (mHolder.getSurface() == null) { 78 | // preview surface does not exist 79 | return; 80 | } 81 | 82 | // stop preview before making changes 83 | try { 84 | mCamera.stopPreview(); 85 | } catch (Exception e) { 86 | // ignore: tried to stop a non-existent preview 87 | } 88 | 89 | try { 90 | // Hard code camera surface rotation 90 degs to match Activity view 91 | // in portrait 92 | mCamera.setDisplayOrientation(90); 93 | 94 | mCamera.setPreviewDisplay(mHolder); 95 | mCamera.setPreviewCallback(previewCallback); 96 | mCamera.startPreview(); 97 | mCamera.autoFocus(autoFocusCallback); 98 | } catch (Exception e) { 99 | Log.d("DBG", "Error starting camera preview: " + e.getMessage()); 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/res/layout/activity_capture.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 11 | 12 | 16 | 17 | 23 | 24 | 31 | 32 | 41 | 42 | 43 | 50 | 51 | 60 | 61 | 70 | 71 | 72 | 79 | 80 | 90 | 91 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/camera/AutoFocusManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 ZXing authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.znq.zbarcode.camera; 18 | 19 | import android.content.Context; 20 | import android.content.SharedPreferences; 21 | import android.hardware.Camera; 22 | import android.os.AsyncTask; 23 | import android.os.Build; 24 | import android.preference.PreferenceManager; 25 | import android.util.Log; 26 | 27 | 28 | import com.znq.zbarcode.utils.Config; 29 | 30 | import java.util.ArrayList; 31 | import java.util.Collection; 32 | import java.util.concurrent.RejectedExecutionException; 33 | 34 | /** 35 | * 由于对焦不是一次性完成的任务(手抖),而系统提供的对焦仅有Camera.autoFocus()方法, 36 | * 因此需要一个线程来不断调用Camera.autoFocus()直到用户满意按下快门为止 37 | */ 38 | final class AutoFocusManager implements Camera.AutoFocusCallback { 39 | 40 | private static final String TAG = AutoFocusManager.class.getSimpleName(); 41 | 42 | private static final long AUTO_FOCUS_INTERVAL_MS = 2000L; 43 | private static final Collection FOCUS_MODES_CALLING_AF; 44 | static { 45 | FOCUS_MODES_CALLING_AF = new ArrayList(2); 46 | FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO); 47 | FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO); 48 | } 49 | 50 | private boolean active; 51 | private final boolean useAutoFocus; 52 | private final Camera camera; 53 | private AsyncTask, ?, ?> outstandingTask; 54 | 55 | AutoFocusManager(Context context, Camera camera) { 56 | this.camera = camera; 57 | SharedPreferences sharedPrefs = PreferenceManager 58 | .getDefaultSharedPreferences(context); 59 | String currentFocusMode = camera.getParameters().getFocusMode(); 60 | useAutoFocus = sharedPrefs.getBoolean(Config.KEY_AUTO_FOCUS, true) 61 | && FOCUS_MODES_CALLING_AF.contains(currentFocusMode); 62 | Log.i(TAG, "Current focus mode '" + currentFocusMode 63 | + "'; use auto focus? " + useAutoFocus); 64 | start(); 65 | } 66 | 67 | @Override 68 | public synchronized void onAutoFocus(boolean success, Camera theCamera) { 69 | if (active) { 70 | AutoFocusTask newTask = new AutoFocusTask(); 71 | try { 72 | if (Build.VERSION.SDK_INT >= 11) { 73 | newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 74 | } else { 75 | newTask.execute(); 76 | } 77 | outstandingTask = newTask; 78 | } catch (RejectedExecutionException ree) { 79 | Log.w(TAG, "Could not request auto focus", ree); 80 | } 81 | 82 | } 83 | } 84 | 85 | private synchronized void start() { 86 | if (useAutoFocus) { 87 | active = true; 88 | try { 89 | camera.autoFocus(this); 90 | } 91 | catch (RuntimeException re) { 92 | // Have heard RuntimeException reported in Android 4.0.x+; 93 | // continue? 94 | Log.w(TAG, "Unexpected exception while focusing", re); 95 | } 96 | } 97 | } 98 | 99 | synchronized void stop() { 100 | if (useAutoFocus) { 101 | try { 102 | camera.cancelAutoFocus(); 103 | } 104 | catch (RuntimeException re) { 105 | // Have heard RuntimeException reported in Android 4.0.x+; 106 | // continue? 107 | Log.w(TAG, "Unexpected exception while cancelling focusing", re); 108 | } 109 | } 110 | if (outstandingTask != null) { 111 | outstandingTask.cancel(true); 112 | outstandingTask = null; 113 | } 114 | active = false; 115 | } 116 | 117 | private final class AutoFocusTask extends AsyncTask { 118 | @Override 119 | protected Object doInBackground(Object... voids) { 120 | try { 121 | Thread.sleep(AUTO_FOCUS_INTERVAL_MS); 122 | } 123 | catch (InterruptedException e) { 124 | // continue 125 | } 126 | synchronized (AutoFocusManager.this) { 127 | if (active) { 128 | start(); 129 | } 130 | } 131 | return null; 132 | } 133 | } 134 | 135 | } 136 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/view/ScanLineView.java: -------------------------------------------------------------------------------- 1 | package com.znq.zbarcode.view; 2 | 3 | import android.content.Context; 4 | import android.graphics.Bitmap; 5 | import android.graphics.BitmapFactory; 6 | import android.graphics.Canvas; 7 | import android.graphics.Paint; 8 | import android.graphics.Rect; 9 | import android.graphics.drawable.BitmapDrawable; 10 | import android.support.v4.content.ContextCompat; 11 | import android.util.AttributeSet; 12 | import android.util.Log; 13 | import android.view.View; 14 | 15 | import com.znq.zbarcode.R; 16 | 17 | /** 18 | * desc:扫描线的滑动,打算用来替换平移动画 19 | * Author: znq 20 | * Date: 2016-11-09 11:25 21 | */ 22 | public class ScanLineView extends View { 23 | private static final String TAG = "ScanLineView"; 24 | private Context mContext; 25 | /** 26 | * 画笔对象的引用 27 | */ 28 | private Paint mPaint; 29 | 30 | private Rect mRect ; 31 | private static final long ANIMATION_DELAY =10L; 32 | 33 | private boolean isFirst = true; 34 | /** 35 | * 线条的最顶端位置 36 | */ 37 | private int slideTop; 38 | 39 | /** 40 | * 线条的最底端位置 41 | */ 42 | private int slideBottom; 43 | 44 | /** 45 | * 线条每次刷新移动的距离 46 | */ 47 | private static final int SPEEN_DISTANCE = 10; 48 | 49 | /** 50 | * 线的宽度 51 | */ 52 | private static int MIDDLE_LINE_WIDTH; 53 | 54 | /** 55 | * 线与扫描框左右的间隙 56 | */ 57 | private static int MIDDLE_LINE_PADDING; 58 | 59 | 60 | public ScanLineView(Context context) { 61 | super(context); 62 | init(context); 63 | } 64 | 65 | public ScanLineView(Context context, AttributeSet attrs) { 66 | super(context, attrs); 67 | init(context); 68 | } 69 | 70 | public ScanLineView(Context context, AttributeSet attrs, int defStyleAttr) { 71 | super(context, attrs, defStyleAttr); 72 | init(context); 73 | } 74 | 75 | private void init(Context context) { 76 | mContext =context; 77 | MIDDLE_LINE_PADDING = dip2px(context, 20.0F); 78 | MIDDLE_LINE_WIDTH = dip2px(context, 2.0F); 79 | Log.e(TAG, "init: "+getWidth()+":"+getHeight() ); 80 | mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // 开启反锯齿 81 | getMeasuredWidth(); 82 | } 83 | 84 | public void getRect(Rect rect){ 85 | if(rect==null){ 86 | Log.e(TAG, "getRect: rect is null" ); 87 | } 88 | Log.e(TAG, "getRect: "+mRect.left); 89 | mRect = rect; 90 | } 91 | 92 | @Override 93 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 94 | super.onMeasure(widthMeasureSpec, heightMeasureSpec); 95 | mRect =new Rect(0,0, getMeasuredWidth(), getMeasuredHeight()); 96 | 97 | } 98 | 99 | 100 | @Override 101 | protected void onDraw(Canvas canvas) { 102 | if (mRect == null) { 103 | return; // not ready yet, early draw before done configuring 104 | } 105 | // 绘制扫描线 106 | drawScanningLine(canvas, mRect); 107 | // 只刷新扫描框的内容,其他地方不刷新 108 | postInvalidateDelayed(ANIMATION_DELAY, mRect.left, mRect.top, 109 | mRect.right, mRect.bottom); 110 | } 111 | 112 | /** 113 | * 绘制扫描线 114 | * 115 | * @param canvas 画布 116 | * @param frame 扫描框 117 | */ 118 | private void drawScanningLine(Canvas canvas, Rect frame) { 119 | 120 | // 初始化中间线滑动的最上边和最下边 121 | if (isFirst) { 122 | isFirst = false; 123 | slideTop = frame.top; 124 | slideBottom = frame.bottom; 125 | } 126 | 127 | // 绘制中间的线,每次刷新界面,中间的线往下移动SPEEN_DISTANCE 128 | slideTop += SPEEN_DISTANCE; 129 | if (slideTop >= slideBottom) { 130 | slideTop = frame.top; 131 | } 132 | 133 | // 从图片资源画扫描线 134 | Rect lineRect = new Rect(); 135 | lineRect.left = frame.left + MIDDLE_LINE_PADDING; 136 | lineRect.right = frame.right - MIDDLE_LINE_PADDING; 137 | lineRect.top = slideTop; 138 | lineRect.bottom = (slideTop + MIDDLE_LINE_WIDTH); 139 | canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.scan_line), null, 140 | mRect, mPaint); 141 | 142 | Log.e(TAG, "drawScanningLine: "+"" ); 143 | 144 | } 145 | 146 | /** 147 | * dp转px 148 | * 149 | * @param context 上下文 150 | * @param dipValue dp值 151 | * @return px值 152 | */ 153 | public int dip2px(Context context, float dipValue) { 154 | final float scale = context.getResources().getDisplayMetrics().density; 155 | return (int) (dipValue * scale + 0.5f); 156 | } 157 | 158 | } 159 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/java/com/carinsur/zqf/zabardemo/ResultsActivity.java: -------------------------------------------------------------------------------- 1 | package com.carinsur.zqf.zabardemo; 2 | 3 | import android.app.ProgressDialog; 4 | import android.graphics.Bitmap; 5 | import android.os.Bundle; 6 | import android.support.v7.app.AppCompatActivity; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | import android.view.ViewParent; 10 | import android.webkit.WebChromeClient; 11 | import android.webkit.WebResourceError; 12 | import android.webkit.WebResourceRequest; 13 | import android.webkit.WebSettings; 14 | import android.webkit.WebView; 15 | import android.webkit.WebViewClient; 16 | import android.widget.ImageView; 17 | import android.widget.TextView; 18 | 19 | import com.znq.zbarcode.CaptureActivity; 20 | 21 | /** 22 | * desc: 23 | * Author :znq 24 | * Date:2018/5/18 25 | */ 26 | 27 | 28 | public class ResultsActivity extends AppCompatActivity { 29 | private static final String TAG = "ResultsActivity"; 30 | 31 | private TextView mTxtTitle; 32 | private WebView mWebView; 33 | private TextView mTxtContent; 34 | 35 | private String mResult; 36 | 37 | @Override 38 | protected void onCreate(Bundle savedInstanceState) { 39 | super.onCreate(savedInstanceState); 40 | setContentView(R.layout.activity_result); 41 | 42 | ImageView mImgBack = (ImageView) findViewById(R.id.img_back); 43 | mTxtTitle = (TextView) findViewById(R.id.scan_title); 44 | mWebView = (WebView) findViewById(R.id.web_view); 45 | mTxtContent = (TextView) findViewById(R.id.tv_result); 46 | 47 | if (getIntent() != null) { 48 | mResult = getIntent().getStringExtra(CaptureActivity.EXTRA_STRING); 49 | } 50 | 51 | mImgBack.setOnClickListener(new View.OnClickListener() { 52 | @Override 53 | public void onClick(View v) { 54 | finish(); 55 | } 56 | }); 57 | 58 | if (mResult.startsWith("http") || mResult.startsWith("https")) { 59 | mWebView.setVisibility(View.VISIBLE); 60 | mTxtContent.setVisibility(View.GONE); 61 | loadUrl(); 62 | } else { 63 | mWebView.setVisibility(View.GONE); 64 | mTxtContent.setVisibility(View.VISIBLE); 65 | mTxtTitle.setText("扫描结果"); 66 | mTxtContent.setText(mResult); 67 | } 68 | } 69 | 70 | private void loadUrl() { 71 | mWebView.loadUrl(mResult); 72 | WebSettings settings = mWebView.getSettings(); 73 | settings.setUseWideViewPort(true); 74 | settings.setLoadWithOverviewMode(true); 75 | settings.setJavaScriptEnabled(true); 76 | // 设置setWebChromeClient对象 77 | mWebView.setWebChromeClient(wvcc); 78 | mWebView.setWebViewClient(wvc); 79 | } 80 | 81 | 82 | WebChromeClient wvcc = new WebChromeClient() { 83 | @Override 84 | public void onReceivedTitle(WebView view, String title) { 85 | super.onReceivedTitle(view, title); 86 | mTxtTitle.setText(title); 87 | } 88 | 89 | }; 90 | 91 | ProgressDialog _dialog; 92 | // 创建WebViewClient对象 93 | WebViewClient wvc = new WebViewClient() { 94 | @Override 95 | public boolean shouldOverrideUrlLoading(WebView view, String url) { 96 | // 使用自己的WebView组件来响应Url加载事件,而不是使用默认浏览器器加载页面 97 | mWebView.loadUrl(url); 98 | // 消耗掉这个事件。Android中返回True的即到此为止吧 99 | // 事件就会不会冒泡传递了,我们称之为消耗掉 100 | return true; 101 | } 102 | 103 | @Override 104 | public void onPageStarted(WebView view, String url, Bitmap favicon) { 105 | super.onPageStarted(view, url, favicon); 106 | _dialog = new ProgressDialog(ResultsActivity.this); 107 | _dialog.setMessage(getString(com.znq.zbarcode.R.string.loading)); 108 | _dialog.show(); 109 | } 110 | 111 | @Override 112 | public void onPageFinished(WebView view, String url) { 113 | super.onPageFinished(view, url); 114 | if (null == _dialog){ 115 | return; 116 | } 117 | _dialog.dismiss(); 118 | } 119 | 120 | @Override 121 | public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { 122 | super.onReceivedError(view, request, error); 123 | if (_dialog != null) { 124 | _dialog.dismiss(); 125 | _dialog=null; 126 | } 127 | mTxtTitle.setVisibility(View.GONE); 128 | mTxtContent.setVisibility(View.VISIBLE); 129 | mTxtContent.setText("链接有问题"); 130 | } 131 | }; 132 | 133 | @Override 134 | protected void onDestroy() { 135 | super.onDestroy(); 136 | if (mWebView != null) { 137 | ViewParent parent = mWebView.getParent(); 138 | if (parent != null) { 139 | ((ViewGroup) parent).removeView(mWebView); 140 | } 141 | mWebView.getSettings().setJavaScriptEnabled(false); 142 | mWebView.stopLoading(); 143 | mWebView.setTag(null); 144 | mWebView.clearHistory(); 145 | mWebView.removeAllViews(); 146 | mWebView.destroy(); 147 | mWebView = null; 148 | } 149 | } 150 | } -------------------------------------------------------------------------------- /ZabarDemo/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /ZabarDemo/app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 11 | 16 | 21 | 26 | 31 | 36 | 41 | 46 | 51 | 56 | 61 | 66 | 71 | 76 | 81 | 86 | 91 | 96 | 101 | 106 | 111 | 116 | 121 | 126 | 131 | 136 | 141 | 146 | 151 | 156 | 161 | 166 | 171 | 172 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/camera/CameraManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 ZXing authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.znq.zbarcode.camera; 17 | 18 | import android.content.Context; 19 | import android.graphics.Point; 20 | import android.hardware.Camera; 21 | import android.os.Handler; 22 | import android.util.Log; 23 | import android.view.SurfaceHolder; 24 | 25 | import java.io.IOException; 26 | 27 | /** 28 | * Desc: 主要对相机的操作 29 | * Update by znq on 2016/10/28. 30 | */ 31 | public final class CameraManager { 32 | 33 | private static final String TAG = CameraManager.class.getSimpleName(); 34 | 35 | private final CameraConfigurationManager configManager; 36 | 37 | private AutoFocusManager autoFocusManager; 38 | 39 | private boolean previewing; 40 | private Camera camera; 41 | private boolean initialized; 42 | 43 | private final Context context; 44 | 45 | private final PreviewCallback previewCallback; 46 | 47 | public CameraManager(Context context) { 48 | this.context = context; 49 | this.configManager = new CameraConfigurationManager(context); 50 | previewCallback = new PreviewCallback(); 51 | } 52 | 53 | /** 54 | * Opens the camera driver and initializes the hardware parameters. 55 | * 56 | * 57 | * The surface object which the camera will draw preview frames 58 | * into. 59 | * 60 | * @throws IOException Indicates the camera driver failed to open. 61 | */ 62 | public synchronized void openDriver(SurfaceHolder holder) throws IOException { 63 | Camera theCamera = camera; 64 | if (theCamera == null) { 65 | theCamera = Camera.open(); 66 | if (theCamera == null) { 67 | throw new IOException(); 68 | } 69 | camera = theCamera; 70 | } 71 | // 设置摄像头预览view 72 | theCamera.setPreviewDisplay(holder); 73 | 74 | if (!initialized) { 75 | initialized = true; 76 | configManager.initFromCameraParameters(theCamera); 77 | } 78 | 79 | Camera.Parameters parameters = theCamera.getParameters(); 80 | String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save 81 | // temporarily 82 | try { 83 | configManager.setDesiredCameraParameters(theCamera, false); 84 | } catch (RuntimeException re) { 85 | // Driver failed 86 | Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters"); 87 | Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened); 88 | // Reset: 89 | if (parametersFlattened != null) { 90 | parameters = theCamera.getParameters(); 91 | parameters.unflatten(parametersFlattened); 92 | try { 93 | theCamera.setParameters(parameters); 94 | configManager.setDesiredCameraParameters(theCamera, true); 95 | } catch (RuntimeException re2) { 96 | // Well, darn. Give up 97 | Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration"); 98 | } 99 | } 100 | } 101 | 102 | } 103 | 104 | /** 105 | * Closes the camera driver if still in use. 106 | */ 107 | public synchronized void closeDriver() { 108 | if (camera != null) { 109 | camera.release(); 110 | camera = null; 111 | } 112 | } 113 | 114 | public synchronized boolean isOpen() { 115 | return camera != null; 116 | } 117 | 118 | public Camera getCamera() { 119 | return camera; 120 | } 121 | 122 | /** 123 | * Asks the camera hardware to begin drawing preview frames to the screen. 124 | */ 125 | public synchronized void startPreview() { 126 | Camera theCamera = camera; 127 | if (theCamera != null && !previewing) { 128 | // Starts capturing and drawing preview frames to the screen 129 | // Preview will not actually start until a surface is supplied with 130 | // setPreviewDisplay(SurfaceHolder) or 131 | // setPreviewTexture(SurfaceTexture). 132 | theCamera.startPreview(); 133 | 134 | previewing = true; 135 | autoFocusManager = new AutoFocusManager(context, camera); 136 | } 137 | } 138 | 139 | /** 140 | * Tells the camera to stop drawing preview frames. 141 | */ 142 | public synchronized void stopPreview() { 143 | if (autoFocusManager != null) { 144 | autoFocusManager.stop(); 145 | autoFocusManager = null; 146 | } 147 | if (camera != null && previewing) { 148 | camera.setPreviewCallback(null); 149 | camera.stopPreview(); 150 | previewCallback.setHandler(null, 0); 151 | previewing = false; 152 | } 153 | } 154 | 155 | /* 两个绑定操作: 156 | * 1:将handler与回调函数绑定; 157 | * 2:将相机与回调函数绑定 158 | * 综上,该函数的作用是当相机的预览界面准备就绪后就会调用hander向其发送传入的message 159 | * @param handler 解码的子线程. 160 | * @param message R.id.decode. 161 | */ 162 | public synchronized void requestPreviewFrame(Handler handler, int message) { 163 | Camera theCamera = camera; 164 | if (theCamera != null && previewing) { 165 | previewCallback.setHandler(handler, message); 166 | // 绑定相机回调函数,当预览界面准备就绪后会回调Camera.PreviewCallback.onPreviewFrame 167 | theCamera.setOneShotPreviewCallback(previewCallback); 168 | } 169 | } 170 | 171 | /** 172 | * 获取相机分辨率 173 | * 174 | * @return 175 | */ 176 | public Point getCameraResolution() { 177 | return configManager.getCameraResolution(); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/camera/CameraConfigurationManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 ZXing authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.znq.zbarcode.camera; 17 | 18 | import android.annotation.SuppressLint; 19 | import android.content.Context; 20 | import android.content.SharedPreferences; 21 | import android.graphics.Point; 22 | import android.hardware.Camera; 23 | import android.preference.PreferenceManager; 24 | import android.util.Log; 25 | import android.view.Display; 26 | import android.view.WindowManager; 27 | 28 | import com.znq.zbarcode.utils.Config; 29 | 30 | import java.util.ArrayList; 31 | import java.util.Collection; 32 | import java.util.Collections; 33 | import java.util.Comparator; 34 | import java.util.Iterator; 35 | import java.util.List; 36 | 37 | /** 38 | * 邮箱: 1076559197@qq.com | tauchen1990@gmail.com 39 | * 40 | * 作者: 陈涛 41 | * 42 | * 日期: 2014年8月20日 43 | * 44 | * 描述: 该类主要负责设置相机的参数信息,获取最佳的预览界面 45 | */ 46 | public final class CameraConfigurationManager { 47 | 48 | private static final String TAG = "CameraConfiguration"; 49 | 50 | private static final int MIN_PREVIEW_PIXELS = 480 * 320; 51 | private static final double MAX_ASPECT_DISTORTION = 0.15; 52 | 53 | private final Context context; 54 | 55 | // 屏幕分辨率 56 | private Point screenResolution; 57 | // 相机分辨率 58 | private Point cameraResolution; 59 | 60 | public CameraConfigurationManager(Context context) { 61 | this.context = context; 62 | } 63 | 64 | public void initFromCameraParameters(Camera camera) { 65 | Camera.Parameters parameters = camera.getParameters(); 66 | WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 67 | Display display = manager.getDefaultDisplay(); 68 | Point theScreenResolution = new Point(); 69 | theScreenResolution = getDisplaySize(display); 70 | 71 | screenResolution = theScreenResolution; 72 | Log.i(TAG, "Screen resolution: " + screenResolution); 73 | 74 | /** 因为换成了竖屏显示,所以不替换屏幕宽高得出的预览图是变形的 */ 75 | Point screenResolutionForCamera = new Point(); 76 | screenResolutionForCamera.x = screenResolution.x; 77 | screenResolutionForCamera.y = screenResolution.y; 78 | 79 | if (screenResolution.x < screenResolution.y) { 80 | screenResolutionForCamera.x = screenResolution.y; 81 | screenResolutionForCamera.y = screenResolution.x; 82 | } 83 | 84 | cameraResolution = findBestPreviewSizeValue(parameters, screenResolutionForCamera); 85 | Log.i(TAG, "Camera resolution x: " + cameraResolution.x); 86 | Log.i(TAG, "Camera resolution y: " + cameraResolution.y); 87 | } 88 | 89 | @SuppressWarnings("deprecation") 90 | @SuppressLint("NewApi") 91 | private Point getDisplaySize(final Display display) { 92 | final Point point = new Point(); 93 | try { 94 | display.getSize(point); 95 | } catch (NoSuchMethodError ignore) { 96 | point.x = display.getWidth(); 97 | point.y = display.getHeight(); 98 | } 99 | return point; 100 | } 101 | 102 | public void setDesiredCameraParameters(Camera camera, boolean safeMode) { 103 | Camera.Parameters parameters = camera.getParameters(); 104 | 105 | if (parameters == null) { 106 | Log.w(TAG, "Device error: no camera parameters are available. Proceeding without configuration."); 107 | return; 108 | } 109 | 110 | Log.i(TAG, "Initial camera parameters: " + parameters.flatten()); 111 | 112 | if (safeMode) { 113 | Log.w(TAG, "In camera config safe mode -- most settings will not be honored"); 114 | } 115 | 116 | 117 | SharedPreferences prefs = PreferenceManager 118 | .getDefaultSharedPreferences(context); 119 | 120 | // 默认使用自动对焦 121 | String focusMode = findSettableValue( 122 | parameters.getSupportedFocusModes(), 123 | Camera.Parameters.FOCUS_MODE_AUTO); 124 | 125 | // Maybe selected auto-focus but not available, so fall through here: 126 | if (!safeMode && focusMode == null) { 127 | focusMode = findSettableValue(parameters.getSupportedFocusModes(), 128 | Camera.Parameters.FOCUS_MODE_MACRO, 129 | Camera.Parameters.FOCUS_MODE_EDOF); 130 | } 131 | if (focusMode != null) { 132 | parameters.setFocusMode(focusMode); 133 | } 134 | 135 | if (prefs.getBoolean(Config.KEY_INVERT_SCAN, false)) { 136 | String colorMode = findSettableValue( 137 | parameters.getSupportedColorEffects(), 138 | Camera.Parameters.EFFECT_NEGATIVE); 139 | if (colorMode != null) { 140 | parameters.setColorEffect(colorMode); 141 | } 142 | } 143 | 144 | parameters.setPreviewSize(cameraResolution.x, cameraResolution.y); 145 | camera.setParameters(parameters); 146 | 147 | Camera.Parameters afterParameters = camera.getParameters(); 148 | Camera.Size afterSize = afterParameters.getPreviewSize(); 149 | if (afterSize != null && (cameraResolution.x != afterSize.width || cameraResolution.y != afterSize.height)) { 150 | Log.w(TAG, "Camera said it supported preview size " + cameraResolution.x + 'x' + cameraResolution.y + ", but after setting it, preview size is " + afterSize.width + 'x' + afterSize.height); 151 | cameraResolution.x = afterSize.width; 152 | cameraResolution.y = afterSize.height; 153 | } 154 | 155 | /** 设置相机预览为竖屏 */ 156 | camera.setDisplayOrientation(90); 157 | } 158 | 159 | public Point getCameraResolution() { 160 | return cameraResolution; 161 | } 162 | 163 | public Point getScreenResolution() { 164 | return screenResolution; 165 | } 166 | 167 | /** 168 | * 从相机支持的分辨率中计算出最适合的预览界面尺寸 169 | * 170 | * @param parameters 171 | * @param screenResolution 172 | * @return 173 | */ 174 | private Point findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution) { 175 | List rawSupportedSizes = parameters.getSupportedPreviewSizes(); 176 | if (rawSupportedSizes == null) { 177 | Log.w(TAG, "Device returned no supported preview sizes; using default"); 178 | Camera.Size defaultSize = parameters.getPreviewSize(); 179 | return new Point(defaultSize.width, defaultSize.height); 180 | } 181 | 182 | // Sort by size, descending 183 | List supportedPreviewSizes = new ArrayList(rawSupportedSizes); 184 | Collections.sort(supportedPreviewSizes, new Comparator() { 185 | @Override 186 | public int compare(Camera.Size a, Camera.Size b) { 187 | int aPixels = a.height * a.width; 188 | int bPixels = b.height * b.width; 189 | if (bPixels < aPixels) { 190 | return -1; 191 | } 192 | if (bPixels > aPixels) { 193 | return 1; 194 | } 195 | return 0; 196 | } 197 | }); 198 | 199 | if (Log.isLoggable(TAG, Log.INFO)) { 200 | StringBuilder previewSizesString = new StringBuilder(); 201 | for (Camera.Size supportedPreviewSize : supportedPreviewSizes) { 202 | previewSizesString.append(supportedPreviewSize.width).append('x').append(supportedPreviewSize.height).append(' '); 203 | } 204 | Log.i(TAG, "Supported preview sizes: " + previewSizesString); 205 | } 206 | 207 | double screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y; 208 | 209 | // Remove sizes that are unsuitable 210 | Iterator it = supportedPreviewSizes.iterator(); 211 | while (it.hasNext()) { 212 | Camera.Size supportedPreviewSize = it.next(); 213 | int realWidth = supportedPreviewSize.width; 214 | int realHeight = supportedPreviewSize.height; 215 | if (realWidth * realHeight < MIN_PREVIEW_PIXELS) { 216 | it.remove(); 217 | continue; 218 | } 219 | 220 | boolean isCandidatePortrait = realWidth < realHeight; 221 | int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth; 222 | int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight; 223 | 224 | double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight; 225 | double distortion = Math.abs(aspectRatio - screenAspectRatio); 226 | if (distortion > MAX_ASPECT_DISTORTION) { 227 | it.remove(); 228 | continue; 229 | } 230 | 231 | if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) { 232 | Point exactPoint = new Point(realWidth, realHeight); 233 | Log.i(TAG, "Found preview size exactly matching screen size: " + exactPoint); 234 | return exactPoint; 235 | } 236 | } 237 | 238 | // If no exact match, use largest preview size. This was not a great 239 | // idea on older devices because 240 | // of the additional computation needed. We're likely to get here on 241 | // newer Android 4+ devices, where 242 | // the CPU is much more powerful. 243 | if (!supportedPreviewSizes.isEmpty()) { 244 | Camera.Size largestPreview = supportedPreviewSizes.get(0); 245 | Point largestSize = new Point(largestPreview.width, largestPreview.height); 246 | Log.i(TAG, "Using largest suitable preview size: " + largestSize); 247 | return largestSize; 248 | } 249 | 250 | // If there is nothing at all suitable, return current preview size 251 | Camera.Size defaultPreview = parameters.getPreviewSize(); 252 | Point defaultSize = new Point(defaultPreview.width, defaultPreview.height); 253 | Log.i(TAG, "No suitable preview sizes, using default: " + defaultSize); 254 | 255 | return defaultSize; 256 | } 257 | 258 | /** 259 | * 在supportedValues中寻找desiredValues,找不到则返回null 260 | * 261 | * @param supportedValues 262 | * @param desiredValues 263 | * @return 264 | */ 265 | private static String findSettableValue(Collection supportedValues, 266 | String... desiredValues) { 267 | Log.i(TAG, "Supported values: " + supportedValues); 268 | String result = null; 269 | if (supportedValues != null) { 270 | for (String desiredValue : desiredValues) { 271 | if (supportedValues.contains(desiredValue)) { 272 | result = desiredValue; 273 | break; 274 | } 275 | } 276 | } 277 | Log.i(TAG, "Settable value: " + result); 278 | return result; 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/CaptureActivity.java: -------------------------------------------------------------------------------- 1 | package com.znq.zbarcode; 2 | 3 | import android.Manifest; 4 | import android.app.Activity; 5 | import android.app.AlertDialog; 6 | import android.app.AppOpsManager; 7 | import android.content.Context; 8 | import android.content.DialogInterface; 9 | import android.content.Intent; 10 | import android.content.pm.ActivityInfo; 11 | import android.content.pm.PackageManager; 12 | import android.graphics.Rect; 13 | import android.os.Binder; 14 | import android.os.Build; 15 | import android.os.Bundle; 16 | import android.os.Handler; 17 | import android.support.v4.app.ActivityCompat; 18 | import android.support.v4.content.PermissionChecker; 19 | import android.util.Log; 20 | import android.view.SurfaceHolder; 21 | import android.view.SurfaceView; 22 | import android.view.View; 23 | import android.view.animation.Animation; 24 | import android.view.animation.TranslateAnimation; 25 | import android.widget.ImageView; 26 | import android.widget.RelativeLayout; 27 | import android.widget.TextView; 28 | 29 | import com.znq.zbarcode.camera.CameraManager; 30 | import com.znq.zbarcode.decode.MainHandler; 31 | import com.znq.zbarcode.utils.BeepManager; 32 | 33 | import java.io.IOException; 34 | import java.lang.reflect.Field; 35 | import java.lang.reflect.Method; 36 | 37 | /** 38 | * Desc: 1:启动一个SurfaceView作为取景预览 39 | * 2:开启camera,在后台独立线程中完成扫描任务 40 | * 3:对解码返回的结果进行处理. 41 | * 4:释放资源 42 | * Update by znq on 2016/11/9. 43 | */ 44 | public class CaptureActivity extends Activity implements SurfaceHolder.Callback { 45 | private static final int MY_PERMISSIONS_REQUEST_CAMERA = 26; 46 | public static final String EXTRA_STRING = "extra_string"; 47 | public static final int TYPE_BOOK_COVER = 0x101; 48 | public static final int TYPE_BOOK_CHAPTER = 0x102; 49 | private static final String TAG = "CaptureActivity"; 50 | private MainHandler mainHandler; 51 | private SurfaceHolder mHolder; 52 | 53 | private CameraManager mCameraManager; 54 | private BeepManager beepManager; 55 | 56 | private SurfaceView scanPreview; 57 | private RelativeLayout scanContainer; 58 | private RelativeLayout scanCropView; 59 | private ImageView scanLine; 60 | private Rect mCropRect = null; 61 | 62 | private boolean isHasSurface = false; 63 | private boolean isOpenCamera = false; 64 | 65 | public Handler getHandler() { 66 | return mainHandler; 67 | } 68 | 69 | 70 | public void onCreate(Bundle savedInstanceState) { 71 | super.onCreate(savedInstanceState); 72 | setContentView(R.layout.activity_capture); 73 | setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 74 | initView(); 75 | checkPermissionCamera(); 76 | } 77 | 78 | private void initView() { 79 | scanPreview = (SurfaceView) findViewById(R.id.capture_preview); 80 | scanContainer = (RelativeLayout) findViewById(R.id.capture_container); 81 | scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view); 82 | scanLine = (ImageView) findViewById(R.id.capture_scan_line); 83 | TextView _textTitle = (TextView) findViewById(R.id.scan_title); 84 | _textTitle.setText(getString(R.string.qr_name)); 85 | findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() { 86 | @Override 87 | public void onClick(View v) { 88 | finish(); 89 | } 90 | }); 91 | isHasSurface = false; 92 | beepManager = new BeepManager(this); 93 | 94 | TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation 95 | .RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 96 | 0.9f); 97 | animation.setDuration(3000); 98 | animation.setRepeatCount(-1); 99 | animation.setRepeatMode(Animation.RESTART); 100 | scanLine.startAnimation(animation); 101 | 102 | } 103 | 104 | @Override 105 | protected void onResume() { 106 | super.onResume(); 107 | if (isOpenCamera) { 108 | mHolder = scanPreview.getHolder(); 109 | mCameraManager = new CameraManager(getApplication()); 110 | if (isHasSurface) { 111 | initCamera(mHolder); 112 | } else { 113 | mHolder.addCallback(this); 114 | mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 115 | } 116 | } 117 | } 118 | 119 | @Override 120 | public void onPause() { 121 | releaseCamera(); 122 | super.onPause(); 123 | if (scanLine != null) { 124 | scanLine.clearAnimation(); 125 | scanLine.setVisibility(View.GONE); 126 | } 127 | } 128 | 129 | @Override 130 | protected void onDestroy() { 131 | super.onDestroy(); 132 | //remove SurfaceCallback 133 | if (!isHasSurface) { 134 | scanPreview.getHolder().removeCallback(this); 135 | } 136 | } 137 | 138 | //region 初始化和回收相关资源 139 | private void initCamera(SurfaceHolder surfaceHolder) { 140 | mainHandler = null; 141 | try { 142 | mCameraManager.openDriver(surfaceHolder); 143 | if (mainHandler == null) { 144 | mainHandler = new MainHandler(this, mCameraManager); 145 | } 146 | } catch (IOException ioe) { 147 | Log.e(TAG, "相机被占用", ioe); 148 | } catch (RuntimeException e) { 149 | e.printStackTrace(); 150 | Log.e(TAG, "Unexpected error initializing camera"); 151 | displayFrameworkBugMessageAndExit(); 152 | } 153 | 154 | } 155 | 156 | private void releaseCamera() { 157 | if (null != mainHandler) { 158 | //关闭聚焦,停止预览,清空预览回调,quit子线程looper 159 | mainHandler.quitSynchronously(); 160 | mainHandler = null; 161 | } 162 | //关闭声音 163 | if (null != beepManager) { 164 | Log.e(TAG, "releaseCamera: beepManager release" ); 165 | beepManager.releaseRing(); 166 | beepManager = null; 167 | } 168 | //关闭相机 169 | if (mCameraManager != null) { 170 | mCameraManager.closeDriver(); 171 | mCameraManager = null; 172 | } 173 | } 174 | //endregion 175 | 176 | //region 检查权限 177 | private void checkPermissionCamera() { 178 | int checkPermission = 0; 179 | if (Build.VERSION.SDK_INT >= 23) { 180 | // checkPermission =ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA); 181 | checkPermission = PermissionChecker.checkSelfPermission(this, Manifest.permission.CAMERA); 182 | if (checkPermission != PackageManager.PERMISSION_GRANTED) { 183 | ActivityCompat.requestPermissions(this, 184 | new String[]{Manifest.permission.CAMERA}, 185 | MY_PERMISSIONS_REQUEST_CAMERA); 186 | } else { 187 | isOpenCamera = true; 188 | } 189 | 190 | } else { 191 | checkPermission = checkPermission(26); 192 | if (checkPermission == AppOpsManager.MODE_ALLOWED) { 193 | isOpenCamera = true; 194 | } else if (checkPermission == AppOpsManager.MODE_IGNORED) { 195 | isOpenCamera = false; 196 | displayFrameworkBugMessageAndExit(); 197 | } 198 | } 199 | } 200 | 201 | /** 202 | * 反射调用系统权限,判断权限是否打开 203 | * 204 | * @param permissionCode 相应的权限所对应的code 205 | * @see {@link AppOpsManager } 206 | */ 207 | private int checkPermission(int permissionCode) { 208 | int checkPermission = 0; 209 | if (Build.VERSION.SDK_INT >= 19) { 210 | AppOpsManager _manager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); 211 | try { 212 | Class>[] types = new Class[]{int.class, int.class, String.class}; 213 | Object[] args = new Object[]{permissionCode, Binder.getCallingUid(), getPackageName()}; 214 | Method method = _manager.getClass().getDeclaredMethod("noteOp", types); 215 | method.setAccessible(true); 216 | Object _o = method.invoke(_manager, args); 217 | if ((_o instanceof Integer)) { 218 | checkPermission = (Integer) _o; 219 | } 220 | } catch (Exception e) { 221 | e.printStackTrace(); 222 | } 223 | } else { 224 | checkPermission = 0; 225 | } 226 | return checkPermission; 227 | } 228 | 229 | @Override 230 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 231 | switch (requestCode) { 232 | case MY_PERMISSIONS_REQUEST_CAMERA: { 233 | if (grantResults.length > 0 234 | && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 235 | finish(); 236 | 237 | } else { 238 | finish(); 239 | } 240 | return; 241 | } 242 | } 243 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 244 | } 245 | 246 | private void displayFrameworkBugMessageAndExit() { 247 | String per = String.format(getString(R.string.permission), getString(R.string.camera), getString(R.string.camera)); 248 | String per1 = getString(R.string.low_permission, getString(R.string.camera)); 249 | AlertDialog.Builder builder = new AlertDialog.Builder(this); 250 | builder.setTitle(getString(R.string.qr_name)); 251 | builder.setMessage(per + per1); 252 | builder.setPositiveButton(getString(R.string.i_know), new DialogInterface.OnClickListener() { 253 | 254 | @Override 255 | public void onClick(DialogInterface dialog, int which) { 256 | CaptureActivity.this.finish(); 257 | } 258 | 259 | }); 260 | builder.setOnCancelListener(new DialogInterface.OnCancelListener() { 261 | 262 | @Override 263 | public void onCancel(DialogInterface dialog) { 264 | CaptureActivity.this.finish(); 265 | } 266 | }); 267 | builder.show(); 268 | } 269 | //endregion 270 | 271 | //region 扫描结果 272 | public void checkResult(final String result) { 273 | if (beepManager != null) { 274 | beepManager.startRing(); 275 | } 276 | mainHandler.postDelayed(new Runnable() { 277 | @Override 278 | public void run() { 279 | activityResult(result.trim()); 280 | } 281 | }, beepManager.getTimeDuration()); 282 | } 283 | 284 | private void activityResult(String result) { 285 | if (!isFinishing()) { 286 | Intent intent =new Intent(); 287 | Bundle bundle = new Bundle(); 288 | bundle.putInt("width", mCropRect.width()); 289 | bundle.putInt("height", mCropRect.height()); 290 | bundle.putString(EXTRA_STRING, result); 291 | intent.putExtras(bundle); 292 | setResult(RESULT_OK,intent); 293 | CaptureActivity.this.finish(); 294 | } 295 | } 296 | 297 | //endregion 298 | 299 | //region 初始化截取的矩形区域 300 | public Rect initCrop() { 301 | int cameraWidth = 0; 302 | int cameraHeight = 0; 303 | if (null != mCameraManager) { 304 | cameraWidth = mCameraManager.getCameraResolution().y; 305 | cameraHeight = mCameraManager.getCameraResolution().x; 306 | } 307 | 308 | /** 获取布局中扫描框的位置信息 */ 309 | int[] location = new int[2]; 310 | scanCropView.getLocationInWindow(location); 311 | 312 | int cropLeft = location[0]; 313 | int cropTop = location[1] - getStatusBarHeight(); 314 | 315 | int cropWidth = scanCropView.getWidth(); 316 | int cropHeight = scanCropView.getHeight(); 317 | 318 | /** 获取布局容器的宽高 */ 319 | int containerWidth = scanContainer.getWidth(); 320 | int containerHeight = scanContainer.getHeight(); 321 | 322 | /** 计算最终截取的矩形的左上角顶点x坐标 */ 323 | int x = cropLeft * cameraWidth / containerWidth; 324 | /** 计算最终截取的矩形的左上角顶点y坐标 */ 325 | int y = cropTop * cameraHeight / containerHeight; 326 | 327 | /** 计算最终截取的矩形的宽度 */ 328 | int width = cropWidth * cameraWidth / containerWidth; 329 | /** 计算最终截取的矩形的高度 */ 330 | int height = cropHeight * cameraHeight / containerHeight; 331 | 332 | /** 生成最终的截取的矩形 */ 333 | mCropRect = new Rect(x, y, width + x, height + y); 334 | return new Rect(x, y, width + x, height + y); 335 | } 336 | 337 | private int getStatusBarHeight() { 338 | try { 339 | Class> c = Class.forName("com.android.internal.R$dimen"); 340 | Object obj = c.newInstance(); 341 | Field field = c.getField("status_bar_height"); 342 | int x = Integer.parseInt(field.get(obj).toString()); 343 | return getResources().getDimensionPixelSize(x); 344 | } catch (Exception e) { 345 | e.printStackTrace(); 346 | } 347 | return 0; 348 | } 349 | //endregion 350 | 351 | //region SurfaceHolder Callback 回调方法 352 | @Override 353 | public void surfaceCreated(SurfaceHolder holder) { 354 | if (holder == null) { 355 | Log.e(TAG, "*** 没有添加SurfaceHolder的Callback"); 356 | } 357 | if (isOpenCamera) { 358 | if (!isHasSurface) { 359 | isHasSurface = true; 360 | initCamera(holder); 361 | } 362 | } 363 | 364 | } 365 | 366 | @Override 367 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 368 | Log.e(TAG, "surfaceChanged: "); 369 | 370 | } 371 | 372 | @Override 373 | public void surfaceDestroyed(SurfaceHolder holder) { 374 | isHasSurface = false; 375 | 376 | } 377 | //endregion 378 | } 379 | --------------------------------------------------------------------------------
56 | *
57 | * The surface object which the camera will draw preview frames 58 | * into. 59 | * 60 | * @throws IOException Indicates the camera driver failed to open. 61 | */ 62 | public synchronized void openDriver(SurfaceHolder holder) throws IOException { 63 | Camera theCamera = camera; 64 | if (theCamera == null) { 65 | theCamera = Camera.open(); 66 | if (theCamera == null) { 67 | throw new IOException(); 68 | } 69 | camera = theCamera; 70 | } 71 | // 设置摄像头预览view 72 | theCamera.setPreviewDisplay(holder); 73 | 74 | if (!initialized) { 75 | initialized = true; 76 | configManager.initFromCameraParameters(theCamera); 77 | } 78 | 79 | Camera.Parameters parameters = theCamera.getParameters(); 80 | String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save 81 | // temporarily 82 | try { 83 | configManager.setDesiredCameraParameters(theCamera, false); 84 | } catch (RuntimeException re) { 85 | // Driver failed 86 | Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters"); 87 | Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened); 88 | // Reset: 89 | if (parametersFlattened != null) { 90 | parameters = theCamera.getParameters(); 91 | parameters.unflatten(parametersFlattened); 92 | try { 93 | theCamera.setParameters(parameters); 94 | configManager.setDesiredCameraParameters(theCamera, true); 95 | } catch (RuntimeException re2) { 96 | // Well, darn. Give up 97 | Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration"); 98 | } 99 | } 100 | } 101 | 102 | } 103 | 104 | /** 105 | * Closes the camera driver if still in use. 106 | */ 107 | public synchronized void closeDriver() { 108 | if (camera != null) { 109 | camera.release(); 110 | camera = null; 111 | } 112 | } 113 | 114 | public synchronized boolean isOpen() { 115 | return camera != null; 116 | } 117 | 118 | public Camera getCamera() { 119 | return camera; 120 | } 121 | 122 | /** 123 | * Asks the camera hardware to begin drawing preview frames to the screen. 124 | */ 125 | public synchronized void startPreview() { 126 | Camera theCamera = camera; 127 | if (theCamera != null && !previewing) { 128 | // Starts capturing and drawing preview frames to the screen 129 | // Preview will not actually start until a surface is supplied with 130 | // setPreviewDisplay(SurfaceHolder) or 131 | // setPreviewTexture(SurfaceTexture). 132 | theCamera.startPreview(); 133 | 134 | previewing = true; 135 | autoFocusManager = new AutoFocusManager(context, camera); 136 | } 137 | } 138 | 139 | /** 140 | * Tells the camera to stop drawing preview frames. 141 | */ 142 | public synchronized void stopPreview() { 143 | if (autoFocusManager != null) { 144 | autoFocusManager.stop(); 145 | autoFocusManager = null; 146 | } 147 | if (camera != null && previewing) { 148 | camera.setPreviewCallback(null); 149 | camera.stopPreview(); 150 | previewCallback.setHandler(null, 0); 151 | previewing = false; 152 | } 153 | } 154 | 155 | /* 两个绑定操作: 156 | * 1:将handler与回调函数绑定; 157 | * 2:将相机与回调函数绑定 158 | * 综上,该函数的作用是当相机的预览界面准备就绪后就会调用hander向其发送传入的message 159 | * @param handler 解码的子线程. 160 | * @param message R.id.decode. 161 | */ 162 | public synchronized void requestPreviewFrame(Handler handler, int message) { 163 | Camera theCamera = camera; 164 | if (theCamera != null && previewing) { 165 | previewCallback.setHandler(handler, message); 166 | // 绑定相机回调函数,当预览界面准备就绪后会回调Camera.PreviewCallback.onPreviewFrame 167 | theCamera.setOneShotPreviewCallback(previewCallback); 168 | } 169 | } 170 | 171 | /** 172 | * 获取相机分辨率 173 | * 174 | * @return 175 | */ 176 | public Point getCameraResolution() { 177 | return configManager.getCameraResolution(); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/camera/CameraConfigurationManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 ZXing authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.znq.zbarcode.camera; 17 | 18 | import android.annotation.SuppressLint; 19 | import android.content.Context; 20 | import android.content.SharedPreferences; 21 | import android.graphics.Point; 22 | import android.hardware.Camera; 23 | import android.preference.PreferenceManager; 24 | import android.util.Log; 25 | import android.view.Display; 26 | import android.view.WindowManager; 27 | 28 | import com.znq.zbarcode.utils.Config; 29 | 30 | import java.util.ArrayList; 31 | import java.util.Collection; 32 | import java.util.Collections; 33 | import java.util.Comparator; 34 | import java.util.Iterator; 35 | import java.util.List; 36 | 37 | /** 38 | * 邮箱: 1076559197@qq.com | tauchen1990@gmail.com 39 | *
40 | * 作者: 陈涛 41 | *
42 | * 日期: 2014年8月20日 43 | *
44 | * 描述: 该类主要负责设置相机的参数信息,获取最佳的预览界面 45 | */ 46 | public final class CameraConfigurationManager { 47 | 48 | private static final String TAG = "CameraConfiguration"; 49 | 50 | private static final int MIN_PREVIEW_PIXELS = 480 * 320; 51 | private static final double MAX_ASPECT_DISTORTION = 0.15; 52 | 53 | private final Context context; 54 | 55 | // 屏幕分辨率 56 | private Point screenResolution; 57 | // 相机分辨率 58 | private Point cameraResolution; 59 | 60 | public CameraConfigurationManager(Context context) { 61 | this.context = context; 62 | } 63 | 64 | public void initFromCameraParameters(Camera camera) { 65 | Camera.Parameters parameters = camera.getParameters(); 66 | WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 67 | Display display = manager.getDefaultDisplay(); 68 | Point theScreenResolution = new Point(); 69 | theScreenResolution = getDisplaySize(display); 70 | 71 | screenResolution = theScreenResolution; 72 | Log.i(TAG, "Screen resolution: " + screenResolution); 73 | 74 | /** 因为换成了竖屏显示,所以不替换屏幕宽高得出的预览图是变形的 */ 75 | Point screenResolutionForCamera = new Point(); 76 | screenResolutionForCamera.x = screenResolution.x; 77 | screenResolutionForCamera.y = screenResolution.y; 78 | 79 | if (screenResolution.x < screenResolution.y) { 80 | screenResolutionForCamera.x = screenResolution.y; 81 | screenResolutionForCamera.y = screenResolution.x; 82 | } 83 | 84 | cameraResolution = findBestPreviewSizeValue(parameters, screenResolutionForCamera); 85 | Log.i(TAG, "Camera resolution x: " + cameraResolution.x); 86 | Log.i(TAG, "Camera resolution y: " + cameraResolution.y); 87 | } 88 | 89 | @SuppressWarnings("deprecation") 90 | @SuppressLint("NewApi") 91 | private Point getDisplaySize(final Display display) { 92 | final Point point = new Point(); 93 | try { 94 | display.getSize(point); 95 | } catch (NoSuchMethodError ignore) { 96 | point.x = display.getWidth(); 97 | point.y = display.getHeight(); 98 | } 99 | return point; 100 | } 101 | 102 | public void setDesiredCameraParameters(Camera camera, boolean safeMode) { 103 | Camera.Parameters parameters = camera.getParameters(); 104 | 105 | if (parameters == null) { 106 | Log.w(TAG, "Device error: no camera parameters are available. Proceeding without configuration."); 107 | return; 108 | } 109 | 110 | Log.i(TAG, "Initial camera parameters: " + parameters.flatten()); 111 | 112 | if (safeMode) { 113 | Log.w(TAG, "In camera config safe mode -- most settings will not be honored"); 114 | } 115 | 116 | 117 | SharedPreferences prefs = PreferenceManager 118 | .getDefaultSharedPreferences(context); 119 | 120 | // 默认使用自动对焦 121 | String focusMode = findSettableValue( 122 | parameters.getSupportedFocusModes(), 123 | Camera.Parameters.FOCUS_MODE_AUTO); 124 | 125 | // Maybe selected auto-focus but not available, so fall through here: 126 | if (!safeMode && focusMode == null) { 127 | focusMode = findSettableValue(parameters.getSupportedFocusModes(), 128 | Camera.Parameters.FOCUS_MODE_MACRO, 129 | Camera.Parameters.FOCUS_MODE_EDOF); 130 | } 131 | if (focusMode != null) { 132 | parameters.setFocusMode(focusMode); 133 | } 134 | 135 | if (prefs.getBoolean(Config.KEY_INVERT_SCAN, false)) { 136 | String colorMode = findSettableValue( 137 | parameters.getSupportedColorEffects(), 138 | Camera.Parameters.EFFECT_NEGATIVE); 139 | if (colorMode != null) { 140 | parameters.setColorEffect(colorMode); 141 | } 142 | } 143 | 144 | parameters.setPreviewSize(cameraResolution.x, cameraResolution.y); 145 | camera.setParameters(parameters); 146 | 147 | Camera.Parameters afterParameters = camera.getParameters(); 148 | Camera.Size afterSize = afterParameters.getPreviewSize(); 149 | if (afterSize != null && (cameraResolution.x != afterSize.width || cameraResolution.y != afterSize.height)) { 150 | Log.w(TAG, "Camera said it supported preview size " + cameraResolution.x + 'x' + cameraResolution.y + ", but after setting it, preview size is " + afterSize.width + 'x' + afterSize.height); 151 | cameraResolution.x = afterSize.width; 152 | cameraResolution.y = afterSize.height; 153 | } 154 | 155 | /** 设置相机预览为竖屏 */ 156 | camera.setDisplayOrientation(90); 157 | } 158 | 159 | public Point getCameraResolution() { 160 | return cameraResolution; 161 | } 162 | 163 | public Point getScreenResolution() { 164 | return screenResolution; 165 | } 166 | 167 | /** 168 | * 从相机支持的分辨率中计算出最适合的预览界面尺寸 169 | * 170 | * @param parameters 171 | * @param screenResolution 172 | * @return 173 | */ 174 | private Point findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution) { 175 | List rawSupportedSizes = parameters.getSupportedPreviewSizes(); 176 | if (rawSupportedSizes == null) { 177 | Log.w(TAG, "Device returned no supported preview sizes; using default"); 178 | Camera.Size defaultSize = parameters.getPreviewSize(); 179 | return new Point(defaultSize.width, defaultSize.height); 180 | } 181 | 182 | // Sort by size, descending 183 | List supportedPreviewSizes = new ArrayList(rawSupportedSizes); 184 | Collections.sort(supportedPreviewSizes, new Comparator() { 185 | @Override 186 | public int compare(Camera.Size a, Camera.Size b) { 187 | int aPixels = a.height * a.width; 188 | int bPixels = b.height * b.width; 189 | if (bPixels < aPixels) { 190 | return -1; 191 | } 192 | if (bPixels > aPixels) { 193 | return 1; 194 | } 195 | return 0; 196 | } 197 | }); 198 | 199 | if (Log.isLoggable(TAG, Log.INFO)) { 200 | StringBuilder previewSizesString = new StringBuilder(); 201 | for (Camera.Size supportedPreviewSize : supportedPreviewSizes) { 202 | previewSizesString.append(supportedPreviewSize.width).append('x').append(supportedPreviewSize.height).append(' '); 203 | } 204 | Log.i(TAG, "Supported preview sizes: " + previewSizesString); 205 | } 206 | 207 | double screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y; 208 | 209 | // Remove sizes that are unsuitable 210 | Iterator it = supportedPreviewSizes.iterator(); 211 | while (it.hasNext()) { 212 | Camera.Size supportedPreviewSize = it.next(); 213 | int realWidth = supportedPreviewSize.width; 214 | int realHeight = supportedPreviewSize.height; 215 | if (realWidth * realHeight < MIN_PREVIEW_PIXELS) { 216 | it.remove(); 217 | continue; 218 | } 219 | 220 | boolean isCandidatePortrait = realWidth < realHeight; 221 | int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth; 222 | int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight; 223 | 224 | double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight; 225 | double distortion = Math.abs(aspectRatio - screenAspectRatio); 226 | if (distortion > MAX_ASPECT_DISTORTION) { 227 | it.remove(); 228 | continue; 229 | } 230 | 231 | if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) { 232 | Point exactPoint = new Point(realWidth, realHeight); 233 | Log.i(TAG, "Found preview size exactly matching screen size: " + exactPoint); 234 | return exactPoint; 235 | } 236 | } 237 | 238 | // If no exact match, use largest preview size. This was not a great 239 | // idea on older devices because 240 | // of the additional computation needed. We're likely to get here on 241 | // newer Android 4+ devices, where 242 | // the CPU is much more powerful. 243 | if (!supportedPreviewSizes.isEmpty()) { 244 | Camera.Size largestPreview = supportedPreviewSizes.get(0); 245 | Point largestSize = new Point(largestPreview.width, largestPreview.height); 246 | Log.i(TAG, "Using largest suitable preview size: " + largestSize); 247 | return largestSize; 248 | } 249 | 250 | // If there is nothing at all suitable, return current preview size 251 | Camera.Size defaultPreview = parameters.getPreviewSize(); 252 | Point defaultSize = new Point(defaultPreview.width, defaultPreview.height); 253 | Log.i(TAG, "No suitable preview sizes, using default: " + defaultSize); 254 | 255 | return defaultSize; 256 | } 257 | 258 | /** 259 | * 在supportedValues中寻找desiredValues,找不到则返回null 260 | * 261 | * @param supportedValues 262 | * @param desiredValues 263 | * @return 264 | */ 265 | private static String findSettableValue(Collection supportedValues, 266 | String... desiredValues) { 267 | Log.i(TAG, "Supported values: " + supportedValues); 268 | String result = null; 269 | if (supportedValues != null) { 270 | for (String desiredValue : desiredValues) { 271 | if (supportedValues.contains(desiredValue)) { 272 | result = desiredValue; 273 | break; 274 | } 275 | } 276 | } 277 | Log.i(TAG, "Settable value: " + result); 278 | return result; 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /ZabarDemo/zbarcode/src/main/java/com/znq/zbarcode/CaptureActivity.java: -------------------------------------------------------------------------------- 1 | package com.znq.zbarcode; 2 | 3 | import android.Manifest; 4 | import android.app.Activity; 5 | import android.app.AlertDialog; 6 | import android.app.AppOpsManager; 7 | import android.content.Context; 8 | import android.content.DialogInterface; 9 | import android.content.Intent; 10 | import android.content.pm.ActivityInfo; 11 | import android.content.pm.PackageManager; 12 | import android.graphics.Rect; 13 | import android.os.Binder; 14 | import android.os.Build; 15 | import android.os.Bundle; 16 | import android.os.Handler; 17 | import android.support.v4.app.ActivityCompat; 18 | import android.support.v4.content.PermissionChecker; 19 | import android.util.Log; 20 | import android.view.SurfaceHolder; 21 | import android.view.SurfaceView; 22 | import android.view.View; 23 | import android.view.animation.Animation; 24 | import android.view.animation.TranslateAnimation; 25 | import android.widget.ImageView; 26 | import android.widget.RelativeLayout; 27 | import android.widget.TextView; 28 | 29 | import com.znq.zbarcode.camera.CameraManager; 30 | import com.znq.zbarcode.decode.MainHandler; 31 | import com.znq.zbarcode.utils.BeepManager; 32 | 33 | import java.io.IOException; 34 | import java.lang.reflect.Field; 35 | import java.lang.reflect.Method; 36 | 37 | /** 38 | * Desc: 1:启动一个SurfaceView作为取景预览 39 | * 2:开启camera,在后台独立线程中完成扫描任务 40 | * 3:对解码返回的结果进行处理. 41 | * 4:释放资源 42 | * Update by znq on 2016/11/9. 43 | */ 44 | public class CaptureActivity extends Activity implements SurfaceHolder.Callback { 45 | private static final int MY_PERMISSIONS_REQUEST_CAMERA = 26; 46 | public static final String EXTRA_STRING = "extra_string"; 47 | public static final int TYPE_BOOK_COVER = 0x101; 48 | public static final int TYPE_BOOK_CHAPTER = 0x102; 49 | private static final String TAG = "CaptureActivity"; 50 | private MainHandler mainHandler; 51 | private SurfaceHolder mHolder; 52 | 53 | private CameraManager mCameraManager; 54 | private BeepManager beepManager; 55 | 56 | private SurfaceView scanPreview; 57 | private RelativeLayout scanContainer; 58 | private RelativeLayout scanCropView; 59 | private ImageView scanLine; 60 | private Rect mCropRect = null; 61 | 62 | private boolean isHasSurface = false; 63 | private boolean isOpenCamera = false; 64 | 65 | public Handler getHandler() { 66 | return mainHandler; 67 | } 68 | 69 | 70 | public void onCreate(Bundle savedInstanceState) { 71 | super.onCreate(savedInstanceState); 72 | setContentView(R.layout.activity_capture); 73 | setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 74 | initView(); 75 | checkPermissionCamera(); 76 | } 77 | 78 | private void initView() { 79 | scanPreview = (SurfaceView) findViewById(R.id.capture_preview); 80 | scanContainer = (RelativeLayout) findViewById(R.id.capture_container); 81 | scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view); 82 | scanLine = (ImageView) findViewById(R.id.capture_scan_line); 83 | TextView _textTitle = (TextView) findViewById(R.id.scan_title); 84 | _textTitle.setText(getString(R.string.qr_name)); 85 | findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() { 86 | @Override 87 | public void onClick(View v) { 88 | finish(); 89 | } 90 | }); 91 | isHasSurface = false; 92 | beepManager = new BeepManager(this); 93 | 94 | TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation 95 | .RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 96 | 0.9f); 97 | animation.setDuration(3000); 98 | animation.setRepeatCount(-1); 99 | animation.setRepeatMode(Animation.RESTART); 100 | scanLine.startAnimation(animation); 101 | 102 | } 103 | 104 | @Override 105 | protected void onResume() { 106 | super.onResume(); 107 | if (isOpenCamera) { 108 | mHolder = scanPreview.getHolder(); 109 | mCameraManager = new CameraManager(getApplication()); 110 | if (isHasSurface) { 111 | initCamera(mHolder); 112 | } else { 113 | mHolder.addCallback(this); 114 | mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 115 | } 116 | } 117 | } 118 | 119 | @Override 120 | public void onPause() { 121 | releaseCamera(); 122 | super.onPause(); 123 | if (scanLine != null) { 124 | scanLine.clearAnimation(); 125 | scanLine.setVisibility(View.GONE); 126 | } 127 | } 128 | 129 | @Override 130 | protected void onDestroy() { 131 | super.onDestroy(); 132 | //remove SurfaceCallback 133 | if (!isHasSurface) { 134 | scanPreview.getHolder().removeCallback(this); 135 | } 136 | } 137 | 138 | //region 初始化和回收相关资源 139 | private void initCamera(SurfaceHolder surfaceHolder) { 140 | mainHandler = null; 141 | try { 142 | mCameraManager.openDriver(surfaceHolder); 143 | if (mainHandler == null) { 144 | mainHandler = new MainHandler(this, mCameraManager); 145 | } 146 | } catch (IOException ioe) { 147 | Log.e(TAG, "相机被占用", ioe); 148 | } catch (RuntimeException e) { 149 | e.printStackTrace(); 150 | Log.e(TAG, "Unexpected error initializing camera"); 151 | displayFrameworkBugMessageAndExit(); 152 | } 153 | 154 | } 155 | 156 | private void releaseCamera() { 157 | if (null != mainHandler) { 158 | //关闭聚焦,停止预览,清空预览回调,quit子线程looper 159 | mainHandler.quitSynchronously(); 160 | mainHandler = null; 161 | } 162 | //关闭声音 163 | if (null != beepManager) { 164 | Log.e(TAG, "releaseCamera: beepManager release" ); 165 | beepManager.releaseRing(); 166 | beepManager = null; 167 | } 168 | //关闭相机 169 | if (mCameraManager != null) { 170 | mCameraManager.closeDriver(); 171 | mCameraManager = null; 172 | } 173 | } 174 | //endregion 175 | 176 | //region 检查权限 177 | private void checkPermissionCamera() { 178 | int checkPermission = 0; 179 | if (Build.VERSION.SDK_INT >= 23) { 180 | // checkPermission =ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA); 181 | checkPermission = PermissionChecker.checkSelfPermission(this, Manifest.permission.CAMERA); 182 | if (checkPermission != PackageManager.PERMISSION_GRANTED) { 183 | ActivityCompat.requestPermissions(this, 184 | new String[]{Manifest.permission.CAMERA}, 185 | MY_PERMISSIONS_REQUEST_CAMERA); 186 | } else { 187 | isOpenCamera = true; 188 | } 189 | 190 | } else { 191 | checkPermission = checkPermission(26); 192 | if (checkPermission == AppOpsManager.MODE_ALLOWED) { 193 | isOpenCamera = true; 194 | } else if (checkPermission == AppOpsManager.MODE_IGNORED) { 195 | isOpenCamera = false; 196 | displayFrameworkBugMessageAndExit(); 197 | } 198 | } 199 | } 200 | 201 | /** 202 | * 反射调用系统权限,判断权限是否打开 203 | * 204 | * @param permissionCode 相应的权限所对应的code 205 | * @see {@link AppOpsManager } 206 | */ 207 | private int checkPermission(int permissionCode) { 208 | int checkPermission = 0; 209 | if (Build.VERSION.SDK_INT >= 19) { 210 | AppOpsManager _manager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); 211 | try { 212 | Class>[] types = new Class[]{int.class, int.class, String.class}; 213 | Object[] args = new Object[]{permissionCode, Binder.getCallingUid(), getPackageName()}; 214 | Method method = _manager.getClass().getDeclaredMethod("noteOp", types); 215 | method.setAccessible(true); 216 | Object _o = method.invoke(_manager, args); 217 | if ((_o instanceof Integer)) { 218 | checkPermission = (Integer) _o; 219 | } 220 | } catch (Exception e) { 221 | e.printStackTrace(); 222 | } 223 | } else { 224 | checkPermission = 0; 225 | } 226 | return checkPermission; 227 | } 228 | 229 | @Override 230 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 231 | switch (requestCode) { 232 | case MY_PERMISSIONS_REQUEST_CAMERA: { 233 | if (grantResults.length > 0 234 | && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 235 | finish(); 236 | 237 | } else { 238 | finish(); 239 | } 240 | return; 241 | } 242 | } 243 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 244 | } 245 | 246 | private void displayFrameworkBugMessageAndExit() { 247 | String per = String.format(getString(R.string.permission), getString(R.string.camera), getString(R.string.camera)); 248 | String per1 = getString(R.string.low_permission, getString(R.string.camera)); 249 | AlertDialog.Builder builder = new AlertDialog.Builder(this); 250 | builder.setTitle(getString(R.string.qr_name)); 251 | builder.setMessage(per + per1); 252 | builder.setPositiveButton(getString(R.string.i_know), new DialogInterface.OnClickListener() { 253 | 254 | @Override 255 | public void onClick(DialogInterface dialog, int which) { 256 | CaptureActivity.this.finish(); 257 | } 258 | 259 | }); 260 | builder.setOnCancelListener(new DialogInterface.OnCancelListener() { 261 | 262 | @Override 263 | public void onCancel(DialogInterface dialog) { 264 | CaptureActivity.this.finish(); 265 | } 266 | }); 267 | builder.show(); 268 | } 269 | //endregion 270 | 271 | //region 扫描结果 272 | public void checkResult(final String result) { 273 | if (beepManager != null) { 274 | beepManager.startRing(); 275 | } 276 | mainHandler.postDelayed(new Runnable() { 277 | @Override 278 | public void run() { 279 | activityResult(result.trim()); 280 | } 281 | }, beepManager.getTimeDuration()); 282 | } 283 | 284 | private void activityResult(String result) { 285 | if (!isFinishing()) { 286 | Intent intent =new Intent(); 287 | Bundle bundle = new Bundle(); 288 | bundle.putInt("width", mCropRect.width()); 289 | bundle.putInt("height", mCropRect.height()); 290 | bundle.putString(EXTRA_STRING, result); 291 | intent.putExtras(bundle); 292 | setResult(RESULT_OK,intent); 293 | CaptureActivity.this.finish(); 294 | } 295 | } 296 | 297 | //endregion 298 | 299 | //region 初始化截取的矩形区域 300 | public Rect initCrop() { 301 | int cameraWidth = 0; 302 | int cameraHeight = 0; 303 | if (null != mCameraManager) { 304 | cameraWidth = mCameraManager.getCameraResolution().y; 305 | cameraHeight = mCameraManager.getCameraResolution().x; 306 | } 307 | 308 | /** 获取布局中扫描框的位置信息 */ 309 | int[] location = new int[2]; 310 | scanCropView.getLocationInWindow(location); 311 | 312 | int cropLeft = location[0]; 313 | int cropTop = location[1] - getStatusBarHeight(); 314 | 315 | int cropWidth = scanCropView.getWidth(); 316 | int cropHeight = scanCropView.getHeight(); 317 | 318 | /** 获取布局容器的宽高 */ 319 | int containerWidth = scanContainer.getWidth(); 320 | int containerHeight = scanContainer.getHeight(); 321 | 322 | /** 计算最终截取的矩形的左上角顶点x坐标 */ 323 | int x = cropLeft * cameraWidth / containerWidth; 324 | /** 计算最终截取的矩形的左上角顶点y坐标 */ 325 | int y = cropTop * cameraHeight / containerHeight; 326 | 327 | /** 计算最终截取的矩形的宽度 */ 328 | int width = cropWidth * cameraWidth / containerWidth; 329 | /** 计算最终截取的矩形的高度 */ 330 | int height = cropHeight * cameraHeight / containerHeight; 331 | 332 | /** 生成最终的截取的矩形 */ 333 | mCropRect = new Rect(x, y, width + x, height + y); 334 | return new Rect(x, y, width + x, height + y); 335 | } 336 | 337 | private int getStatusBarHeight() { 338 | try { 339 | Class> c = Class.forName("com.android.internal.R$dimen"); 340 | Object obj = c.newInstance(); 341 | Field field = c.getField("status_bar_height"); 342 | int x = Integer.parseInt(field.get(obj).toString()); 343 | return getResources().getDimensionPixelSize(x); 344 | } catch (Exception e) { 345 | e.printStackTrace(); 346 | } 347 | return 0; 348 | } 349 | //endregion 350 | 351 | //region SurfaceHolder Callback 回调方法 352 | @Override 353 | public void surfaceCreated(SurfaceHolder holder) { 354 | if (holder == null) { 355 | Log.e(TAG, "*** 没有添加SurfaceHolder的Callback"); 356 | } 357 | if (isOpenCamera) { 358 | if (!isHasSurface) { 359 | isHasSurface = true; 360 | initCamera(holder); 361 | } 362 | } 363 | 364 | } 365 | 366 | @Override 367 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 368 | Log.e(TAG, "surfaceChanged: "); 369 | 370 | } 371 | 372 | @Override 373 | public void surfaceDestroyed(SurfaceHolder holder) { 374 | isHasSurface = false; 375 | 376 | } 377 | //endregion 378 | } 379 | --------------------------------------------------------------------------------