Integrate ZXing in Android Studio

六月ゝ 毕业季﹏ 提交于 2019-11-26 06:13:47

问题


I\'ll start explaining all the steps I have done and in the end what is the problem.

  1. Download ZXing-2.2 https://code.google.com/p/zxing/downloads/list
  2. Extrac all in zxing-2.2.
  3. Download and install Apache Ant http://www.youtube.com/watch?v=XJmndRfb1TU
  4. With the use of Windows Commandline (Run->CMD) navigate to the extracted directory
  5. In the commandline window - Type \'ant -f core/build.xml\' press enter and let Apache work it\'s magic

At this moment is like Integrating the ZXing library directly into my Android application

But Wooops, \"Buildfile: core\\build.xml does not exists! Build failed. ok. 6. Importing ZXing - missing core/build.xml

Now yes, i have my core.jar.

  1. Open Android Studio, File -> Import Project -> Select /android/ in /zxing-2.2/ -> Create project from existing sources -> Project name: andoid -> Source files for... all checked Next -> Libraries (cant do nothing) Next -> Modules (android checked) Next -> SDK 1.7 Next -> Finish

With Project Open -> Build -> Rebuild project

100 errors 19 warnings

File -> project Structure -> Libraries -> Add -> Java -> Select core.jar that i create before and OK -> Library \'core\' will be added to the selected modules. (android) OK -> And OK in the Project Structure Dialog.

Build -> Rebuild Project

15 errors 20 warnings

All errors are error: constant expression required and I see Error in Switch cases of ZXing project in android I change all switchs for if elses.

0 errors 20 warnings

Ok, now continue:

File -> New project -> zxing_demo Next -> Next -> Blank Activity Next -> Finish

In new project -> File -> Import module -> Search and select /android/ OK -> Create module from existing sources Next -> Next -> Next -> Next -> Finish

Now I can see in the explorer /android/ /zging_demoProject/ and External Libraries

Now i change my code tu scan QR

AndroidManifest.xml

<?xml version=\"1.0\" encoding=\"utf-8\"?>
<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"
package=\"com.example.zxing_demo\"
android:versionCode=\"1\"
android:versionName=\"1.0\" >

<uses-sdk
    android:minSdkVersion=\"7\"
    android:targetSdkVersion=\"16\" />
<uses-permission android:name=\"android.permission.CAMERA\"/>
<uses-feature android:name=\"android.hardware.camera\" />
<uses-feature
    android:name=\"android.hardware.camera.autofocus\"
    android:required=\"false\" />
<uses-feature
    android:name=\"android.hardware.touchscreen\"
    android:required=\"false\" />
<application
    android:allowBackup=\"true\"
    android:icon=\"@drawable/ic_launcher\"
    android:label=\"@string/app_name\"
    android:theme=\"@style/AppTheme\" >
    <activity
        android:name=\"com.example.zxing_demo.MainActivity\"
        android:label=\"@string/app_name\" >
        <intent-filter>
            <action android:name=\"android.intent.action.MAIN\" />

            <category android:name=\"android.intent.category.LAUNCHER\" />
        </intent-filter>
    </activity>
    <activity
        android:clearTaskOnLaunch=\"true\"
        android:stateNotNeeded=\"true\"
        android:configChanges=\"orientation|keyboardHidden\"
        android:name=\"com.google.zxing.client.android.CaptureActivity\"
        android:screenOrientation=\"landscape\"
        android:theme=\"@android:style/Theme.NoTitleBar.Fullscreen\"
        android:windowSoftInputMode=\"stateAlwaysHidden\" >
        <intent-filter >
            <action android:name=\"android.intent.action.MAIN\" />
            <category android:name=\"android.intent.category.DEFAULT\" />
        </intent-filter>
        <intent-filter >
            <action android:name=\"com.google.zxing.client.android.SCAN\" />
            <category android:name=\"android.intent.category.DEFAULT\" />
        </intent-filter>
    </activity>
</application>

MainActivity.java

package com.example.zxing_demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(\"com.google.zxing.client.android.SCAN\");
    intent.putExtra(\"SCAN_MODE\", \"QR_CODE_MODE\");
    startActivityForResult(intent, 0);
}


public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String contents = intent.getStringExtra(\"SCAN_RESULT\");
            String format = intent.getStringExtra(\"SCAN_RESULT_FORMAT\");
            // Handle successful scan
        } else if (resultCode == RESULT_CANCELED) {
            // Handle cancel
        }
    }
}

}

Now test, Run -> Debug

