Integrating the ZXing library directly into my Android application

后端 未结 17 1619
[愿得一人]
[愿得一人] 2020-11-22 04:35

I\'m writing this in mere desperation :) I\'ve been assigned to make a standalone barcode scanner (as a proof of concept) to an Android 1.6 phone.

For this i\'ve dis

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 05:18

    Since some of the answers are outdated, I would like to provide my own -

    To integrate ZXing library into your Android app as suggested by their Wiki, you need to add 2 Java files to your project:

    • IntentIntegrator.java
    • IntentResult.java

    Then in Android Studio add the following line to build.gradle file:

    dependencies {
        ....
        compile 'com.google.zxing:core:3.2.1'
    }
    

    Or if still using Eclipse with ADT-plugin add core.jar file to the libs subdirectory of your project (here fullscreen Windows and fullscreen Mac):

    Windows screenshot

    Finally add this code to your MainActivity.java:

    public void scanQRCode(View v) {
        IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
        integrator.initiateScan(IntentIntegrator.QR_CODE_TYPES);
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        IntentResult result = 
            IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        if (result != null) {
            String contents = result.getContents();
            if (contents != null) {
                showDialog(R.string.result_succeeded, result.toString());
            } else {
                showDialog(R.string.result_failed,
                    getString(R.string.result_failed_why));
            }
        }
    }
    
    private void showDialog(int title, CharSequence message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.ok_button, null);
        builder.show();
    }
    

    The resulting app will ask to install and start Barcode Scanner app by ZXing (which will return to your app automatically after scanning):

    Barcode Scanner app

    Additionally, if you would like to build and run the ZXing Test app as inspiration for your own app:

    ZXing Test app

    Then you need 4 Java files from GitHub:

    • BenchmarkActivity.java
    • BenchmarkAsyncTask.java
    • BenchmarkItem.java
    • ZXingTestActivity.java

    And 3 Jar files from Maven repository:

    • core.jar
    • android-core.jar
    • android-integration.jar

    (You can build the Jar files yourself with mvn package - if your check out ZXing from GitHub and install ant and maven tools at your computer).

    Note: if your project does not recognize the Jar files, you might need to up the Java version in the Project Properties:

    properties screenshot

提交回复
热议问题