├── demo
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── drawable-xhdpi
│ │ │ │ ├── ic_default_qr.png
│ │ │ │ ├── ic_build_white_36dp.png
│ │ │ │ ├── ic_clear_white_36dp.png
│ │ │ │ └── ic_slideshow_white_36dp.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── strings.xml
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ ├── menu
│ │ │ │ └── main.xml
│ │ │ └── layout
│ │ │ │ ├── activity_main.xml
│ │ │ │ └── activity_generator.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── me
│ │ │ └── ydcool
│ │ │ └── qrmodule
│ │ │ └── demo
│ │ │ ├── MainActivity.java
│ │ │ └── DemoGeneratorActivity.java
│ ├── test
│ │ └── java
│ │ │ └── me
│ │ │ └── ydcool
│ │ │ └── qrmodule
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── me
│ │ └── ydcool
│ │ └── qrmodule
│ │ └── ApplicationTest.java
├── proguard-rules.pro
└── build.gradle
├── qrmodule
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── raw
│ │ │ │ └── beep.ogg
│ │ │ ├── drawable-xhdpi
│ │ │ │ ├── ic_flash_on_white_36dp.png
│ │ │ │ ├── ic_arrow_back_white_36dp.png
│ │ │ │ └── ic_flash_off_white_36dp.png
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ └── colors.xml
│ │ │ ├── values-zh-rCN
│ │ │ │ └── strings.xml
│ │ │ ├── menu
│ │ │ │ └── capture_menu.xml
│ │ │ └── layout
│ │ │ │ └── activity_qr_scanner.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── me
│ │ │ └── ydcool
│ │ │ └── lib
│ │ │ └── qrmodule
│ │ │ ├── common
│ │ │ └── Cons.java
│ │ │ ├── view
│ │ │ ├── ViewfinderResultPointCallback.java
│ │ │ └── ViewfinderView.java
│ │ │ ├── decoding
│ │ │ ├── FinishListener.java
│ │ │ ├── InactivityTimer.java
│ │ │ ├── DecodeThread.java
│ │ │ ├── DecodeFormatManager.java
│ │ │ ├── DecodeHandler.java
│ │ │ ├── CaptureActivityHandler.java
│ │ │ └── Intents.java
│ │ │ ├── camera
│ │ │ ├── AutoFocusCallback.java
│ │ │ ├── PreviewCallback.java
│ │ │ ├── PlanarYUVLuminanceSource.java
│ │ │ ├── FlashlightManager.java
│ │ │ ├── CameraConfigurationManager.java
│ │ │ └── CameraManager.java
│ │ │ ├── encoding
│ │ │ └── QrGenerator.java
│ │ │ └── activity
│ │ │ └── QrScannerActivity.java
│ ├── test
│ │ └── java
│ │ │ └── me
│ │ │ └── ydcool
│ │ │ └── lib
│ │ │ └── qrmodule
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── me
│ │ └── ydcool
│ │ └── lib
│ │ └── qrmodule
│ │ └── ApplicationTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── art
├── demo_scan.gif
└── demo_generate.gif
├── .gitignore
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .travis.yml
├── gradle.properties
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/demo/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/qrmodule/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':demo', ':qrmodule'
2 |
--------------------------------------------------------------------------------
/art/demo_scan.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/art/demo_scan.gif
--------------------------------------------------------------------------------
/art/demo_generate.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/art/demo_generate.gif
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/qrmodule/src/main/res/raw/beep.ogg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/qrmodule/src/main/res/raw/beep.ogg
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/demo/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/demo/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/demo/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/demo/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/drawable-xhdpi/ic_default_qr.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/demo/src/main/res/drawable-xhdpi/ic_default_qr.png
--------------------------------------------------------------------------------
/demo/src/main/res/drawable-xhdpi/ic_build_white_36dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/demo/src/main/res/drawable-xhdpi/ic_build_white_36dp.png
--------------------------------------------------------------------------------
/demo/src/main/res/drawable-xhdpi/ic_clear_white_36dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/demo/src/main/res/drawable-xhdpi/ic_clear_white_36dp.png
--------------------------------------------------------------------------------
/demo/src/main/res/drawable-xhdpi/ic_slideshow_white_36dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/demo/src/main/res/drawable-xhdpi/ic_slideshow_white_36dp.png
--------------------------------------------------------------------------------
/qrmodule/src/main/res/drawable-xhdpi/ic_flash_on_white_36dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/qrmodule/src/main/res/drawable-xhdpi/ic_flash_on_white_36dp.png
--------------------------------------------------------------------------------
/qrmodule/src/main/res/drawable-xhdpi/ic_arrow_back_white_36dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/qrmodule/src/main/res/drawable-xhdpi/ic_arrow_back_white_36dp.png
--------------------------------------------------------------------------------
/qrmodule/src/main/res/drawable-xhdpi/ic_flash_off_white_36dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ydcool/QrModule/HEAD/qrmodule/src/main/res/drawable-xhdpi/ic_flash_off_white_36dp.png
--------------------------------------------------------------------------------
/qrmodule/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | QrModule
3 | Scan Barcode
4 | Flash Light
5 |
6 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/qrmodule/src/main/res/values-zh-rCN/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 二维码模块
4 | 将取景框对准二维码,即可自动扫描
5 | 闪光灯
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Jan 26 09:19:12 CST 2016
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-2.10-all.zip
7 |
--------------------------------------------------------------------------------
/qrmodule/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/qrmodule/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #66ffffff
4 | #ffff0000
5 | #60000000
6 | #b0000000
7 | #c0ffff00
8 |
--------------------------------------------------------------------------------
/qrmodule/src/main/res/menu/capture_menu.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/demo/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 | sudo: false
3 | jdk: oraclejdk7
4 | android:
5 | components:
6 | - tools
7 | - build-tools-23.0.2
8 | - android-23
9 | - extra-android-m2repository
10 | - extra-android-support
11 | script:
12 | - ./gradlew assembleRelease
13 | deploy:
14 | provider: releases
15 | file: app/build/outputs/apk/app-release.apk
16 | skip_cleanup: true
17 | on:
18 | tags: true
19 |
--------------------------------------------------------------------------------
/demo/src/test/java/me/ydcool/qrmodule/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package me.ydcool.qrmodule;
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 | }
--------------------------------------------------------------------------------
/qrmodule/src/test/java/me/ydcool/lib/qrmodule/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package me.ydcool.lib.qrmodule;
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 | }
--------------------------------------------------------------------------------
/demo/src/androidTest/java/me/ydcool/qrmodule/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package me.ydcool.qrmodule;
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 | }
--------------------------------------------------------------------------------
/demo/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/qrmodule/src/androidTest/java/me/ydcool/lib/qrmodule/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package me.ydcool.lib.qrmodule;
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 | }
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/common/Cons.java:
--------------------------------------------------------------------------------
1 | package me.ydcool.lib.qrmodule.common;
2 |
3 | /**
4 | * Created by ydcool on 15/11/18.
5 | *
6 | * @author ydcool
7 | */
8 | public class Cons {
9 | public static final int ID_AUTO_FOCUS = 100;
10 | public static final int ID_RESTART_PREVIEW = 101;
11 | public static final int ID_DECODE_SUCCEED = 102;
12 | public static final int ID_DECODE_FAILED = 103;
13 | public static final int ID_RETURN_SCAN_RESULT = 104;
14 | public static final int ID_LAUNCH_PRODUCT_QUERY = 105;
15 | public static final int ID_DECODE = 106;
16 | public static final int ID_QUIT = 107;
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/demo/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 /Users/Shared/Android/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 |
--------------------------------------------------------------------------------
/demo/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "me.ydcool.qrmodule"
9 | minSdkVersion 14
10 | targetSdkVersion 22
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile project (':qrmodule')
26 | compile 'com.android.support:appcompat-v7:23.1.1'
27 | compile 'com.jakewharton:butterknife:6.1.0'
28 | }
29 |
--------------------------------------------------------------------------------
/demo/src/main/res/menu/main.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/demo/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/qrmodule/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 /Users/Shared/Android/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 | -keep class !android.support.v7.internal.view.menu.**,android.support.** {*;}
19 |
20 | -keep class android.support.v4.app.** { *; }
21 | -keep interface android.support.v4.app.** { *; }
22 |
23 | -keep class android.support.v7.app.** { *; }
24 | -keep interface android.support.v7.app.** { *; }
25 |
26 | -keep class android.support.v7.internal.** { *; }
27 | -keep interface android.support.v7.internal.** { *; }
28 |
--------------------------------------------------------------------------------
/qrmodule/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | minSdkVersion 14
9 | targetSdkVersion 22
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | lintOptions {
20 | abortOnError false
21 | }
22 | }
23 |
24 | dependencies {
25 | compile fileTree(dir: 'libs', include: ['*.jar'])
26 | testCompile 'junit:junit:4.12'
27 | compile 'com.google.zxing:core:latest.integration'
28 | }
29 |
30 | buildscript {
31 | repositories {
32 | jcenter()
33 | }
34 | dependencies {
35 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
36 | classpath "org.jfrog.buildinfo:build-info-extractor-gradle:3.1.1"
37 | }
38 | }
39 |
40 | //apply from: 'bintray.gradle'
41 | apply from:'https://raw.githubusercontent.com/Ydcool/EasingAndroid/master/lib/bintray.gradle'
42 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/view/ViewfinderResultPointCallback.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2009 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 me.ydcool.lib.qrmodule.view;
18 |
19 | import com.google.zxing.ResultPoint;
20 | import com.google.zxing.ResultPointCallback;
21 |
22 | public final class ViewfinderResultPointCallback implements ResultPointCallback {
23 |
24 | private final ViewfinderView viewfinderView;
25 |
26 | public ViewfinderResultPointCallback(ViewfinderView viewfinderView) {
27 | this.viewfinderView = viewfinderView;
28 | }
29 |
30 | public void foundPossibleResultPoint(ResultPoint point) {
31 | viewfinderView.addPossibleResultPoint(point);
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/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 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 | PROJ_GROUP=me.ydcool.lib
20 | PROJ_VERSION=1.0
21 | PROJ_NAME=QrModule
22 | PROJ_WEBSITEURL=https://github.com/Ydcool/QrModule
23 | PROJ_ISSUETRACKERURL=https://github.com/Ydcool/QrModule/issues
24 | PROJ_VCSURL=https://github.com/Ydcool/QrModule.git
25 | PROJ_DESCRIPTION=Qr Scanner and generator module for Android
26 | PROJ_ARTIFACTID=qrmodule
27 |
28 | DEVELOPER_ID=ydcool
29 | DEVELOPER_NAME=ydcool
30 | DEVELOPER_EMAIL=hi@ydcool.me
31 |
32 | # placeholders for travis
33 | BINTRAY_USER=ydcool
34 | BINTRAY_KEY=****
35 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/decoding/FinishListener.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 me.ydcool.lib.qrmodule.decoding;
18 |
19 | import android.app.Activity;
20 | import android.content.DialogInterface;
21 |
22 | /**
23 | * Simple listener used to exit the app in a few cases.
24 | */
25 | public final class FinishListener
26 | implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, Runnable {
27 |
28 | private final Activity activityToFinish;
29 |
30 | public FinishListener(Activity activityToFinish) {
31 | this.activityToFinish = activityToFinish;
32 | }
33 |
34 | public void onCancel(DialogInterface dialogInterface) {
35 | run();
36 | }
37 |
38 | public void onClick(DialogInterface dialogInterface, int i) {
39 | run();
40 | }
41 |
42 | public void run() {
43 | activityToFinish.finish();
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | QrModule
3 | Start Scan
4 | Scan Result Here
5 | Input Content(Required)
6 | Error Correction Level(Default:L(~7%))
7 | Overlay:ON
8 | Overlay:OFF
9 | Overlay Xfermode
10 | Footnote(Feature Under Develop)
11 | Qr Image Size(Required)
12 | QrCode Margin(Default:2)
13 | Set Qr Code Color.Default is Black(0,0,0)
14 | R(0~255)
15 | G(0~255)
16 | B(0~255)
17 | Set Qr Code Background Color.Default is White(255,255,255)
18 | R(0~255)
19 | G(0~255)
20 | B(0~255)
21 | Generate!
22 | Over Size(Required If Overlay has Set)
23 | Overlay Alpha,Default:255(Opaque)
24 | Clear
25 | Generate
26 | 0~255
27 | Generated QrCode.
28 |
29 |
30 |
--------------------------------------------------------------------------------
/demo/src/main/java/me/ydcool/qrmodule/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package me.ydcool.qrmodule.demo;
2 |
3 | import android.content.Intent;
4 | import android.os.Bundle;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.widget.TextView;
7 |
8 | import butterknife.ButterKnife;
9 | import butterknife.InjectView;
10 | import butterknife.OnClick;
11 | import me.ydcool.lib.qrmodule.activity.QrScannerActivity;
12 | import me.ydcool.qrmodule.R;
13 |
14 | public class MainActivity extends AppCompatActivity {
15 |
16 | @InjectView(R.id.txt_scan_result)
17 | TextView mTxtScanResult;
18 |
19 | @Override
20 | protected void onCreate(Bundle savedInstanceState) {
21 | super.onCreate(savedInstanceState);
22 | setContentView(R.layout.activity_main);
23 | ButterKnife.inject(this);
24 | }
25 |
26 | @OnClick(R.id.Main_btn_scan)
27 | void onScanBtnClick() {
28 | startActivityForResult(
29 | new Intent(MainActivity.this, QrScannerActivity.class),
30 | QrScannerActivity.QR_REQUEST_CODE);
31 | }
32 |
33 | @OnClick(R.id.Main_btn_generate)
34 | void onGenerateBtnClick() {
35 | startActivity(new Intent(MainActivity.this, DemoGeneratorActivity.class));
36 | }
37 |
38 | @Override
39 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
40 | super.onActivityResult(requestCode, resultCode, data);
41 | if (requestCode == QrScannerActivity.QR_REQUEST_CODE) {
42 | mTxtScanResult.setText(
43 | resultCode == RESULT_OK
44 | ? data.getExtras().getString(QrScannerActivity.QR_RESULT_STR)
45 | : "Scanned Nothing!");
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/demo/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
17 |
18 |
23 |
24 |
29 |
30 |
31 |
32 |
38 |
39 |
45 |
46 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/camera/AutoFocusCallback.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 me.ydcool.lib.qrmodule.camera;
18 |
19 | import android.hardware.Camera;
20 | import android.os.Handler;
21 | import android.os.Message;
22 | import android.util.Log;
23 |
24 | final class AutoFocusCallback implements Camera.AutoFocusCallback {
25 |
26 | private static final String TAG = AutoFocusCallback.class.getSimpleName();
27 |
28 | private static final long AUTOFOCUS_INTERVAL_MS = 1500L;
29 |
30 | private Handler autoFocusHandler;
31 | private int autoFocusMessage;
32 |
33 | void setHandler(Handler autoFocusHandler, int autoFocusMessage) {
34 | this.autoFocusHandler = autoFocusHandler;
35 | this.autoFocusMessage = autoFocusMessage;
36 | }
37 |
38 | public void onAutoFocus(boolean success, Camera camera) {
39 | if (autoFocusHandler != null) {
40 | Message message = autoFocusHandler.obtainMessage(autoFocusMessage, success);
41 | autoFocusHandler.sendMessageDelayed(message, AUTOFOCUS_INTERVAL_MS);
42 | autoFocusHandler = null;
43 | } else {
44 | Log.d(TAG, "Got auto-focus callback, but no handler for it");
45 | }
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/qrmodule/src/main/res/layout/activity_qr_scanner.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
12 |
13 |
18 |
19 |
23 |
24 |
33 |
34 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/camera/PreviewCallback.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 me.ydcool.lib.qrmodule.camera;
18 |
19 | import android.graphics.Point;
20 | import android.hardware.Camera;
21 | import android.os.Handler;
22 | import android.os.Message;
23 | import android.util.Log;
24 |
25 | final class PreviewCallback implements Camera.PreviewCallback {
26 |
27 | private static final String TAG = PreviewCallback.class.getSimpleName();
28 |
29 | private final CameraConfigurationManager configManager;
30 | private final boolean useOneShotPreviewCallback;
31 | private Handler previewHandler;
32 | private int previewMessage;
33 |
34 | PreviewCallback(CameraConfigurationManager configManager, boolean useOneShotPreviewCallback) {
35 | this.configManager = configManager;
36 | this.useOneShotPreviewCallback = useOneShotPreviewCallback;
37 | }
38 |
39 | void setHandler(Handler previewHandler, int previewMessage) {
40 | this.previewHandler = previewHandler;
41 | this.previewMessage = previewMessage;
42 | }
43 |
44 | public void onPreviewFrame(byte[] data, Camera camera) {
45 | Point cameraResolution = configManager.getCameraResolution();
46 | if (!useOneShotPreviewCallback) {
47 | camera.setPreviewCallback(null);
48 | }
49 | if (previewHandler != null) {
50 | Message message = previewHandler.obtainMessage(previewMessage, cameraResolution.x,
51 | cameraResolution.y, data);
52 | message.sendToTarget();
53 | previewHandler = null;
54 | } else {
55 | Log.d(TAG, "Got preview callback, but no handler for it");
56 | }
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/decoding/InactivityTimer.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 me.ydcool.lib.qrmodule.decoding;
18 |
19 | import android.app.Activity;
20 |
21 | import java.util.concurrent.Executors;
22 | import java.util.concurrent.ScheduledExecutorService;
23 | import java.util.concurrent.ScheduledFuture;
24 | import java.util.concurrent.ThreadFactory;
25 | import java.util.concurrent.TimeUnit;
26 |
27 | /**
28 | * Finishes an activity after a period of inactivity.
29 | */
30 | public final class InactivityTimer {
31 |
32 | private static final int INACTIVITY_DELAY_SECONDS = 5 * 60;
33 |
34 | private final ScheduledExecutorService inactivityTimer =
35 | Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory());
36 | private final Activity activity;
37 | private ScheduledFuture> inactivityFuture = null;
38 |
39 | public InactivityTimer(Activity activity) {
40 | this.activity = activity;
41 | onActivity();
42 | }
43 |
44 | public void onActivity() {
45 | cancel();
46 | inactivityFuture = inactivityTimer.schedule(new me.ydcool.lib.qrmodule.decoding.FinishListener(activity),
47 | INACTIVITY_DELAY_SECONDS,
48 | TimeUnit.SECONDS);
49 | }
50 |
51 | private void cancel() {
52 | if (inactivityFuture != null) {
53 | inactivityFuture.cancel(true);
54 | inactivityFuture = null;
55 | }
56 | }
57 |
58 | public void shutdown() {
59 | cancel();
60 | inactivityTimer.shutdown();
61 | }
62 |
63 | private static final class DaemonThreadFactory implements ThreadFactory {
64 | public Thread newThread(Runnable runnable) {
65 | Thread thread = new Thread(runnable);
66 | thread.setDaemon(true);
67 | return thread;
68 | }
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/decoding/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 me.ydcool.lib.qrmodule.decoding;
18 |
19 | import android.os.Handler;
20 | import android.os.Looper;
21 |
22 | import com.google.zxing.BarcodeFormat;
23 | import com.google.zxing.DecodeHintType;
24 | import com.google.zxing.ResultPointCallback;
25 |
26 | import java.util.Hashtable;
27 | import java.util.Vector;
28 | import java.util.concurrent.CountDownLatch;
29 |
30 | import me.ydcool.lib.qrmodule.activity.QrScannerActivity;
31 |
32 | /**
33 | * This thread does all the heavy lifting of decoding the images.
34 | */
35 | final class DecodeThread extends Thread {
36 |
37 | public static final String BARCODE_BITMAP = "barcode_bitmap";
38 | private final QrScannerActivity activity;
39 | private final Hashtable hints;
40 | private final CountDownLatch handlerInitLatch;
41 | private Handler handler;
42 |
43 | DecodeThread(QrScannerActivity activity,
44 | Vector decodeFormats,
45 | String characterSet,
46 | ResultPointCallback resultPointCallback) {
47 |
48 | this.activity = activity;
49 | handlerInitLatch = new CountDownLatch(1);
50 |
51 | hints = new Hashtable(3);
52 |
53 | if (decodeFormats == null || decodeFormats.isEmpty()) {
54 | decodeFormats = new Vector();
55 | decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
56 | decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
57 | decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
58 | }
59 |
60 | hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
61 |
62 | if (characterSet != null) {
63 | hints.put(DecodeHintType.CHARACTER_SET, characterSet);
64 | }
65 |
66 | hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback);
67 | }
68 |
69 | Handler getHandler() {
70 | try {
71 | handlerInitLatch.await();
72 | } catch (InterruptedException ie) {
73 | // continue?
74 | }
75 | return handler;
76 | }
77 |
78 | @Override
79 | public void run() {
80 | Looper.prepare();
81 | handler = new DecodeHandler(activity, hints);
82 | handlerInitLatch.countDown();
83 | Looper.loop();
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/decoding/DecodeFormatManager.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 me.ydcool.lib.qrmodule.decoding;
18 |
19 | import android.content.Intent;
20 | import android.net.Uri;
21 |
22 | import com.google.zxing.BarcodeFormat;
23 |
24 | import java.util.Arrays;
25 | import java.util.List;
26 | import java.util.Vector;
27 | import java.util.regex.Pattern;
28 |
29 | final class DecodeFormatManager {
30 |
31 | static final Vector PRODUCT_FORMATS;
32 | static final Vector ONE_D_FORMATS;
33 | static final Vector QR_CODE_FORMATS;
34 | static final Vector DATA_MATRIX_FORMATS;
35 | private static final Pattern COMMA_PATTERN = Pattern.compile(",");
36 |
37 | static {
38 | PRODUCT_FORMATS = new Vector(5);
39 | PRODUCT_FORMATS.add(BarcodeFormat.UPC_A);
40 | PRODUCT_FORMATS.add(BarcodeFormat.UPC_E);
41 | PRODUCT_FORMATS.add(BarcodeFormat.EAN_13);
42 | PRODUCT_FORMATS.add(BarcodeFormat.EAN_8);
43 | // PRODUCT_FORMATS.add(BarcodeFormat.RSS14);
44 | ONE_D_FORMATS = new Vector(PRODUCT_FORMATS.size() + 4);
45 | ONE_D_FORMATS.addAll(PRODUCT_FORMATS);
46 | ONE_D_FORMATS.add(BarcodeFormat.CODE_39);
47 | ONE_D_FORMATS.add(BarcodeFormat.CODE_93);
48 | ONE_D_FORMATS.add(BarcodeFormat.CODE_128);
49 | ONE_D_FORMATS.add(BarcodeFormat.ITF);
50 | QR_CODE_FORMATS = new Vector(1);
51 | QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE);
52 | DATA_MATRIX_FORMATS = new Vector(1);
53 | DATA_MATRIX_FORMATS.add(BarcodeFormat.DATA_MATRIX);
54 | }
55 |
56 | private DecodeFormatManager() {
57 | }
58 |
59 | static Vector parseDecodeFormats(Intent intent) {
60 | List scanFormats = null;
61 | String scanFormatsString = intent.getStringExtra(Intents.Scan.SCAN_FORMATS);
62 | if (scanFormatsString != null) {
63 | scanFormats = Arrays.asList(COMMA_PATTERN.split(scanFormatsString));
64 | }
65 | return parseDecodeFormats(scanFormats, intent.getStringExtra(Intents.Scan.MODE));
66 | }
67 |
68 | static Vector parseDecodeFormats(Uri inputUri) {
69 | List formats = inputUri.getQueryParameters(Intents.Scan.SCAN_FORMATS);
70 | if (formats != null && formats.size() == 1 && formats.get(0) != null) {
71 | formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
72 | }
73 | return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
74 | }
75 |
76 | private static Vector parseDecodeFormats(Iterable scanFormats,
77 | String decodeMode) {
78 | if (scanFormats != null) {
79 | Vector formats = new Vector();
80 | try {
81 | for (String format : scanFormats) {
82 | formats.add(BarcodeFormat.valueOf(format));
83 | }
84 | return formats;
85 | } catch (IllegalArgumentException iae) {
86 | // ignore it then
87 | }
88 | }
89 | if (decodeMode != null) {
90 | if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
91 | return PRODUCT_FORMATS;
92 | }
93 | if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
94 | return QR_CODE_FORMATS;
95 | }
96 | if (Intents.Scan.DATA_MATRIX_MODE.equals(decodeMode)) {
97 | return DATA_MATRIX_FORMATS;
98 | }
99 | if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
100 | return ONE_D_FORMATS;
101 | }
102 | }
103 | return null;
104 | }
105 |
106 | }
107 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/decoding/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 me.ydcool.lib.qrmodule.decoding;
18 |
19 | import android.os.Bundle;
20 | import android.os.Handler;
21 | import android.os.Looper;
22 | import android.os.Message;
23 | import android.util.Log;
24 |
25 | import com.google.zxing.BinaryBitmap;
26 | import com.google.zxing.DecodeHintType;
27 | import com.google.zxing.MultiFormatReader;
28 | import com.google.zxing.ReaderException;
29 | import com.google.zxing.Result;
30 | import com.google.zxing.common.HybridBinarizer;
31 |
32 | import java.util.Hashtable;
33 |
34 | import me.ydcool.lib.qrmodule.activity.QrScannerActivity;
35 | import me.ydcool.lib.qrmodule.camera.CameraManager;
36 | import me.ydcool.lib.qrmodule.camera.PlanarYUVLuminanceSource;
37 | import me.ydcool.lib.qrmodule.common.Cons;
38 |
39 | final class DecodeHandler extends Handler {
40 |
41 | private static final String TAG = DecodeHandler.class.getSimpleName();
42 |
43 | private final QrScannerActivity activity;
44 | private final MultiFormatReader multiFormatReader;
45 |
46 | DecodeHandler(QrScannerActivity activity, Hashtable hints) {
47 | multiFormatReader = new MultiFormatReader();
48 | multiFormatReader.setHints(hints);
49 | this.activity = activity;
50 | }
51 |
52 | @Override
53 | public void handleMessage(Message message) {
54 | switch (message.what) {
55 | case Cons.ID_DECODE:
56 | //Log.d(TAG, "Got decode message");
57 | decode((byte[]) message.obj, message.arg1, message.arg2);
58 | break;
59 | case Cons.ID_QUIT:
60 | Looper.myLooper().quit();
61 | break;
62 | }
63 | }
64 |
65 | /**
66 | * Decode the data within the viewfinder rectangle, and time how long it took. For efficiency,
67 | * reuse the same reader objects from one decode to the next.
68 | *
69 | * @param data The YUV preview frame.
70 | * @param width The width of the preview frame.
71 | * @param height The height of the preview frame.
72 | */
73 | private void decode(byte[] data, int width, int height) {
74 | long start = System.currentTimeMillis();
75 | Result rawResult = null;
76 |
77 | //modify here
78 | byte[] rotatedData = new byte[data.length];
79 | for (int y = 0; y < height; y++) {
80 | for (int x = 0; x < width; x++)
81 | rotatedData[x * height + height - y - 1] = data[x + y * width];
82 | }
83 | int tmp = width; // Here we are swapping, that's the difference to #11
84 | width = height;
85 | height = tmp;
86 |
87 | PlanarYUVLuminanceSource source = CameraManager.get().buildLuminanceSource(rotatedData, width, height);
88 | BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
89 | try {
90 | rawResult = multiFormatReader.decodeWithState(bitmap);
91 | } catch (ReaderException re) {
92 | // continue
93 | } finally {
94 | multiFormatReader.reset();
95 | }
96 |
97 | if (rawResult != null) {
98 | long end = System.currentTimeMillis();
99 | Log.d(TAG, "Found barcode (" + (end - start) + " ms):\n" + rawResult.toString());
100 | Message message = Message.obtain(activity.getHandler(), Cons.ID_DECODE_SUCCEED, rawResult);
101 | Bundle bundle = new Bundle();
102 | bundle.putParcelable(DecodeThread.BARCODE_BITMAP, source.renderCroppedGreyscaleBitmap());
103 | message.setData(bundle);
104 | //Log.d(TAG, "Sending decode succeeded message...");
105 | message.sendToTarget();
106 | } else {
107 | Message message = Message.obtain(activity.getHandler(), Cons.ID_DECODE_FAILED);
108 | message.sendToTarget();
109 | }
110 | }
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/camera/PlanarYUVLuminanceSource.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 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 me.ydcool.lib.qrmodule.camera;
18 |
19 | import android.graphics.Bitmap;
20 | import android.util.Log;
21 |
22 | import com.google.zxing.LuminanceSource;
23 |
24 | /**
25 | * This object extends LuminanceSource around an array of YUV data returned from the camera driver,
26 | * with the option to crop to a rectangle within the full data. This can be used to exclude
27 | * superfluous pixels around the perimeter and speed up decoding.
28 | * It works for any pixel format where the Y channel is planar and appears first, including
29 | * YCbCr_420_SP and YCbCr_422_SP.
30 | *
31 | * @author dswitkin@google.com (Daniel Switkin)
32 | */
33 | public final class PlanarYUVLuminanceSource extends LuminanceSource {
34 | private final byte[] yuvData;
35 | private final int dataWidth;
36 | private final int dataHeight;
37 | private final int left;
38 | private final int top;
39 |
40 | public PlanarYUVLuminanceSource(byte[] yuvData, int dataWidth, int dataHeight, int left, int top,
41 | int width, int height) {
42 | super(width, height);
43 |
44 | if (left + width > dataWidth || top + height > dataHeight) {
45 | Log.e("ZXing", "Crop rectangle does not fit within image data.");
46 | // throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
47 | }
48 |
49 | this.yuvData = yuvData;
50 | this.dataWidth = dataWidth;
51 | this.dataHeight = dataHeight;
52 | this.left = left;
53 | this.top = top;
54 | }
55 |
56 | @Override
57 | public byte[] getRow(int y, byte[] row) {
58 | if (y < 0 || y >= getHeight()) {
59 | throw new IllegalArgumentException("Requested row is outside the image: " + y);
60 | }
61 | int width = getWidth();
62 | if (row == null || row.length < width) {
63 | row = new byte[width];
64 | }
65 | int offset = (y + top) * dataWidth + left;
66 | System.arraycopy(yuvData, offset, row, 0, width);
67 | return row;
68 | }
69 |
70 | @Override
71 | public byte[] getMatrix() {
72 | int width = getWidth();
73 | int height = getHeight();
74 |
75 | // If the caller asks for the entire underlying image, save the copy and give them the
76 | // original data. The docs specifically warn that result.length must be ignored.
77 | if (width == dataWidth && height == dataHeight) {
78 | return yuvData;
79 | }
80 |
81 | int area = width * height;
82 | byte[] matrix = new byte[area];
83 | int inputOffset = top * dataWidth + left;
84 |
85 | // If the width matches the full width of the underlying data, perform a single copy.
86 | if (width == dataWidth) {
87 | System.arraycopy(yuvData, inputOffset, matrix, 0, area);
88 | return matrix;
89 | }
90 |
91 | // Otherwise copy one cropped row at a time.
92 | byte[] yuv = yuvData;
93 | for (int y = 0; y < height; y++) {
94 | int outputOffset = y * width;
95 | System.arraycopy(yuv, inputOffset, matrix, outputOffset, width);
96 | inputOffset += dataWidth;
97 | }
98 | return matrix;
99 | }
100 |
101 | @Override
102 | public boolean isCropSupported() {
103 | return true;
104 | }
105 |
106 | public int getDataWidth() {
107 | return dataWidth;
108 | }
109 |
110 | public int getDataHeight() {
111 | return dataHeight;
112 | }
113 |
114 | public Bitmap renderCroppedGreyscaleBitmap() {
115 | int width = getWidth();
116 | int height = getHeight();
117 | int[] pixels = new int[width * height];
118 | byte[] yuv = yuvData;
119 | int inputOffset = top * dataWidth + left;
120 |
121 | for (int y = 0; y < height; y++) {
122 | int outputOffset = y * width;
123 | for (int x = 0; x < width; x++) {
124 | int grey = yuv[inputOffset + x] & 0xff;
125 | pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
126 | }
127 | inputOffset += dataWidth;
128 | }
129 |
130 | Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
131 | bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
132 | return bitmap;
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### Android QR Module
2 |
3 |
4 |
5 | [](https://bintray.com/ydcool/maven/QrModule/_latestVersion)
6 | [](https://travis-ci.org/Ydcool/QrModule)
7 |
8 | >
9 | * Thanks to [Ryan_Tang][].本项目基于他[blog][]上的项目优化改进。
10 | * Feel free to fork and pr.
11 |
12 | #### Features
13 |
14 | * Qr Scan
15 | * Qr Generate
16 |
17 | ##### QR Scan
18 |
19 | Demo APK [download][] or scan 
20 |
21 | 
22 |
23 | ###### Usage
24 |
25 | 1 Add gradle dependence:
26 |
27 | ```java
28 | compile 'me.ydcool.lib:qrmodule:latest.integration'
29 | ```
30 |
31 | 2 Add [QrScannerActivity][] to your `AndroidManifest.xml`
32 |
33 | ```xml
34 |
35 | ```
36 |
37 | 3 Add permissions
38 |
39 | ```xml
40 |
41 |
42 |
43 | ```
44 |
45 | 4 Start `QrScannerActivity` in your activity.
46 |
47 | ```java
48 | Intent intent = new Intent(MainActivity.this, QrScannerActivity.class);
49 | startActivityForResult(intent, QrScannerActivity.QR_REQUEST_CODE);
50 | ```
51 |
52 | 5 And receive scanner activity result in your activity.
53 |
54 | ```java
55 | @Override
56 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
57 | super.onActivityResult(requestCode, resultCode, data);
58 | if (requestCode == QrScannerActivity.QR_REQUEST_CODE) {
59 | Log.d(TAG, resultCode == RESULT_OK
60 | ? data.getExtras().getString(QrScannerActivity.QR_RESULT_STR)
61 | : "Scanned Nothing!");
62 | }
63 | }
64 | ```
65 |
66 | See more details in Demo [MainActivity][].
67 |
68 | ##### QR Generate
69 |
70 | 
71 |
72 | ###### Usage
73 |
74 | * Generate qr code with `QrGenerator`.
75 |
76 | ```java
77 | Bitmap qrCode = new QrGenerator.Builder()
78 | .content("https://github.com/Ydcool/QrModule")
79 | .qrSize(300)
80 | .margin(2)
81 | .color(Color.BLACK)
82 | .bgColor(Color.WHITE)
83 | .ecc(ErrorCorrectionLevel.H)
84 | .overlay(getContext(),R.mipmap.ic_launcher)
85 | .overlaySize(100)
86 | .overlayAlpha(255)
87 | .overlayXfermode(PortBuff.Mode.SRC_ATOP)
88 | .encode();
89 |
90 | mImageView.setImageBitmap(qrCode);
91 | ```
92 |
93 | | Method | Description |
94 | | ----- | ----- |
95 | | `content(String content)` | content of qr code. |
96 | | `qrSize(int size)` | qr code image size. |
97 | | `margin(int margin)` | default is 2.See more about [EncodeHintType.MARGIN][] |
98 | | `color(int color)` | qr code foreground color. |
99 | | `color(Context c, @ColorRes int color)` | set foreground color with color resource. |
100 | | `bgColor(int color)` | set the background color. |
101 | | `bgColor(Context c,@ColorRes int color)` | set the background color with color resource. |
102 | | `ecc(ErrorCorrectionLevel e)` | error correction level , default is `L` (~7%).See more about [ErrorCorrectionLevel][]. |
103 | | `overlay(Bitmap overlay)` | overlay image on qr code, usually set with logo. **NOTICE: once you set overlay image,you'd better set `ecc` to `H`**. |
104 | | `overlay(Context c,@DrawableRes int overlay)` | set overlay with drawable resource. |
105 | | `overlaySize(int size)` | overlay image size in qr code. |
106 | | `overlayAlpha(int alpha)` |set overlay image alpha, range [0,255], default is 255(opaque). |
107 | | `overlayXfermode(PorterDuff.Mode m)` | set xfermode for overlay bitmap,default is `SRC`,see more about [PorterDuff.Mode][]. |
108 | | `footNote(String s)` | *This feature is under develop* . |
109 | | `encode()` | return a encoded qrCode bitmap. |
110 |
111 | #### TODO
112 |
113 | * Custom pattern support.
114 |
115 | #### License
116 |
117 | Apache License.
118 | See the [LICENSE][] for more info.
119 |
120 | [Ryan_Tang]:http://blog.csdn.net/ryantang03
121 | [blog]:http://blog.csdn.net/ryantang03/article/details/7831826
122 | [QrScannerActivity]:https://github.com/Ydcool/QrModule/blob/master/qrmodule/src/main/java/me/ydcool/lib/qrmodule/activity/QrScannerActivity.java
123 | [MainActivity]:https://github.com/Ydcool/QrModule/blob/master/demo/src/main/java/me/ydcool/qrmodule/demo/MainActivity.java
124 | [QrGenerator]:https://github.com/Ydcool/QrModule/blob/master/qrmodule/src/main/java/me/ydcool/lib/qrmodule/encoding/QrGenerator.java
125 | [DemoGeneratorActivity]:https://github.com/Ydcool/QrModule/blob/master/demo/src/main/java/me/ydcool/qrmodule/demo/DemoGeneratorActivity.java
126 | [LICENSE]:https://github.com/Ydcool/QrModule/blob/master/LICENSE
127 | [EncodeHintType.MARGIN]:https://github.com/zxing/zxing/blob/master/core/src/main/java/com/google/zxing/EncodeHintType.java
128 | [ErrorCorrectionLevel]:https://github.com/zxing/zxing/blob/master/core/src/main/java/com/google/zxing/qrcode/decoder/ErrorCorrectionLevel.java
129 | [PorterDuff.Mode]:http://developer.android.com/reference/android/graphics/PorterDuff.Mode.html
130 | [download]:http://cdn.ydcool.me/apk%2Fqrmodule-demo-v1.0.apk
131 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/camera/FlashlightManager.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 me.ydcool.lib.qrmodule.camera;
18 |
19 | import android.os.IBinder;
20 | import android.util.Log;
21 |
22 | import java.lang.reflect.InvocationTargetException;
23 | import java.lang.reflect.Method;
24 |
25 | /**
26 | * This class is used to activate the weak light on some camera phones (not flash)
27 | * in order to illuminate surfaces for scanning. There is no official way to do this,
28 | * but, classes which allow access to this function still exist on some devices.
29 | * This therefore proceeds through a great deal of reflection.
30 | *
31 | * See
32 | * http://almondmendoza.com/2009/01/05/changing-the-screen-brightness-programatically/ and
33 | *
34 | * http://code.google.com/p/droidled/source/browse/trunk/src/com/droidled/demo/DroidLED.java.
35 | * Thanks to Ryan Alford for pointing out the availability of this class.
36 | */
37 | final class FlashlightManager {
38 |
39 | private static final String TAG = FlashlightManager.class.getSimpleName();
40 |
41 | private static final Object iHardwareService;
42 | private static final Method setFlashEnabledMethod;
43 |
44 | static {
45 | iHardwareService = getHardwareService();
46 | setFlashEnabledMethod = getSetFlashEnabledMethod(iHardwareService);
47 | if (iHardwareService == null) {
48 | Log.v(TAG, "This device does supports control of a flashlight");
49 | } else {
50 | Log.v(TAG, "This device does not support control of a flashlight");
51 | }
52 | }
53 |
54 | private FlashlightManager() {
55 | }
56 |
57 | /**
58 | * �����������ƿ���
59 | */
60 | //FIXME
61 | static void enableFlashlight() {
62 | setFlashlight(false);
63 | }
64 |
65 | static void disableFlashlight() {
66 | setFlashlight(false);
67 | }
68 |
69 | private static Object getHardwareService() {
70 | Class> serviceManagerClass = maybeForName("android.os.ServiceManager");
71 | if (serviceManagerClass == null) {
72 | return null;
73 | }
74 |
75 | Method getServiceMethod = maybeGetMethod(serviceManagerClass, "getService", String.class);
76 | if (getServiceMethod == null) {
77 | return null;
78 | }
79 |
80 | Object hardwareService = invoke(getServiceMethod, null, "hardware");
81 | if (hardwareService == null) {
82 | return null;
83 | }
84 |
85 | Class> iHardwareServiceStubClass = maybeForName("android.os.IHardwareService$Stub");
86 | if (iHardwareServiceStubClass == null) {
87 | return null;
88 | }
89 |
90 | Method asInterfaceMethod = maybeGetMethod(iHardwareServiceStubClass, "asInterface", IBinder.class);
91 | if (asInterfaceMethod == null) {
92 | return null;
93 | }
94 |
95 | return invoke(asInterfaceMethod, null, hardwareService);
96 | }
97 |
98 | private static Method getSetFlashEnabledMethod(Object iHardwareService) {
99 | if (iHardwareService == null) {
100 | return null;
101 | }
102 | Class> proxyClass = iHardwareService.getClass();
103 | return maybeGetMethod(proxyClass, "setFlashlightEnabled", boolean.class);
104 | }
105 |
106 | private static Class> maybeForName(String name) {
107 | try {
108 | return Class.forName(name);
109 | } catch (ClassNotFoundException cnfe) {
110 | // OK
111 | return null;
112 | } catch (RuntimeException re) {
113 | Log.w(TAG, "Unexpected error while finding class " + name, re);
114 | return null;
115 | }
116 | }
117 |
118 | private static Method maybeGetMethod(Class> clazz, String name, Class>... argClasses) {
119 | try {
120 | return clazz.getMethod(name, argClasses);
121 | } catch (NoSuchMethodException nsme) {
122 | // OK
123 | return null;
124 | } catch (RuntimeException re) {
125 | Log.w(TAG, "Unexpected error while finding method " + name, re);
126 | return null;
127 | }
128 | }
129 |
130 | private static Object invoke(Method method, Object instance, Object... args) {
131 | try {
132 | return method.invoke(instance, args);
133 | } catch (IllegalAccessException e) {
134 | Log.w(TAG, "Unexpected error while invoking " + method, e);
135 | return null;
136 | } catch (InvocationTargetException e) {
137 | Log.w(TAG, "Unexpected error while invoking " + method, e.getCause());
138 | return null;
139 | } catch (RuntimeException re) {
140 | Log.w(TAG, "Unexpected error while invoking " + method, re);
141 | return null;
142 | }
143 | }
144 |
145 | private static void setFlashlight(boolean active) {
146 | if (iHardwareService != null) {
147 | invoke(setFlashEnabledMethod, iHardwareService, active);
148 | }
149 | }
150 |
151 | }
152 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/decoding/CaptureActivityHandler.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 me.ydcool.lib.qrmodule.decoding;
18 |
19 | import android.app.Activity;
20 | import android.content.Intent;
21 | import android.graphics.Bitmap;
22 | import android.net.Uri;
23 | import android.os.Bundle;
24 | import android.os.Handler;
25 | import android.os.Message;
26 | import android.util.Log;
27 |
28 | import com.google.zxing.BarcodeFormat;
29 | import com.google.zxing.Result;
30 |
31 | import java.util.Vector;
32 |
33 | import me.ydcool.lib.qrmodule.activity.QrScannerActivity;
34 | import me.ydcool.lib.qrmodule.camera.CameraManager;
35 | import me.ydcool.lib.qrmodule.common.Cons;
36 | import me.ydcool.lib.qrmodule.view.ViewfinderResultPointCallback;
37 |
38 | /**
39 | * This class handles all the messaging which comprises the state machine for capture.
40 | */
41 | public final class CaptureActivityHandler extends Handler {
42 |
43 | private static final String TAG = CaptureActivityHandler.class.getSimpleName();
44 |
45 | private final QrScannerActivity activity;
46 | private final DecodeThread decodeThread;
47 | private State state;
48 |
49 | public CaptureActivityHandler(QrScannerActivity activity, Vector decodeFormats,
50 | String characterSet) {
51 | this.activity = activity;
52 | decodeThread = new DecodeThread(activity, decodeFormats, characterSet,
53 | new ViewfinderResultPointCallback(activity.getViewfinderView()));
54 | decodeThread.start();
55 | state = State.SUCCESS;
56 | // Start ourselves capturing previews and decoding.
57 | CameraManager.get().startPreview();
58 | restartPreviewAndDecode();
59 | }
60 |
61 | @Override
62 | public void handleMessage(Message message) {
63 | switch (message.what) {
64 | case Cons.ID_AUTO_FOCUS:
65 | //Log.d(TAG, "Got auto-focus message");
66 | // When one auto focus pass finishes, start another. This is the closest thing to
67 | // continuous AF. It does seem to hunt a bit, but I'm not sure what else to do.
68 | if (state == State.PREVIEW) {
69 | CameraManager.get().requestAutoFocus(this, Cons.ID_AUTO_FOCUS);
70 | }
71 | break;
72 | case Cons.ID_RESTART_PREVIEW:
73 | Log.d(TAG, "Got restart preview message");
74 | restartPreviewAndDecode();
75 | break;
76 | case Cons.ID_DECODE_SUCCEED:
77 | Log.d(TAG, "Got decode succeeded message");
78 | state = State.SUCCESS;
79 | Bundle bundle = message.getData();
80 |
81 | /***********************************************************************/
82 | Bitmap barcode = bundle == null ? null :
83 | (Bitmap) bundle.getParcelable(DecodeThread.BARCODE_BITMAP);
84 |
85 | activity.handleDecode((Result) message.obj, barcode);
86 | /***********************************************************************/
87 | break;
88 | case Cons.ID_DECODE_FAILED:
89 | // We're decoding as fast as possible, so when one decode fails, start another.
90 | state = State.PREVIEW;
91 | CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), Cons.ID_DECODE);
92 | break;
93 | case Cons.ID_RETURN_SCAN_RESULT:
94 | Log.d(TAG, "Got return scan result message");
95 | activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
96 | activity.finish();
97 | break;
98 | case Cons.ID_LAUNCH_PRODUCT_QUERY:
99 | Log.d(TAG, "Got product query message");
100 | String url = (String) message.obj;
101 | Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
102 | intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
103 | activity.startActivity(intent);
104 | break;
105 | }
106 | }
107 |
108 | public void quitSynchronously() {
109 | state = State.DONE;
110 | CameraManager.get().stopPreview();
111 | Message quit = Message.obtain(decodeThread.getHandler(), Cons.ID_QUIT);
112 | quit.sendToTarget();
113 | try {
114 | decodeThread.join();
115 | } catch (InterruptedException e) {
116 | // continue
117 | }
118 |
119 | // Be absolutely sure we don't send any queued up messages
120 | removeMessages(Cons.ID_DECODE_SUCCEED);
121 | removeMessages(Cons.ID_DECODE_FAILED);
122 | }
123 |
124 | public void restartPreviewAndDecode() {
125 | if (state == State.SUCCESS) {
126 | state = State.PREVIEW;
127 | CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), Cons.ID_DECODE);
128 | CameraManager.get().requestAutoFocus(this, Cons.ID_AUTO_FOCUS);
129 | activity.drawViewfinder();
130 | }
131 | }
132 |
133 | private enum State {
134 | PREVIEW,
135 | SUCCESS,
136 | DONE
137 | }
138 |
139 | }
140 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/view/ViewfinderView.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 me.ydcool.lib.qrmodule.view;
18 |
19 | import android.content.Context;
20 | import android.graphics.Bitmap;
21 | import android.graphics.Canvas;
22 | import android.graphics.Color;
23 | import android.graphics.Paint;
24 | import android.graphics.Rect;
25 | import android.util.AttributeSet;
26 | import android.view.View;
27 |
28 | import com.google.zxing.ResultPoint;
29 |
30 | import java.util.Collection;
31 | import java.util.HashSet;
32 |
33 | import me.ydcool.lib.qrmodule.R;
34 | import me.ydcool.lib.qrmodule.camera.CameraManager;
35 |
36 | /**
37 | * This view is overlaid on top of the camera preview. It adds the viewfinder rectangle and partial
38 | * transparency outside it, as well as the laser scanner animation and result points.
39 | */
40 | public final class ViewfinderView extends View {
41 |
42 | private static final int[] SCANNER_ALPHA = {0, 64, 128, 192, 255, 192, 128, 64};
43 | private static final long ANIMATION_DELAY = 100L;
44 | private static final int OPAQUE = 0xFF;
45 |
46 | private final Paint paint;
47 | private final int maskColor;
48 | private final int resultColor;
49 | private final int frameColor;
50 | private final int laserColor;
51 | private final int resultPointColor;
52 | private Bitmap resultBitmap;
53 | private int scannerAlpha;
54 | private String hintString;
55 | private Collection possibleResultPoints;
56 | private Collection lastPossibleResultPoints;
57 |
58 | // This constructor is used when the class is built from an XML resource.
59 | public ViewfinderView(Context context, AttributeSet attrs) {
60 | super(context, attrs);
61 |
62 | // Initialize these once for performance rather than calling them every time in onDraw().
63 | paint = new Paint();
64 | paint.setTextSize(context.getResources().getDisplayMetrics().scaledDensity * 15);
65 | paint.setAntiAlias(true);
66 | paint.setTextAlign(Paint.Align.CENTER);
67 |
68 | maskColor = getContext().getResources().getColor(R.color.viewfinder_mask);
69 | resultColor = getContext().getResources().getColor(R.color.result_view);
70 | frameColor = getContext().getResources().getColor(R.color.viewfinder_frame);
71 | laserColor = getContext().getResources().getColor(R.color.viewfinder_laser);
72 | resultPointColor = getContext().getResources().getColor(R.color.possible_result_points);
73 | hintString = context.getString(R.string.scan_hint);
74 | scannerAlpha = 0;
75 | possibleResultPoints = new HashSet<>(5);
76 | }
77 |
78 | @Override
79 | public void onDraw(Canvas canvas) {
80 | Rect frame = CameraManager.get().getFramingRect();
81 | if (frame == null) {
82 | return;
83 | }
84 | int width = canvas.getWidth();
85 | int height = canvas.getHeight();
86 |
87 | // Draw the exterior (i.e. outside the framing rect) darkened
88 | paint.setColor(resultBitmap != null ? resultColor : maskColor);
89 | canvas.drawRect(0, 0, width, frame.top, paint);
90 | canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
91 | canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
92 | canvas.drawRect(0, frame.bottom + 1, width, height, paint);
93 |
94 | if (resultBitmap != null) {
95 | // Draw the opaque result bitmap over the scanning rectangle
96 | paint.setAlpha(OPAQUE);
97 | canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint);
98 | } else {
99 |
100 | // Draw a two pixel solid black border inside the framing rect
101 | paint.setColor(frameColor);
102 | canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint);
103 | canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint);
104 | canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint);
105 | canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint);
106 |
107 | // Draw a red "laser scanner" line through the middle to show decoding is active
108 | paint.setColor(laserColor);
109 | paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
110 | scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
111 | int middle = frame.height() / 2 + frame.top;
112 | canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1, middle + 2, paint);
113 |
114 | //draw hint text
115 | paint.setColor(Color.WHITE);
116 | canvas.drawText(hintString, frame.centerX(), frame.bottom + frame.height() / 4, paint);
117 |
118 | Collection currentPossible = possibleResultPoints;
119 | Collection currentLast = lastPossibleResultPoints;
120 | if (currentPossible.isEmpty()) {
121 | lastPossibleResultPoints = null;
122 | } else {
123 | possibleResultPoints = new HashSet<>(5);
124 | lastPossibleResultPoints = currentPossible;
125 | paint.setAlpha(OPAQUE);
126 | paint.setColor(resultPointColor);
127 | for (ResultPoint point : currentPossible) {
128 | canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 6.0f, paint);
129 | }
130 | }
131 | if (currentLast != null) {
132 | paint.setAlpha(OPAQUE / 2);
133 | paint.setColor(resultPointColor);
134 | for (ResultPoint point : currentLast) {
135 | canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 3.0f, paint);
136 | }
137 | }
138 |
139 | // Request another update at the animation interval, but only repaint the laser line,
140 | // not the entire viewfinder mask.
141 | postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom);
142 | }
143 | }
144 |
145 | public void drawViewfinder() {
146 | resultBitmap = null;
147 | invalidate();
148 | }
149 |
150 | /**
151 | * Draw a bitmap with the result points highlighted instead of the live scanning display.
152 | *
153 | * @param barcode An image of the decoded barcode.
154 | */
155 | public void drawResultBitmap(Bitmap barcode) {
156 | resultBitmap = barcode;
157 | invalidate();
158 | }
159 |
160 | public void addPossibleResultPoint(ResultPoint point) {
161 | possibleResultPoints.add(point);
162 | }
163 |
164 | }
165 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/decoding/Intents.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 me.ydcool.lib.qrmodule.decoding;
18 |
19 | /**
20 | * This class provides the constants to use when sending an Intent to Barcode Scanner.
21 | * These strings are effectively API and cannot be changed.
22 | */
23 | public final class Intents {
24 | private Intents() {
25 | }
26 |
27 | public static final class Scan {
28 | /**
29 | * Send this intent to open the Barcodes app in scanning mode, find a barcode, and return
30 | * the results.
31 | */
32 | public static final String ACTION = "com.google.zxing.client.android.SCAN";
33 |
34 | /**
35 | * By default, sending Scan.ACTION will decode all barcodes that we understand. However it
36 | * may be useful to limit scanning to certain formats. Use Intent.putExtra(MODE, value) with
37 | * one of the values below ({@link #PRODUCT_MODE}, {@link #ONE_D_MODE}, {@link #QR_CODE_MODE}).
38 | * Optional.
39 | * Setting this is effectively shorthnad for setting explicit formats with {@link #SCAN_FORMATS}.
40 | * It is overridden by that setting.
41 | */
42 | public static final String MODE = "SCAN_MODE";
43 |
44 | /**
45 | * Comma-separated list of formats to scan for. The values must match the names of
46 | * {@link com.google.zxing.BarcodeFormat}s, such as {@link com.google.zxing.BarcodeFormat#EAN_13}.
47 | * Example: "EAN_13,EAN_8,QR_CODE"
48 | * This overrides {@link #MODE}.
49 | */
50 | public static final String SCAN_FORMATS = "SCAN_FORMATS";
51 |
52 | /**
53 | * @see com.google.zxing.DecodeHintType#CHARACTER_SET
54 | */
55 | public static final String CHARACTER_SET = "CHARACTER_SET";
56 |
57 | /**
58 | * Decode only UPC and EAN barcodes. This is the right choice for shopping apps which get
59 | * prices, reviews, etc. for products.
60 | */
61 | public static final String PRODUCT_MODE = "PRODUCT_MODE";
62 |
63 | /**
64 | * Decode only 1D barcodes (currently UPC, EAN, Code 39, and Code 128).
65 | */
66 | public static final String ONE_D_MODE = "ONE_D_MODE";
67 |
68 | /**
69 | * Decode only QR codes.
70 | */
71 | public static final String QR_CODE_MODE = "QR_CODE_MODE";
72 |
73 | /**
74 | * Decode only Data Matrix codes.
75 | */
76 | public static final String DATA_MATRIX_MODE = "DATA_MATRIX_MODE";
77 |
78 | /**
79 | * If a barcode is found, Barcodes returns RESULT_OK to onActivityResult() of the app which
80 | * requested the scan via startSubActivity(). The barcodes contents can be retrieved with
81 | * intent.getStringExtra(RESULT). If the user presses Back, the result code will be
82 | * RESULT_CANCELED.
83 | */
84 | public static final String RESULT = "SCAN_RESULT";
85 |
86 | /**
87 | * Call intent.getStringExtra(RESULT_FORMAT) to determine which barcode format was found.
88 | * See Contents.Format for possible values.
89 | */
90 | public static final String RESULT_FORMAT = "SCAN_RESULT_FORMAT";
91 |
92 | /**
93 | * Setting this to false will not save scanned codes in the history.
94 | */
95 | public static final String SAVE_HISTORY = "SAVE_HISTORY";
96 |
97 | private Scan() {
98 | }
99 | }
100 |
101 | public static final class Encode {
102 | /**
103 | * Send this intent to encode a piece of data as a QR code and display it full screen, so
104 | * that another person can scan the barcode from your screen.
105 | */
106 | public static final String ACTION = "com.google.zxing.client.android.ENCODE";
107 |
108 | /**
109 | * The data to encode. Use Intent.putExtra(DATA, data) where data is either a String or a
110 | * Bundle, depending on the type and format specified. Non-QR Code formats should
111 | * just use a String here. For QR Code, see Contents for details.
112 | */
113 | public static final String DATA = "ENCODE_DATA";
114 |
115 | /**
116 | * The type of data being supplied if the format is QR Code. Use
117 | * Intent.putExtra(TYPE, type) with one of Contents.Type.
118 | */
119 | public static final String TYPE = "ENCODE_TYPE";
120 |
121 | /**
122 | * The barcode format to be displayed. If this isn't specified or is blank,
123 | * it defaults to QR Code. Use Intent.putExtra(FORMAT, format), where
124 | * format is one of Contents.Format.
125 | */
126 | public static final String FORMAT = "ENCODE_FORMAT";
127 |
128 | private Encode() {
129 | }
130 | }
131 |
132 | public static final class SearchBookContents {
133 | /**
134 | * Use Google Book Search to search the contents of the book provided.
135 | */
136 | public static final String ACTION = "com.google.zxing.client.android.SEARCH_BOOK_CONTENTS";
137 |
138 | /**
139 | * The book to search, identified by ISBN number.
140 | */
141 | public static final String ISBN = "ISBN";
142 |
143 | /**
144 | * An optional field which is the text to search for.
145 | */
146 | public static final String QUERY = "QUERY";
147 |
148 | private SearchBookContents() {
149 | }
150 | }
151 |
152 | public static final class WifiConnect {
153 | /**
154 | * Internal intent used to trigger connection to a wi-fi network.
155 | */
156 | public static final String ACTION = "com.google.zxing.client.android.WIFI_CONNECT";
157 |
158 | /**
159 | * The network to connect to, all the configuration provided here.
160 | */
161 | public static final String SSID = "SSID";
162 |
163 | /**
164 | * The network to connect to, all the configuration provided here.
165 | */
166 | public static final String TYPE = "TYPE";
167 |
168 | /**
169 | * The network to connect to, all the configuration provided here.
170 | */
171 | public static final String PASSWORD = "PASSWORD";
172 |
173 | private WifiConnect() {
174 | }
175 | }
176 |
177 |
178 | public static final class Share {
179 | /**
180 | * Give the user a choice of items to encode as a barcode, then render it as a QR Code and
181 | * display onscreen for a friend to scan with their phone.
182 | */
183 | public static final String ACTION = "com.google.zxing.client.android.SHARE";
184 |
185 | private Share() {
186 | }
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/demo/src/main/java/me/ydcool/qrmodule/demo/DemoGeneratorActivity.java:
--------------------------------------------------------------------------------
1 | package me.ydcool.qrmodule.demo;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.graphics.Bitmap;
5 | import android.graphics.BitmapFactory;
6 | import android.graphics.Color;
7 | import android.graphics.PorterDuff;
8 | import android.os.Bundle;
9 | import android.support.v7.app.AppCompatActivity;
10 | import android.text.TextUtils;
11 | import android.view.Menu;
12 | import android.view.MenuItem;
13 | import android.view.View;
14 | import android.widget.AdapterView;
15 | import android.widget.ArrayAdapter;
16 | import android.widget.CompoundButton;
17 | import android.widget.EditText;
18 | import android.widget.ImageView;
19 | import android.widget.ScrollView;
20 | import android.widget.Spinner;
21 | import android.widget.Toast;
22 | import android.widget.ToggleButton;
23 |
24 | import com.google.zxing.WriterException;
25 | import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
26 |
27 | import java.util.EnumSet;
28 |
29 | import butterknife.ButterKnife;
30 | import butterknife.InjectView;
31 | import me.ydcool.lib.qrmodule.encoding.QrGenerator;
32 | import me.ydcool.qrmodule.R;
33 |
34 | public class DemoGeneratorActivity extends AppCompatActivity {
35 | private static final String TAG = "DemoGeneratorActivity";
36 |
37 | @InjectView(R.id.root_scrollview)
38 | ScrollView mScrollView;
39 | @InjectView(R.id.edt_content)
40 | EditText mEdtContent;
41 | @InjectView(R.id.edt_size)
42 | EditText mEdtSize;
43 | @InjectView(R.id.edt_margin)
44 | EditText mEdtMargin;
45 | @InjectView(R.id.edt_color_r)
46 | EditText mEdtColorR;
47 | @InjectView(R.id.edt_color_g)
48 | EditText mEdtColorG;
49 | @InjectView(R.id.edt_color_b)
50 | EditText mEdtColorB;
51 | @InjectView(R.id.edt_color_bg_r)
52 | EditText mEdtColorBgR;
53 | @InjectView(R.id.edt_color_bg_g)
54 | EditText mEdtColorBgG;
55 | @InjectView(R.id.edt_color_bg_b)
56 | EditText mEdtColorBgB;
57 | @InjectView(R.id.spinner_ecc)
58 | Spinner mSpinnerEcc;
59 | @InjectView(R.id.toggle_overlay)
60 | ToggleButton mTbOverlay;
61 | @InjectView(R.id.edt_overlay_size)
62 | EditText mEdtOverlaySize;
63 | @InjectView(R.id.edt_overlay_aplha)
64 | EditText mEdtOverlayAplha;
65 | @InjectView(R.id.spinner_xfermode)
66 | Spinner mSpinnerXfermode;
67 | @InjectView(R.id.edt_footnote)
68 | EditText mEdtFootnote;
69 | @InjectView(R.id.img_qr_generated)
70 | ImageView mImgQrGenerated;
71 |
72 | private ErrorCorrectionLevel mEcc = ErrorCorrectionLevel.L;
73 | private PorterDuff.Mode mXfermode = PorterDuff.Mode.SRC;
74 |
75 | private boolean mOverlayEnabled;
76 |
77 | @Override
78 | protected void onCreate(Bundle savedInstanceState) {
79 | super.onCreate(savedInstanceState);
80 | setContentView(R.layout.activity_generator);
81 | ButterKnife.inject(this);
82 |
83 | setUpEccSpinner();
84 | setUpXfermodeSpinner();
85 | setUpOverlayToggleBtn();
86 | }
87 |
88 | @Override
89 | public boolean onCreateOptionsMenu(Menu menu) {
90 | getMenuInflater().inflate(R.menu.main, menu);
91 | return super.onCreateOptionsMenu(menu);
92 | }
93 |
94 | @Override
95 | public boolean onOptionsItemSelected(MenuItem item) {
96 | super.onOptionsItemSelected(item);
97 | switch (item.getItemId()) {
98 | case R.id.action_quick_build:
99 | quickEdit(false);
100 | return true;
101 | case R.id.action_clear:
102 | quickEdit(true);
103 | return true;
104 | case R.id.action_generate:
105 | onGenerateClick();
106 | return true;
107 | default:
108 | return false;
109 | }
110 | }
111 |
112 | void onGenerateClick() {
113 | if (checkEmpty(mEdtContent)) {
114 | Toast.makeText(DemoGeneratorActivity.this, "Content Required!", Toast.LENGTH_SHORT).show();
115 | } else if (checkEmpty(mEdtSize)) {
116 | Toast.makeText(DemoGeneratorActivity.this, "Qr Size Required!", Toast.LENGTH_SHORT).show();
117 | } else {
118 | try {
119 | int _color = Color.rgb(getInputtedInt(mEdtColorR, 0), getInputtedInt(mEdtColorG, 0), getInputtedInt(mEdtColorB, 0));
120 | int _bgColor = Color.rgb(getInputtedInt(mEdtColorBgR, 255), getInputtedInt(mEdtColorBgG, 255), getInputtedInt(mEdtColorBgB, 255));
121 |
122 | Bitmap qrCode = new QrGenerator.Builder()
123 | .content(mEdtContent.getText().toString())
124 | .qrSize(getInputtedInt(mEdtSize, 400))
125 | .margin(getInputtedInt(mEdtMargin, 2))
126 | .color(_color)
127 | .bgColor(_bgColor)
128 | .ecc(mEcc)
129 | .overlay(mOverlayEnabled ? BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher) : null)
130 | .overlaySize(getInputtedInt(mEdtOverlaySize, 100))
131 | .overlayAlpha(getInputtedInt(mEdtOverlayAplha, 255))
132 | .overlayXfermode(mXfermode)
133 | .footNote(mEdtFootnote.getText().toString())
134 | .encode();
135 |
136 | mImgQrGenerated.setImageBitmap(qrCode);
137 | mScrollView.smoothScrollTo(0, 0);
138 | } catch (WriterException e) {
139 | e.printStackTrace();
140 | }
141 | }
142 | }
143 |
144 | private void setUpEccSpinner() {
145 | final String[] items = getEnumNames(ErrorCorrectionLevel.class);
146 | ArrayAdapter eccSpinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items);
147 | eccSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
148 | mSpinnerEcc.setAdapter(eccSpinnerAdapter);
149 | mSpinnerEcc.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
150 | @Override
151 | public void onItemSelected(AdapterView> parent, View view, int position, long id) {
152 | mEcc = ErrorCorrectionLevel.valueOf(items[position]);
153 | }
154 |
155 | @Override
156 | public void onNothingSelected(AdapterView> parent) {
157 | }
158 | });
159 | }
160 |
161 | private void setUpXfermodeSpinner() {
162 | final String[] items = getEnumNames(PorterDuff.Mode.class);
163 | ArrayAdapter xfermodeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items);
164 | xfermodeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
165 | mSpinnerXfermode.setAdapter(xfermodeAdapter);
166 | mSpinnerXfermode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
167 | @Override
168 | public void onItemSelected(AdapterView> parent, View view, int position, long id) {
169 | mXfermode = PorterDuff.Mode.valueOf(items[position]);
170 | }
171 |
172 | @Override
173 | public void onNothingSelected(AdapterView> parent) {
174 | }
175 | });
176 | }
177 |
178 | private void setUpOverlayToggleBtn() {
179 | mTbOverlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
180 | @Override
181 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
182 | mOverlayEnabled = isChecked;
183 | }
184 | });
185 | }
186 |
187 | @SuppressLint("SetTextI18n")
188 | private void quickEdit(boolean clear) {
189 | mEdtContent.setText(clear ? "" : "https://github.com/Ydcool/QrModule");
190 | mEdtSize.setText(clear ? "" : "400");
191 | mEdtMargin.setText(clear ? "" : "2");
192 | mEdtColorR.setText(clear ? "" : "65");
193 | mEdtColorG.setText(clear ? "" : "82");
194 | mEdtColorB.setText(clear ? "" : "172");
195 | mEdtColorBgR.setText(clear ? "" : "233");
196 | mEdtColorBgG.setText(clear ? "" : "233");
197 | mEdtColorBgB.setText(clear ? "" : "233");
198 |
199 | mSpinnerEcc.setSelection(ErrorCorrectionLevel.H.ordinal(), true);
200 |
201 | mOverlayEnabled = !clear;
202 | mTbOverlay.setChecked(!clear);
203 |
204 | mEdtOverlaySize.setText(clear ? "" : "100");
205 | mEdtOverlayAplha.setText(clear ? "" : "255");
206 |
207 | mXfermode = PorterDuff.Mode.SRC_ATOP;
208 | mSpinnerXfermode.setSelection(PorterDuff.Mode.SRC_ATOP.ordinal(), true);
209 |
210 | if (clear)
211 | mImgQrGenerated.setImageResource(R.drawable.ic_default_qr);
212 | }
213 |
214 | private boolean checkEmpty(EditText e) {
215 | return TextUtils.isEmpty(e.getText());
216 | }
217 |
218 | private int getInputtedInt(EditText edt, int def) {
219 | try {
220 | String s = edt.getText().toString();
221 |
222 | if (TextUtils.isEmpty(s))
223 | return def;
224 | else
225 | return Integer.parseInt(s);
226 |
227 | } catch (Exception e) {
228 | e.printStackTrace();
229 | return def;
230 | }
231 | }
232 |
233 | private > String[] getEnumNames(Class enumType) {
234 | EnumSet set = EnumSet.allOf(enumType);
235 |
236 | String[] names = new String[set.size()];
237 |
238 | for (Enum e : set) {
239 | names[e.ordinal()] = e.toString();
240 | }
241 |
242 | return names;
243 | }
244 | }
245 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/encoding/QrGenerator.java:
--------------------------------------------------------------------------------
1 | package me.ydcool.lib.qrmodule.encoding;
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.Color;
8 | import android.graphics.Paint;
9 | import android.graphics.PorterDuff;
10 | import android.graphics.PorterDuffXfermode;
11 | import android.graphics.Rect;
12 | import android.text.Layout;
13 | import android.text.StaticLayout;
14 | import android.text.TextPaint;
15 | import android.text.TextUtils;
16 |
17 | import com.google.zxing.BarcodeFormat;
18 | import com.google.zxing.EncodeHintType;
19 | import com.google.zxing.MultiFormatWriter;
20 | import com.google.zxing.WriterException;
21 | import com.google.zxing.common.BitMatrix;
22 | import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
23 |
24 | import java.util.Hashtable;
25 |
26 | /**
27 | * @author Ryan Tang
28 | */
29 | public final class QrGenerator {
30 | private int mQrSize;
31 | private int mColor;
32 | private int mMargin;
33 | private int mBgColor;
34 | private int mOverlaySize;
35 | private int mOverlayAlpha;
36 | private String mContent;
37 | private String mFootNote;
38 | private Bitmap mOverlay;
39 | private ErrorCorrectionLevel mEcl;
40 | private PorterDuff.Mode mXfermode;
41 |
42 | private QrGenerator(Builder builder) {
43 | mMargin = builder.mMargin;
44 | mQrSize = builder.mQrSize;
45 | mColor = builder.mColor;
46 | mBgColor = builder.mBgColor;
47 | mContent = builder.mContent;
48 | mEcl = builder.mEcl;
49 | mOverlay = builder.mOverlay;
50 | mOverlaySize = builder.mOverlaySize;
51 | mOverlayAlpha = builder.mOverlayAlpha;
52 | mXfermode = builder.mXFerMode;
53 | mFootNote = builder.mFootNote;
54 | }
55 |
56 | private Bitmap createQRCode()
57 | throws WriterException {
58 | Hashtable hints = new Hashtable<>();
59 |
60 | hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
61 | hints.put(EncodeHintType.ERROR_CORRECTION, mEcl);
62 | hints.put(EncodeHintType.MARGIN, mMargin);
63 |
64 | BitMatrix matrix = new MultiFormatWriter().encode(mContent,
65 | BarcodeFormat.QR_CODE, mQrSize, mQrSize, hints);
66 |
67 | int width = matrix.getWidth();
68 | int height = matrix.getHeight();
69 | int[] pixels = new int[width * height];
70 |
71 | for (int y = 0; y < height; y++) {
72 | for (int x = 0; x < width; x++) {
73 | if (matrix.get(x, y)) {
74 | pixels[y * width + x] = mColor;
75 | } else {
76 | pixels[y * width + x] = mBgColor;
77 | }
78 | }
79 | }
80 |
81 | Bitmap bitmap = Bitmap.createBitmap(width, height,
82 | Bitmap.Config.ARGB_8888);
83 | bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
84 |
85 | //draw overlay
86 | if (mOverlay != null && mOverlaySize > 0) {
87 | Bitmap w = Bitmap.createBitmap(mOverlay);
88 | Bitmap o = w.copy(Bitmap.Config.ARGB_8888, true);
89 | w.recycle();
90 |
91 | int overlayW = o.getWidth();
92 | int overlayH = o.getHeight();
93 |
94 | int scaledH = mOverlaySize * overlayW / overlayH;
95 | int offsetX = (mQrSize - mOverlaySize) / 2;
96 | int offsetY = (mQrSize - scaledH) / 2;
97 |
98 | Paint p = new Paint(Paint.FILTER_BITMAP_FLAG);
99 | p.setAlpha(mOverlayAlpha);
100 | p.setXfermode(new PorterDuffXfermode(mXfermode));
101 |
102 | Canvas canvas = new Canvas(bitmap);
103 | Rect src = new Rect(0, 0, overlayW, overlayH);
104 | Rect dst = new Rect(0, 0, mOverlaySize, scaledH);
105 |
106 | canvas.translate(offsetX, offsetY);
107 | canvas.drawBitmap(o, src, dst, p);
108 | }
109 |
110 | //draw enlarge the canvas and add footnote
111 | if (!TextUtils.isEmpty(mFootNote)) {
112 | Bitmap result = Bitmap.createBitmap(mQrSize, mQrSize * 3 / 2, Bitmap.Config.ARGB_8888);
113 |
114 | TextPaint textPaint = new TextPaint();
115 | textPaint.setColor(mColor);
116 | textPaint.setTextSize(20);
117 | textPaint.setAntiAlias(true);
118 |
119 | StaticLayout mTextLayout = new StaticLayout(
120 | mFootNote,
121 | textPaint,
122 | mQrSize,
123 | Layout.Alignment.ALIGN_CENTER,
124 | 1.4f, 0.2f, false);
125 |
126 | Canvas canvas = new Canvas(result);
127 | canvas.drawColor(mBgColor);
128 | canvas.drawBitmap(bitmap, 0, 0, null);
129 |
130 | canvas.translate(0, mQrSize * 9 / 8);
131 | mTextLayout.draw(canvas);
132 |
133 | return result;
134 | }
135 |
136 | return bitmap;
137 | }
138 |
139 | public static class Builder {
140 | private int mColor = Color.BLACK;
141 | private int mBgColor = Color.WHITE;
142 | private int mMargin = 2;
143 | private int mQrSize;
144 | private int mOverlaySize;
145 | private int mOverlayAlpha = 255;
146 |
147 | private String mContent;
148 | private String mFootNote;
149 | private Bitmap mOverlay;
150 | private ErrorCorrectionLevel mEcl = ErrorCorrectionLevel.L;
151 | private PorterDuff.Mode mXFerMode = PorterDuff.Mode.SRC_OVER;
152 |
153 | public Bitmap encode() throws WriterException {
154 | return new QrGenerator(this).createQRCode();
155 | }
156 |
157 | /**
158 | * @param content qr content
159 | * @return builder instance
160 | */
161 | public Builder content(String content) {
162 | this.mContent = content;
163 | return this;
164 | }
165 |
166 | /**
167 | * @param widthAndHeight qr image size
168 | * @return builder instance
169 | */
170 | public Builder qrSize(int widthAndHeight) {
171 | this.mQrSize = widthAndHeight;
172 | return this;
173 | }
174 |
175 | /**
176 | * Optional
177 | *
178 | * @param margin default is 2.See more about {@link EncodeHintType#MARGIN}
179 | * @return builder instance
180 | */
181 | public Builder margin(int margin) {
182 | this.mMargin = margin;
183 | return this;
184 | }
185 |
186 | /**
187 | * Optional
188 | *
189 | * @param color QRCode foreground color,default is {@link Color#BLACK}
190 | * @return builder instance
191 | */
192 | public Builder color(int color) {
193 | this.mColor = color;
194 | return this;
195 | }
196 |
197 | /**
198 | * Optional
199 | *
200 | * @param context context
201 | * @param color @ColorRes: QRCode foreground color resource,default is {@link Color#BLACK}
202 | * @return builder instance
203 | */
204 | public Builder color(Context context, int color) {
205 | return color(context.getResources().getColor(color));
206 | }
207 |
208 | /**
209 | * Optional
210 | *
211 | * @param bgColor QRCode background color,default is {@link Color#WHITE}
212 | * @return builder instance
213 | */
214 | public Builder bgColor(int bgColor) {
215 | this.mBgColor = bgColor;
216 | return this;
217 | }
218 |
219 | /**
220 | * Optional
221 | *
222 | * @param ecl ErrorCorrectionLevel,default is {@link ErrorCorrectionLevel#L}(=~7%).
223 | * @return builder instance
224 | */
225 | public Builder ecc(ErrorCorrectionLevel ecl) {
226 | this.mEcl = ecl;
227 | return this;
228 | }
229 |
230 | /**
231 | * @param overlay Optional,the overlay on QRCode ,like app icon or something else.
232 | * @return builder instance
233 | */
234 | public Builder overlay(Bitmap overlay) {
235 | this.mOverlay = overlay;
236 | return this;
237 | }
238 |
239 | /**
240 | * Optional
241 | *
242 | * @param context the context to get resources instance.
243 | * @param overlay @DrawableRes:the drawable overlay on QRCode, like app icon or something else.
244 | * @return builder instance
245 | */
246 | public Builder overlay(Context context, int overlay) {
247 | return overlay(BitmapFactory.decodeResource(context.getResources(), overlay));
248 | }
249 |
250 | /**
251 | * Optional
252 | *
253 | * @param overlaySize the overlay icon size
254 | * @return build instance
255 | */
256 | public Builder overlaySize(int overlaySize) {
257 | this.mOverlaySize = overlaySize;
258 | return this;
259 | }
260 |
261 | /**
262 | * Optional
263 | *
264 | * @param alpha the alpha of overlay bitmap, range [0..255],default is 255 (opaque)
265 | * @return build instance
266 | */
267 | public Builder overlayAlpha(int alpha) {
268 | this.mOverlayAlpha = alpha;
269 | return this;
270 | }
271 |
272 | /**
273 | * Optional
274 | *
275 | * @param xfermode xfermode to combine overlay with qr code image, default is {@link android.graphics.PorterDuff.Mode#SRC_OVER}
276 | * @return builder instance
277 | */
278 | public Builder overlayXfermode(PorterDuff.Mode xfermode) {
279 | this.mXFerMode = xfermode;
280 | return this;
281 | }
282 |
283 | public Builder footNote(String note) {
284 | this.mFootNote = note;
285 | return this;
286 | }
287 | }
288 | }
289 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/activity/QrScannerActivity.java:
--------------------------------------------------------------------------------
1 | package me.ydcool.lib.qrmodule.activity;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.content.res.AssetFileDescriptor;
6 | import android.graphics.Bitmap;
7 | import android.media.AudioManager;
8 | import android.media.MediaPlayer;
9 | import android.media.MediaPlayer.OnCompletionListener;
10 | import android.os.Bundle;
11 | import android.os.Handler;
12 | import android.os.Vibrator;
13 | import android.view.SurfaceHolder;
14 | import android.view.SurfaceHolder.Callback;
15 | import android.view.SurfaceView;
16 | import android.view.View;
17 | import android.widget.ImageView;
18 | import android.widget.Toast;
19 |
20 | import com.google.zxing.BarcodeFormat;
21 | import com.google.zxing.Result;
22 |
23 | import java.io.IOException;
24 | import java.util.Vector;
25 |
26 | import me.ydcool.lib.qrmodule.R;
27 | import me.ydcool.lib.qrmodule.camera.CameraManager;
28 | import me.ydcool.lib.qrmodule.decoding.CaptureActivityHandler;
29 | import me.ydcool.lib.qrmodule.decoding.InactivityTimer;
30 | import me.ydcool.lib.qrmodule.view.ViewfinderView;
31 |
32 | /**
33 | * Initial the camera
34 | * override {@link #onQrResult(String)} to handle qr result if you want,
35 | * or we will default do {@link Activity#setResult(int, Intent)}
36 | * with string extras "result" then call{@link Activity#finish()}.
37 | *
38 | * @author Ryan.Tang
39 | * modify: ydcool 2015-11-18 09:48:06 add method {@link #onQrResult(String)}
40 | */
41 | public class QrScannerActivity extends Activity implements Callback {
42 |
43 | private static final float BEEP_VOLUME = 0.10f;
44 | private static final long VIBRATE_DURATION = 200L;
45 | public static final String QR_RESULT_STR = "result";
46 | public static final int QR_REQUEST_CODE = 200;
47 | /**
48 | * When the beep has finished playing, rewind to queue up another one.
49 | */
50 | private final OnCompletionListener beepListener = new OnCompletionListener() {
51 | public void onCompletion(MediaPlayer mediaPlayer) {
52 | mediaPlayer.seekTo(0);
53 | }
54 | };
55 | private CaptureActivityHandler handler;
56 | private ViewfinderView viewfinderView;
57 | private boolean hasSurface;
58 | private Vector decodeFormats;
59 | private String characterSet;
60 | private InactivityTimer inactivityTimer;
61 | private MediaPlayer mediaPlayer;
62 | private boolean playBeep;
63 | private boolean vibrate;
64 |
65 | private boolean isFlashLightOn;
66 | private ImageView mFlashBtn;
67 |
68 | @Override
69 | public void onCreate(Bundle savedInstanceState) {
70 |
71 | // requestWindowFeature(Window.FEATURE_NO_TITLE);
72 |
73 | // getWindow().setFlags(
74 | // WindowManager.LayoutParams.FLAG_FULLSCREEN,
75 | // WindowManager.LayoutParams.FLAG_FULLSCREEN);
76 |
77 | super.onCreate(savedInstanceState);
78 | setContentView(R.layout.activity_qr_scanner);
79 |
80 | if (getActionBar() != null)
81 | getActionBar().hide();
82 |
83 | setUpButtons();
84 | setUpCamera();
85 | }
86 |
87 | private void setUpButtons() {
88 | findViewById(R.id.back_btn).setOnClickListener(new View.OnClickListener() {
89 | @Override
90 | public void onClick(View v) {
91 | QrScannerActivity.this.finish();
92 | }
93 | });
94 |
95 | mFlashBtn = (ImageView) findViewById(R.id.flash_btn);
96 | mFlashBtn.setOnClickListener(new View.OnClickListener() {
97 | @Override
98 | public void onClick(View v) {
99 | if (isFlashLightOn)
100 | CameraManager.get().offLight();
101 | else
102 | CameraManager.get().openLight();
103 |
104 | mFlashBtn.setImageResource(isFlashLightOn
105 | ? R.drawable.ic_flash_off_white_36dp
106 | : R.drawable.ic_flash_on_white_36dp);
107 |
108 | isFlashLightOn = !isFlashLightOn;
109 | }
110 | });
111 | }
112 |
113 | @Override
114 | protected void onResume() {
115 | super.onResume();
116 | setUpSurfaceAndSound();
117 | }
118 |
119 | protected void setUpCamera() {
120 | CameraManager.init(getApplication());
121 | viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
122 | viewfinderView.setVisibility(View.VISIBLE);
123 | hasSurface = false;
124 | inactivityTimer = new InactivityTimer(QrScannerActivity.this);
125 | }
126 |
127 | protected void setUpSurfaceAndSound() {
128 | SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
129 | surfaceView.setVisibility(View.VISIBLE);
130 | SurfaceHolder surfaceHolder = surfaceView.getHolder();
131 | if (hasSurface) {
132 | initCamera(surfaceHolder);
133 | } else {
134 | surfaceHolder.addCallback(QrScannerActivity.this);
135 | surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
136 | }
137 | decodeFormats = null;
138 | characterSet = null;
139 |
140 | playBeep = true;
141 | AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
142 | if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
143 | playBeep = false;
144 | }
145 | initBeepSound();
146 | vibrate = true;
147 | }
148 |
149 | @Override
150 | protected void onPause() {
151 | super.onPause();
152 | if (handler != null) {
153 | handler.quitSynchronously();
154 | handler = null;
155 | }
156 |
157 | if (isFlashLightOn) {
158 | isFlashLightOn = false;
159 | CameraManager.get().offLight();
160 | }
161 |
162 | CameraManager.get().closeDriver();
163 | }
164 |
165 | @Override
166 | protected void onDestroy() {
167 | inactivityTimer.shutdown();
168 | super.onDestroy();
169 | }
170 |
171 | /**
172 | * Handler scan result
173 | *
174 | * @param result qr scan result string.
175 | * @param barcode original qr code
176 | */
177 | public void handleDecode(Result result, Bitmap barcode) {
178 | inactivityTimer.onActivity();
179 | playBeepSoundAndVibrate();
180 |
181 | onQrResult(result.getText());
182 | }
183 |
184 | public void resetScanner() {
185 | if (handler != null)//containue scan
186 | handler.restartPreviewAndDecode();
187 | }
188 |
189 | public void resetScannerDelayed(long millionSeconds) {
190 | mFlashBtn.postDelayed(new Runnable() {
191 | @Override
192 | public void run() {
193 | resetScanner();
194 | }
195 | }, millionSeconds);
196 | }
197 |
198 | /**
199 | * override this to handle qr result if you want,
200 | * or we will default do {@link Activity#setResult(int, Intent)}
201 | * with string extras "result" then call{@link Activity#finish()}.
202 | *
203 | * @param resultString qr scan result string.
204 | */
205 | public void onQrResult(String resultString) {
206 | if (resultString.equals("")) {
207 | Toast.makeText(QrScannerActivity.this, "Scan Result Empty!", Toast.LENGTH_SHORT).show();
208 | this.setResult(RESULT_CANCELED);
209 | } else {
210 | Intent resultIntent = new Intent();
211 | Bundle bundle = new Bundle();
212 | bundle.putString(QR_RESULT_STR, resultString);
213 | resultIntent.putExtras(bundle);
214 | this.setResult(RESULT_OK, resultIntent);
215 | }
216 | QrScannerActivity.this.finish();
217 | }
218 |
219 | private void initCamera(SurfaceHolder surfaceHolder) {
220 | try {
221 | CameraManager.get().openDriver(surfaceHolder);
222 | } catch (IOException ioe) {
223 | ioe.printStackTrace();
224 | return;
225 | } catch (RuntimeException e) {
226 | e.printStackTrace();
227 | return;
228 | }
229 | if (handler == null) {
230 | handler = new CaptureActivityHandler(QrScannerActivity.this, decodeFormats,
231 | characterSet);
232 | }
233 | }
234 |
235 | @Override
236 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
237 | }
238 |
239 | @Override
240 | public void surfaceCreated(SurfaceHolder holder) {
241 | if (!hasSurface) {
242 | hasSurface = true;
243 | initCamera(holder);
244 | }
245 | }
246 |
247 | @Override
248 | public void surfaceDestroyed(SurfaceHolder holder) {
249 | hasSurface = false;
250 | }
251 |
252 | public ViewfinderView getViewfinderView() {
253 | return viewfinderView;
254 | }
255 |
256 | public Handler getHandler() {
257 | return handler;
258 | }
259 |
260 | public void drawViewfinder() {
261 | viewfinderView.drawViewfinder();
262 | }
263 |
264 | private void initBeepSound() {
265 | if (playBeep && mediaPlayer == null) {
266 | // The volume on STREAM_SYSTEM is not adjustable, and users found it
267 | // too loud,
268 | // so we now play on the music stream.
269 | setVolumeControlStream(AudioManager.STREAM_MUSIC);
270 | mediaPlayer = new MediaPlayer();
271 | mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
272 | mediaPlayer.setOnCompletionListener(beepListener);
273 |
274 | AssetFileDescriptor file = getResources().openRawResourceFd(
275 | R.raw.beep);
276 | try {
277 | mediaPlayer.setDataSource(file.getFileDescriptor(),
278 | file.getStartOffset(), file.getLength());
279 | file.close();
280 | mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
281 | mediaPlayer.prepare();
282 | } catch (IOException e) {
283 | mediaPlayer = null;
284 | }
285 | }
286 | }
287 |
288 | private void playBeepSoundAndVibrate() {
289 | if (playBeep && mediaPlayer != null) {
290 | mediaPlayer.start();
291 | }
292 | if (vibrate) {
293 | Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
294 | vibrator.vibrate(VIBRATE_DURATION);
295 | }
296 | }
297 |
298 | }
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/camera/CameraConfigurationManager.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 me.ydcool.lib.qrmodule.camera;
18 |
19 | import android.content.Context;
20 | import android.graphics.Point;
21 | import android.hardware.Camera;
22 | import android.os.Build;
23 | import android.util.Log;
24 | import android.view.Display;
25 | import android.view.WindowManager;
26 |
27 | import java.util.regex.Pattern;
28 |
29 | final class CameraConfigurationManager {
30 |
31 | private static final String TAG = CameraConfigurationManager.class.getSimpleName();
32 |
33 | private static final int TEN_DESIRED_ZOOM = 27;
34 | private static final int DESIRED_SHARPNESS = 30;
35 |
36 | private static final Pattern COMMA_PATTERN = Pattern.compile(",");
37 |
38 | private final Context context;
39 | private Point screenResolution;
40 | private Point cameraResolution;
41 | private int previewFormat;
42 | private String previewFormatString;
43 |
44 | CameraConfigurationManager(Context context) {
45 | this.context = context;
46 | }
47 |
48 | private static Point getCameraResolution(Camera.Parameters parameters, Point screenResolution) {
49 |
50 | String previewSizeValueString = parameters.get("preview-size-values");
51 | // saw this on Xperia
52 | if (previewSizeValueString == null) {
53 | previewSizeValueString = parameters.get("preview-size-value");
54 | }
55 |
56 | Point cameraResolution = null;
57 |
58 | if (previewSizeValueString != null) {
59 | Log.d(TAG, "preview-size-values parameter: " + previewSizeValueString);
60 | cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution);
61 | }
62 |
63 | if (cameraResolution == null) {
64 | // Ensure that the camera resolution is a multiple of 8, as the screen may not be.
65 | cameraResolution = new Point(
66 | (screenResolution.x >> 3) << 3,
67 | (screenResolution.y >> 3) << 3);
68 | }
69 |
70 | return cameraResolution;
71 | }
72 |
73 | private static Point findBestPreviewSizeValue(CharSequence previewSizeValueString, Point screenResolution) {
74 | int bestX = 0;
75 | int bestY = 0;
76 | int diff = Integer.MAX_VALUE;
77 | for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
78 |
79 | previewSize = previewSize.trim();
80 | int dimPosition = previewSize.indexOf('x');
81 | if (dimPosition < 0) {
82 | Log.w(TAG, "Bad preview-size: " + previewSize);
83 | continue;
84 | }
85 |
86 | int newX;
87 | int newY;
88 | try {
89 | newX = Integer.parseInt(previewSize.substring(0, dimPosition));
90 | newY = Integer.parseInt(previewSize.substring(dimPosition + 1));
91 | } catch (NumberFormatException nfe) {
92 | Log.w(TAG, "Bad preview-size: " + previewSize);
93 | continue;
94 | }
95 |
96 | int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);
97 | if (newDiff == 0) {
98 | bestX = newX;
99 | bestY = newY;
100 | break;
101 | } else if (newDiff < diff) {
102 | bestX = newX;
103 | bestY = newY;
104 | diff = newDiff;
105 | }
106 |
107 | }
108 |
109 | if (bestX > 0 && bestY > 0) {
110 | return new Point(bestX, bestY);
111 | }
112 | return null;
113 | }
114 |
115 | private static int findBestMotZoomValue(CharSequence stringValues, int tenDesiredZoom) {
116 | int tenBestValue = 0;
117 | for (String stringValue : COMMA_PATTERN.split(stringValues)) {
118 | stringValue = stringValue.trim();
119 | double value;
120 | try {
121 | value = Double.parseDouble(stringValue);
122 | } catch (NumberFormatException nfe) {
123 | return tenDesiredZoom;
124 | }
125 | int tenValue = (int) (10.0 * value);
126 | if (Math.abs(tenDesiredZoom - value) < Math.abs(tenDesiredZoom - tenBestValue)) {
127 | tenBestValue = tenValue;
128 | }
129 | }
130 | return tenBestValue;
131 | }
132 |
133 | public static int getDesiredSharpness() {
134 | return DESIRED_SHARPNESS;
135 | }
136 |
137 | /**
138 | * Reads, one time, values from the camera that are needed by the app.
139 | */
140 | @SuppressWarnings("SuspiciousNameCombination")
141 | void initFromCameraParameters(Camera camera) {
142 | Camera.Parameters parameters = camera.getParameters();
143 | previewFormat = parameters.getPreviewFormat();
144 | previewFormatString = parameters.get("preview-format");
145 | Log.d(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);
146 | WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
147 | Display display = manager.getDefaultDisplay();
148 | screenResolution = new Point(display.getWidth(), display.getHeight());
149 | // display.getSize(screenResolution);//api > 13
150 | Log.d(TAG, "Screen resolution: " + screenResolution);
151 |
152 | //-- modify by ydcool at 2015-11-18 16:12:15 --
153 | Point screenResolutionForCamera = new Point();
154 | screenResolutionForCamera.x = screenResolution.x;
155 | screenResolutionForCamera.y = screenResolution.y;
156 | // preview size is always something like 480*320, other 320*480
157 | if (screenResolution.x < screenResolution.y) {
158 | screenResolutionForCamera.x = screenResolution.y;
159 | screenResolutionForCamera.y = screenResolution.x;
160 | }
161 |
162 | // cameraResolution = getCameraResolution(parameters, screenResolution);
163 | cameraResolution = getCameraResolution(parameters, screenResolutionForCamera);
164 | //-- end modify --
165 |
166 | Log.d(TAG, "Camera resolution: " + screenResolution);
167 | }
168 |
169 | /**
170 | * Sets the camera up to take preview images which are used for both preview and decoding.
171 | * We detect the preview format here so that buildLuminanceSource() can build an appropriate
172 | * LuminanceSource subclass. In the future we may want to force YUV420SP as it's the smallest,
173 | * and the planar Y can be used for barcode scanning without a copy in some cases.
174 | */
175 | void setDesiredCameraParameters(Camera camera) {
176 | Camera.Parameters parameters = camera.getParameters();
177 | Log.d(TAG, "Setting preview size: " + cameraResolution);
178 | parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
179 | setFlash(parameters);
180 | setZoom(parameters);
181 | //setSharpness(parameters);
182 | //modify here
183 | camera.setDisplayOrientation(90);
184 | camera.setParameters(parameters);
185 | }
186 |
187 | Point getCameraResolution() {
188 | return cameraResolution;
189 | }
190 |
191 | Point getScreenResolution() {
192 | return screenResolution;
193 | }
194 |
195 | int getPreviewFormat() {
196 | return previewFormat;
197 | }
198 |
199 | String getPreviewFormatString() {
200 | return previewFormatString;
201 | }
202 |
203 | private void setFlash(Camera.Parameters parameters) {
204 | // FIXME: This is a hack to turn the flash off on the Samsung Galaxy.
205 | // And this is a hack-hack to work around a different value on the Behold II
206 | // Restrict Behold II check to Cupcake, per Samsung's advice
207 | //if (Build.MODEL.contains("Behold II") &&
208 | // CameraManager.SDK_INT == Build.VERSION_CODES.CUPCAKE) {
209 | if (Build.MODEL.contains("Behold II") && CameraManager.SDK_INT == 3) { // 3 = Cupcake
210 | parameters.set("flash-value", 1);
211 | } else {
212 | parameters.set("flash-value", 2);
213 | }
214 | // This is the standard setting to turn the flash off that all devices should honor.
215 | parameters.set("flash-mode", "off");
216 | }
217 |
218 | private void setZoom(Camera.Parameters parameters) {
219 |
220 | String zoomSupportedString = parameters.get("zoom-supported");
221 | if (zoomSupportedString != null && !Boolean.parseBoolean(zoomSupportedString)) {
222 | return;
223 | }
224 |
225 | int tenDesiredZoom = TEN_DESIRED_ZOOM;
226 |
227 | String maxZoomString = parameters.get("max-zoom");
228 | if (maxZoomString != null) {
229 | try {
230 | int tenMaxZoom = (int) (10.0 * Double.parseDouble(maxZoomString));
231 | if (tenDesiredZoom > tenMaxZoom) {
232 | tenDesiredZoom = tenMaxZoom;
233 | }
234 | } catch (NumberFormatException nfe) {
235 | Log.w(TAG, "Bad max-zoom: " + maxZoomString);
236 | }
237 | }
238 |
239 | String takingPictureZoomMaxString = parameters.get("taking-picture-zoom-max");
240 | if (takingPictureZoomMaxString != null) {
241 | try {
242 | int tenMaxZoom = Integer.parseInt(takingPictureZoomMaxString);
243 | if (tenDesiredZoom > tenMaxZoom) {
244 | tenDesiredZoom = tenMaxZoom;
245 | }
246 | } catch (NumberFormatException nfe) {
247 | Log.w(TAG, "Bad taking-picture-zoom-max: " + takingPictureZoomMaxString);
248 | }
249 | }
250 |
251 | String motZoomValuesString = parameters.get("mot-zoom-values");
252 | if (motZoomValuesString != null) {
253 | tenDesiredZoom = findBestMotZoomValue(motZoomValuesString, tenDesiredZoom);
254 | }
255 |
256 | String motZoomStepString = parameters.get("mot-zoom-step");
257 | if (motZoomStepString != null) {
258 | try {
259 | double motZoomStep = Double.parseDouble(motZoomStepString.trim());
260 | int tenZoomStep = (int) (10.0 * motZoomStep);
261 | if (tenZoomStep > 1) {
262 | tenDesiredZoom -= tenDesiredZoom % tenZoomStep;
263 | }
264 | } catch (NumberFormatException nfe) {
265 | // continue
266 | }
267 | }
268 |
269 | // Set zoom. This helps encourage the user to pull back.
270 | // Some devices like the Behold have a zoom parameter
271 | if (maxZoomString != null || motZoomValuesString != null) {
272 | parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0));
273 | }
274 |
275 | // Most devices, like the Hero, appear to expose this zoom parameter.
276 | // It takes on values like "27" which appears to mean 2.7x zoom
277 | if (takingPictureZoomMaxString != null) {
278 | parameters.set("taking-picture-zoom", tenDesiredZoom);
279 | }
280 | }
281 |
282 | }
283 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------
/demo/src/main/res/layout/activity_generator.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
18 |
19 |
27 |
28 |
34 |
35 |
39 |
40 |
45 |
46 |
52 |
53 |
54 |
55 |
59 |
60 |
65 |
66 |
73 |
74 |
75 |
79 |
80 |
85 |
86 |
93 |
94 |
95 |
98 |
99 |
100 |
105 |
106 |
111 |
112 |
120 |
121 |
129 |
130 |
138 |
139 |
140 |
141 |
144 |
145 |
146 |
151 |
152 |
157 |
158 |
166 |
167 |
175 |
176 |
184 |
185 |
186 |
187 |
190 |
191 |
196 |
197 |
203 |
204 |
209 |
210 |
211 |
212 |
215 |
216 |
221 |
222 |
229 |
230 |
234 |
235 |
240 |
241 |
242 |
243 |
248 |
249 |
254 |
255 |
262 |
263 |
264 |
269 |
270 |
275 |
276 |
284 |
285 |
286 |
291 |
292 |
298 |
299 |
304 |
305 |
306 |
307 |
310 |
311 |
312 |
317 |
318 |
323 |
324 |
330 |
331 |
332 |
333 |
336 |
337 |
338 |
339 |
--------------------------------------------------------------------------------
/qrmodule/src/main/java/me/ydcool/lib/qrmodule/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 |
17 | package me.ydcool.lib.qrmodule.camera;
18 |
19 | import android.content.Context;
20 | import android.graphics.ImageFormat;
21 | import android.graphics.Point;
22 | import android.graphics.Rect;
23 | import android.hardware.Camera;
24 | import android.os.Build;
25 | import android.os.Handler;
26 | import android.util.Log;
27 | import android.view.SurfaceHolder;
28 |
29 | import com.google.zxing.ResultPoint;
30 |
31 | import java.io.IOException;
32 |
33 | /**
34 | * This object wraps the Camera service object and expects to be the only one talking to it. The
35 | * implementation encapsulates the steps needed to take preview-sized images, which are used for
36 | * both preview and decoding.
37 | */
38 | public final class CameraManager {
39 |
40 | static final int SDK_INT; // Later we can use Build.VERSION.SDK_INT
41 | private static final String TAG = CameraManager.class.getSimpleName();
42 | private static final int MIN_FRAME_WIDTH = 480;
43 | private static final int MIN_FRAME_HEIGHT = 360;
44 | private static final int MAX_FRAME_WIDTH = 800;
45 | private static final int MAX_FRAME_HEIGHT = 600;
46 | private static CameraManager cameraManager;
47 |
48 | static {
49 | int sdkInt;
50 | try {
51 | sdkInt = Integer.parseInt(Build.VERSION.SDK);
52 | } catch (NumberFormatException nfe) {
53 | // Just to be safe
54 | sdkInt = 10000;
55 | }
56 | SDK_INT = sdkInt;
57 | }
58 |
59 | private final Context context;
60 | private final CameraConfigurationManager configManager;
61 | private final boolean useOneShotPreviewCallback;
62 | /**
63 | * Preview frames are delivered here, which we pass on to the registered handler. Make sure to
64 | * clear the handler so it will only receive one message.
65 | */
66 | private final PreviewCallback previewCallback;
67 | /**
68 | * Autofocus callbacks arrive here, and are dispatched to the Handler which requested them.
69 | */
70 | private final AutoFocusCallback autoFocusCallback;
71 | private Camera camera;
72 | private Rect framingRect;
73 | private Rect framingRectInPreview;
74 | private boolean initialized;
75 | private boolean previewing;
76 |
77 | private CameraManager(Context context) {
78 |
79 | this.context = context;
80 | this.configManager = new CameraConfigurationManager(context);
81 |
82 | // Camera.setOneShotPreviewCallback() has a race condition in Cupcake, so we use the older
83 | // Camera.setPreviewCallback() on 1.5 and earlier. For Donut and later, we need to use
84 | // the more efficient one shot callback, as the older one can swamp the system and cause it
85 | // to run out of memory. We can't use SDK_INT because it was introduced in the Donut SDK.
86 | //useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.CUPCAKE;
87 | useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > 3; // 3 = Cupcake
88 |
89 | previewCallback = new PreviewCallback(configManager, useOneShotPreviewCallback);
90 | autoFocusCallback = new AutoFocusCallback();
91 | }
92 |
93 | /**
94 | * Initializes this static object with the Context of the calling Activity.
95 | *
96 | * @param context The Activity which wants to use the camera.
97 | */
98 | public static void init(Context context) {
99 | if (cameraManager == null) {
100 | cameraManager = new CameraManager(context);
101 | }
102 | }
103 |
104 | /**
105 | * Gets the CameraManager singleton instance.
106 | *
107 | * @return A reference to the CameraManager singleton.
108 | */
109 | public static CameraManager get() {
110 | return cameraManager;
111 | }
112 |
113 | /**
114 | * Opens the camera driver and initializes the hardware parameters.
115 | *
116 | * @param holder The surface object which the camera will draw preview frames into.
117 | * @throws IOException Indicates the camera driver failed to open.
118 | */
119 | public void openDriver(SurfaceHolder holder) throws IOException {
120 | if (camera == null) {
121 | camera = Camera.open();
122 | if (camera == null) {
123 | throw new IOException();
124 | }
125 | camera.setPreviewDisplay(holder);
126 |
127 | if (!initialized) {
128 | initialized = true;
129 | configManager.initFromCameraParameters(camera);
130 | }
131 | configManager.setDesiredCameraParameters(camera);
132 |
133 | //FIXME
134 | // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
135 | // if (prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false)) {
136 | // FlashlightManager.enableFlashlight();
137 | // }
138 | FlashlightManager.enableFlashlight();
139 | }
140 | }
141 |
142 | /**
143 | * Closes the camera driver if still in use.
144 | */
145 | public void closeDriver() {
146 | if (camera != null) {
147 | FlashlightManager.disableFlashlight();
148 | camera.release();
149 | camera = null;
150 | }
151 | }
152 |
153 | /**
154 | * Asks the camera hardware to begin drawing preview frames to the screen.
155 | */
156 | public void startPreview() {
157 | if (camera != null && !previewing) {
158 | camera.startPreview();
159 | previewing = true;
160 | }
161 | }
162 |
163 | /**
164 | * Tells the camera to stop drawing preview frames.
165 | */
166 | public void stopPreview() {
167 | if (camera != null && previewing) {
168 | if (!useOneShotPreviewCallback) {
169 | camera.setPreviewCallback(null);
170 | }
171 | camera.stopPreview();
172 | previewCallback.setHandler(null, 0);
173 | autoFocusCallback.setHandler(null, 0);
174 | previewing = false;
175 | }
176 | }
177 |
178 | /**
179 | * A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
180 | * in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
181 | * respectively.
182 | *
183 | * @param handler The handler to send the message to.
184 | * @param message The what field of the message to be sent.
185 | */
186 | public void requestPreviewFrame(Handler handler, int message) {
187 | if (camera != null && previewing) {
188 | previewCallback.setHandler(handler, message);
189 | if (useOneShotPreviewCallback) {
190 | camera.setOneShotPreviewCallback(previewCallback);
191 | } else {
192 | camera.setPreviewCallback(previewCallback);
193 | }
194 | }
195 | }
196 |
197 | /**
198 | * Asks the camera hardware to perform an autofocus.
199 | *
200 | * @param handler The Handler to notify when the autofocus completes.
201 | * @param message The message to deliver.
202 | */
203 | public void requestAutoFocus(Handler handler, int message) {
204 | if (camera != null && previewing) {
205 | autoFocusCallback.setHandler(handler, message);
206 | //Log.d(TAG, "Requesting auto-focus callback");
207 | camera.autoFocus(autoFocusCallback);
208 | }
209 | }
210 |
211 | /**
212 | * Calculates the framing rect which the UI should draw to show the user where to place the
213 | * barcode. This target helps with alignment as well as forces the user to hold the device
214 | * far enough away to ensure the image will be in focus.
215 | *
216 | * @return The rectangle to draw on screen in window coordinates.
217 | */
218 | @SuppressWarnings("SuspiciousNameCombination")
219 | public Rect getFramingRect() {
220 | Point screenResolution = configManager.getScreenResolution();
221 | if (framingRect == null) {
222 | if (camera == null) {
223 | return null;
224 | }
225 | int width = screenResolution.x * 3 / 5;
226 | // if (width < MIN_FRAME_WIDTH) {
227 | // width = MIN_FRAME_WIDTH;
228 | // } else if (width > MAX_FRAME_WIDTH) {
229 | // width = MAX_FRAME_WIDTH;
230 | // }
231 | // int height = screenResolution.y * 3 / 4;
232 | // if (height < MIN_FRAME_HEIGHT) {
233 | // height = MIN_FRAME_HEIGHT;
234 | // } else if (height > MAX_FRAME_HEIGHT) {
235 | // height = MAX_FRAME_HEIGHT;
236 | // }
237 | int height = width;//make a square
238 | int leftOffset = (screenResolution.x - width) / 2;
239 | int topOffset = (screenResolution.y - height) / 3;
240 | framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
241 | Log.d(TAG, "Calculated framing rect: " + framingRect);
242 | }
243 | return framingRect;
244 | }
245 |
246 | /**
247 | * Like {@link #getFramingRect} but coordinates are in terms of the preview frame,
248 | * not UI / screen.
249 | *
250 | * @return framing rect in preview
251 | */
252 | public Rect getFramingRectInPreview() {
253 | if (framingRectInPreview == null) {
254 | Rect rect = new Rect(getFramingRect());
255 | Point cameraResolution = configManager.getCameraResolution();
256 | Point screenResolution = configManager.getScreenResolution();
257 | rect.left = rect.left * cameraResolution.y / screenResolution.x;
258 | rect.right = rect.right * cameraResolution.y / screenResolution.x;
259 | rect.top = rect.top * cameraResolution.x / screenResolution.y;
260 | rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;
261 | framingRectInPreview = rect;
262 | }
263 | return framingRectInPreview;
264 | }
265 |
266 | /**
267 | * Converts the result points from still resolution coordinates to screen coordinates.
268 | *
269 | * @param points The points returned by the Reader subclass through Result.getResultPoints().
270 | * @return An array of Points scaled to the size of the framing rect and offset appropriately
271 | * so they can be drawn in screen coordinates.
272 | */
273 |
274 | public Point[] convertResultPoints(ResultPoint[] points) {
275 | Rect frame = getFramingRectInPreview();
276 | int count = points.length;
277 | Point[] output = new Point[count];
278 | for (int x = 0; x < count; x++) {
279 | output[x] = new Point();
280 | output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
281 | output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
282 | }
283 | return output;
284 | }
285 |
286 |
287 | /**
288 | * A factory method to build the appropriate LuminanceSource object based on the format
289 | * of the preview buffers, as described by Camera.Parameters.
290 | *
291 | * @param data A preview frame.
292 | * @param width The width of the image.
293 | * @param height The height of the image.
294 | * @return A PlanarYUVLuminanceSource instance.
295 | */
296 | public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
297 | Rect rect = getFramingRectInPreview();
298 | int previewFormat = configManager.getPreviewFormat();
299 | String previewFormatString = configManager.getPreviewFormatString();
300 | switch (previewFormat) {
301 | // This is the standard Android format which all devices are REQUIRED to support.
302 | // In theory, it's the only one we should ever care about.
303 | case ImageFormat.NV21:
304 | // This format has never been seen in the wild, but is compatible as we only care
305 | // about the Y channel, so allow it.
306 | case ImageFormat.NV16:
307 | return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
308 | rect.width(), rect.height());
309 | default:
310 | // The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
311 | // Fortunately, it too has all the Y data up front, so we can read it.
312 | if ("yuv420p".equals(previewFormatString)) {
313 | return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
314 | rect.width(), rect.height());
315 | }
316 | }
317 | throw new IllegalArgumentException("Unsupported picture format: " +
318 | previewFormat + '/' + previewFormatString);
319 | }
320 |
321 | public void openLight() {
322 | if (camera != null) {
323 | Camera.Parameters parameter = camera.getParameters();
324 | parameter.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
325 | camera.setParameters(parameter);
326 | }
327 | }
328 |
329 | public void offLight() {
330 | if (camera != null) {
331 | Camera.Parameters parameter = camera.getParameters();
332 | parameter.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
333 | camera.setParameters(parameter);
334 | }
335 | }
336 |
337 | public Context getContext() {
338 | return context;
339 | }
340 |
341 | }
342 |
--------------------------------------------------------------------------------