And CRASH.

Logcat

08-31 02:58:28.085  20665-20665/com.example.zxing_demo E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.zxing_demo/com.google.zxing.client.android.CaptureActivity}: java.lang.ClassNotFoundException: com.google.zxing.client.android.CaptureActivity
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
    at android.app.ActivityThread.access$600(ActivityThread.java:127)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4448)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.ClassNotFoundException: com.google.zxing.client.android.CaptureActivity
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
    ... 11 more

I can see in AndroidManifest.xml in this line

android:name=\"com.google.zxing.client.android.CaptureActivity\"

\"CaptureActivity\" in red and the error say: Cannot resolve symbol \'CaptureActivity\'

File -> Project Structure -> Modules -> zxing_demo -> Dependencies -> Add -> Module dependency -> android OK -> Apply and OK

Now CaptureActivity looks good

Debug again

08-31 03:06:58.513  21740-21740/com.example.zxing_demo E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.zxing_demo/com.google.zxing.client.android.CaptureActivity}: java.lang.ClassNotFoundException: com.google.zxing.client.android.CaptureActivity
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
    at android.app.ActivityThread.access$600(ActivityThread.java:127)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4448)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.ClassNotFoundException: com.google.zxing.client.android.CaptureActivity
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
    ... 11 more

I think I will use the application and intents, but now I want do this work, if someone now whats happen tell me please.


回答1:


I was integrating ZXING into an Android application and there were no good sources for the input all over, I will give you a hint on what worked for me - because it turned out to be very easy.

There is a real handy git repository that provides the zxing android library project as an AAR archive.

  • https://github.com/journeyapps/zxing-android-embedded

All you have to do is add this to your build.gradle

repositories {
    jcenter()
}

dependencies {
    implementation 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
    implementation 'com.google.zxing:core:3.2.0'
}

and Gradle does all the magic to compile the code and makes it accessible in your app.

To start the Scanner afterwards, use this class/method: From the Activity:

new IntentIntegrator(this).initiateScan(); // `this` is the current Activity

From a Fragment:

IntentIntegrator.forFragment(this).initiateScan(); // `this` is the current Fragment
// If you're using the support library, use IntentIntegrator.forSupportFragment(this) instead.

There are several customizing options:

IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0);  // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();

They have a sample-project and are providing several integration examples:

  • AnyOrientationCaptureActivity
  • ContinuousCaptureActivity
  • CustomScannerActivity
  • ToolbarCaptureActivity

If you already visited the link you going to see that I just copy&pasted the code from the git README. If not, go there to get some more insight and code examples.




回答2:


buttion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new com.google.zxing.integration.android.IntentIntegrator(Fragment.this).initiateScan();
            }
        });

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Log.d("MainActivity", "Scanned");
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
        }
    }



dependencies {
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    compile 'com.google.zxing:core:3.2.1'
    compile 'com.android.support:appcompat-v7:23.1.0'
}



回答3:


Anybody facing the same issues, follow the simple steps:

Import the project android from downloaded zxing-master zip file using option Import project (Eclipse ADT, Gradle, etc.) and add the dollowing 2 lines of codes in your app level build.gradle file and and you are ready to run.

So simple, yahh...

dependencies {
        // https://mvnrepository.com/artifact/com.google.zxing/core
        compile group: 'com.google.zxing', name: 'core', version: '3.2.1'
        // https://mvnrepository.com/artifact/com.google.zxing/android-core
        compile group: 'com.google.zxing', name: 'android-core', version: '3.2.0'

    }

You can always find latest version core and android core from below links:

https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1 https://mvnrepository.com/artifact/com.google.zxing/android-core/3.2.0

UPDATE (29.05.2019)

Add these dependencies instead:

dependencies {
    implementation 'com.google.zxing:core:3.4.0'
    implementation 'com.google.zxing:android-core:3.3.0'
}



回答4:


this tutorial help me to integrate to android studio: http://wahidgazzah.olympe.in/integrating-zxing-in-your-android-app-as-standalone-scanner/ if down try THIS

just add to AndroidManifest.xml

<activity
         android:name="com.google.zxing.client.android.CaptureActivity"
         android:configChanges="orientation|keyboardHidden"
         android:screenOrientation="landscape"
         android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
         android:windowSoftInputMode="stateAlwaysHidden" >
         <intent-filter>
             <action android:name="com.google.zxing.client.android.SCAN" />
             <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
     </activity>

Hope this help!.



来源:https://stackoverflow.com/questions/18543668/integrate-zxing-in-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!