欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[原创] Android 长按识别图中二维码 - Zxing 博客分类: Android androidzxingqrcode 

程序员文章站 2024-03-24 17:15:40
...
前提:
本文使用了 ButterKnife 依赖库

开始环境: Android Studio

在 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();
    }
}