Как прочитать код 39 с помощью zxing в Android?

Я использую zxing в своем приложении для Android для чтения QR_CODE и штрих-кодов. Мое приложение не может прочитать код CODE_39 с помощью zxing. Я использую следующий код в методе CaptureActivity OnResume:

Intent intent = getIntent();
        String action = intent == null ? null : intent.getAction();
        String dataString = intent == null ? null : intent.getDataString();
        if (intent != null && action != null) {
            if (action.equals(Intents.Scan.ACTION)) {
                 //Scan the formats the intent requested, and return the
                 //result
                 //to the calling activity.
                source = Source.NATIVE_APP_INTENT;
                decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);

            } else if (dataString != null
                    && dataString.contains(PRODUCT_SEARCH_URL_PREFIX)
                    && dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
                // Scan only products and send the result to mobile Product
                // Search.
                source = Source.PRODUCT_SEARCH_LINK;
                sourceUrl = dataString;
                decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
            } else if (dataString != null
                    && dataString.startsWith(ZXING_URL)) {
                // Scan formats requested in query string (all formats if
                // none
                // specified).
                // If a return URL is specified, send the results there.
                // Otherwise, handle it ourselves.
                source = Source.ZXING_LINK;
                sourceUrl = dataString;
                Uri inputUri = Uri.parse(sourceUrl);
                returnUrlTemplate = inputUri
                        .getQueryParameter(RETURN_URL_PARAM);
                decodeFormats = DecodeFormatManager
                        .parseDecodeFormats(inputUri);
            } else {
                // Scan all formats and handle the results ourselves
                // (launched
                // from Home).
                source = Source.NONE;
                decodeFormats = null;
                }

            characterSet = intent
                    .getStringExtra(Intents.Scan.CHARACTER_SET);

Пожалуйста, помогите мне решить эту проблему. Заранее спасибо.


person Ehsan Anjum    schedule 21.12.2015    source источник


Ответы (1)


Если вы используете Android Studio, добавьте эти зависимости:

compile 'me.dm7.barcodescanner:zxing:1.8.3'
compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
compile 'com.google.zxing:core:3.2.0'

Zxing Автоматически принимает тип кода при сканировании

integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES) 

Здесь учитываются все типы кодов по умолчанию

Если вам нужен конкретный QR, просто

integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);

Используйте следующий код-

import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class YourActivity extends Activity {


//Barcode Scanning
private ZXingScannerView mScannerView;


// This is your click listener
public void checkBarcode(View v) {
    try {
        IntentIntegrator integrator = new IntentIntegrator(GateEntryActivity.this);
        integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
        integrator.setPrompt("Scan a barcode");
        integrator.setCameraId(0);  // Use a specific camera of the device
        integrator.setBeepEnabled(false);
        integrator.initiateScan();
        //start the scanning activity from the com.google.zxing.client.android.SCAN intent
        // Programmatically initialize the scanner view
        // setContentView(mScannerView);
    } catch (ActivityNotFoundException anfe) {
        //on catch, show the download dialog
        showDialog(GateEntryActivity.this, "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
    }
}


//alert dialog for downloadDialog
private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
    AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
    downloadDialog.setTitle(title);
    downloadDialog.setMessage(message);
    downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
            Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
                act.startActivity(intent);
            } catch (ActivityNotFoundException anfe) {

            }
        }
    });
    downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
        }
    });
    return downloadDialog.show();
}

//on ActivityResult method
@Override
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 {
        Log.d("MainActivity", "Weird");
        // This is important, otherwise the result will not be passed to the fragment
        super.onActivityResult(requestCode, resultCode, data);
    }
}

}

person Ajinkya    schedule 21.12.2015
comment
Я использую core.jar. У меня нет класса IntentIntegrator в core.jar. - person Ehsan Anjum; 21.12.2015
comment
Используйте эту зависимость, если вы используете Android Studio 1) скомпилируйте 'me.dm7.barcodescanner:zxing:1.8.3' 2) скомпилируйте 'com.journeyapps:zxing-android-embedded:3.0.2@aar' 3) скомпилируйте 'com .google.zxing:ядро:3.2.0' - person Ajinkya; 21.12.2015
comment
Я пытаюсь добавить упомянутые зависимости, но получаю эту ошибку: Не удалось разрешить: com.google.zxing:core:3.2.0 - person Ehsan Anjum; 21.12.2015
comment
Я хочу использовать сканер zxing code_39 в своем приложении. Позволяет ли IntentIntegrator использовать zxing в моем собственном приложении или просит установить сканер zxing? - person Ehsan Anjum; 21.12.2015
comment
На самом деле, я использовал его, и он отлично работает без загрузки какого-либо вспомогательного приложения. - person Ajinkya; 21.12.2015