[原创] Android 长按识别图中二维码 - Zxing

前提:

本文使用了ButterKnife依赖库

开始环境:AndroidStudio

在Module文件夹下的build.gradle文件中追加zxing依赖:

compile 'com.google.zxing:core:3.3.0'

之后添加图片长按事件(此处使用了ButterKnife的注解),并实现识别二维码的功能:

@OnLongClick({R.id.imageView})
public boolean btnLongClick(final ImageView iv) {
    Logger.info(TAG, "Long click on image");

    new AlertDialog.Builder(getActivity())
            .setPositiveButton(R.string.recognize_qr_code, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    progressBar.setVisibility(View.VISIBLE);

                    Bitmap obmp = ((BitmapDrawable) (iv.getDrawable())).getBitmap();
                    int width = obmp.getWidth();
                    int height = obmp.getHeight();
                    int[] data = new int[width * height];
                    obmp.getPixels(data, 0, width, 0, 0, width, height);
                    RGBLuminanceSource source = new RGBLuminanceSource(width, height, data);
                    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

                    new QrCodeAsyncTask().execute(bitmap);
                }
            }).show();

    return true;
}

class QrCodeAsyncTask extends AsyncTask<BinaryBitmap, Void, Result> {

    @Override
    protected Result doInBackground(BinaryBitmap... params) {
        QRCodeReader reader = new QRCodeReader();
        Result result = null;
        try {
            result = reader.decode(params[0]);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onPostExecute(Result result) {
        super.onPostExecute(result);
        progressBar.setVisibility(View.GONE);

        String text = result.getText();
        Logger.info(TAG, "QR CODE: " + text);
        Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
    }
}

相关推荐