android二维码扫描 Zxing 3.X 使用与开启闪关灯

来源:互联网 发布:陕西网络广告公司 编辑:程序博客网 时间:2024/05/14 12:24

android二维码扫描 Zxing 3.X 使用与开启闪关灯

在Android studio中我们使用新版的二维码扫描要方便了很多只需要以下几个步骤:

1. 在app的build.gradle中添加

compile 'com.journeyapps:zxing-android-embedded:3.4.0'

2. 在需要调用的二维码界面的地方添加以下代码就可以调用扫描界面了。

IntentIntegrator integrator = new IntentIntegrator(activity);integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);//integrator.setCameraId(0);  // Use a specific camera of the deviceintegrator.setBeepEnabled(true);integrator.setOrientationLocked(false);integrator.setBarcodeImageEnabled(true);integrator.setPrompt("");integrator.setCaptureActivity(ScanActivity.class);integrator.initiateScan();
  • integrator.setCaptureActivity(ScanActivity.class);为设置自定义界面。
  • integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);为设置支持的格式,比如二维码一维码的格式等,这里设置的是全格式支持。
public class ScanActivity extends Activity {    private CaptureManager capture;    private DecoratedBarcodeView barcodeScannerView;    private boolean flag = true;    private String photo_path;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_scan);        barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.viewfinder_view);        capture = new CaptureManager(this, barcodeScannerView);        capture.initializeFromIntent(getIntent(), savedInstanceState);        capture.decode();        setClick();    }    @Override    protected void onResume() {        super.onResume();        capture.onResume();    }    @Override    protected void onPause() {        super.onPause();        capture.onPause();    }    @Override    protected void onDestroy() {        super.onDestroy();        capture.onDestroy();    }    @Override    protected void onSaveInstanceState(Bundle outState) {        super.onSaveInstanceState(outState);        capture.onSaveInstanceState(outState);    }    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {        capture.onRequestPermissionsResult(requestCode, permissions, grantResults);    }    @Override    public boolean onKeyDown(int keyCode, KeyEvent event) {        return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);    }    private void setClick(){        findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                finish();            }        });        findViewById(R.id.btn_torch).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                light();            }        });        findViewById(R.id.mo_scanner_photo).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent innerIntent = new Intent(); // "android.intent.action.GET_CONTENT"                if (Build.VERSION.SDK_INT < 19) {                    innerIntent.setAction(Intent.ACTION_GET_CONTENT);                } else {                    // innerIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);  这个方法报 图片地址 空指针;使用下面的方法                    innerIntent.setAction(Intent.ACTION_PICK);                }                innerIntent.setType("image/*");                Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");                startActivityForResult(wrapperIntent, REQUEST_CODE);            }        });    }    @RequiresApi(api = Build.VERSION_CODES.KITKAT)    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (resultCode == RESULT_OK) {            switch (requestCode) {                case REQUEST_CODE:                    String[] proj = { MediaStore.Images.Media.DATA };                    // 获取选中图片的路径                    Cursor cursor = getContentResolver().query(data.getData(),                            proj, null, null, null);                    if (cursor.moveToFirst()) {                        int column_index = cursor                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);                        photo_path = cursor.getString(column_index);                        if (photo_path == null) {                            photo_path = ImagePathUtil.getPath(getApplicationContext(),                                    data.getData());                        }                    }                    cursor.close();                    new Thread(new Runnable() {                        @Override                        public void run() {                            Result result = scanningImage(photo_path);                            // String result = decode(photo_path);                            if (result == null) {                                Looper.prepare();                                Toast.makeText(ScanActivity.this, R.string.image_code_error, Toast.LENGTH_SHORT)                                        .show();                                Looper.loop();                            } else {                                // 数据返回                                String recode = recode(result.toString());                                Intent data = new Intent();                                data.putExtra("recodeResult", recode);                                setResult(ScanManger.RECODERESULT, data);                                finish();                            }                        }                    }).start();                    break;            }        }    }    protected Result scanningImage(String path) {        if (TextUtils.isEmpty(path)) {            return null;        }        // DecodeHintType 和EncodeHintType        Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();        hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 设置二维码内容的编码        BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true; // 先获取原大小        Bitmap scanBitmap = BitmapFactory.decodeFile(path, options);        options.inJustDecodeBounds = false; // 获取新的大小        int sampleSize = (int) (options.outHeight / (float) 200);        if (sampleSize <= 0)            sampleSize = 1;        options.inSampleSize = sampleSize;        scanBitmap = BitmapFactory.decodeFile(path, options);        int width = scanBitmap.getWidth();        int height = scanBitmap.getHeight();        int[] pixels = new int[width * height];        scanBitmap.getPixels(pixels, 0, width, 0, 0, width, height);        RGBLuminanceSource source = new RGBLuminanceSource(width,height,pixels);        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));        QRCodeReader reader = new QRCodeReader();        try {            return reader.decode(bitmap1, hints);        } catch (NotFoundException | ChecksumException | FormatException e) {            e.printStackTrace();        }        return null;    }    private String recode(String str) {        String formart = "";        try {            boolean ISO = Charset.forName("ISO-8859-1").newEncoder()                    .canEncode(str);            if (ISO) {                formart = new String(str.getBytes("ISO-8859-1"), "GB2312");            } else {                formart = str;            }        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return formart;    }    protected void light() {        if (flag) {            flag = false;            // 开闪光灯            barcodeScannerView.setTorchOn();        } else {            flag = true;            // 关闪光灯            barcodeScannerView.setTorchOff();        }    }}

自定义布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <FrameLayout        android:id="@+id/fl_zxing"        android:layout_width="match_parent"        android:layout_height="match_parent" >        <SurfaceView            android:id="@+id/preview_view"            android:layout_width="fill_parent"            android:layout_height="fill_parent" />        <com.journeyapps.barcodescanner.DecoratedBarcodeView            android:id="@+id/viewfinder_view"            android:layout_width="fill_parent"            android:layout_height="fill_parent" />        <RelativeLayout            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_marginBottom="50dp"            android:background="@color/transparent" >            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_alignParentBottom="true"                android:layout_centerHorizontal="true"                android:layout_marginBottom="12dp"                android:text="@string/msg_default_status"                android:textColor="@color/white"                android:textSize="12sp" />        </RelativeLayout>        <RelativeLayout            android:layout_width="match_parent"            android:layout_height="45dp"            android:background="@color/zxing_transparent"            android:visibility="visible" >            <Button                android:id="@+id/btn_back"                android:layout_width="70dp"                android:layout_height="match_parent"                android:background="@null"                android:text="返回"                android:textColor="@color/white"                android:textSize="18sp" />            <ImageView                android:padding="3dp"                android:id="@+id/mo_scanner_photo"                android:layout_width="40dp"                android:layout_height="20dp"                android:layout_marginTop="8dp"                android:layout_centerInParent="true"                android:src="@mipmap/mo_scanner_album" />            <Button                android:id="@+id/btn_torch"                android:layout_width="70dp"                android:layout_height="match_parent"                android:layout_alignParentRight="true"                android:background="@null"                android:text="开灯"                android:textColor="@color/white"                android:textSize="18sp" />        </RelativeLayout>    </FrameLayout></LinearLayout>

大家可以直接复制过去修改使用。

3. 获取结果
在onActivityResult中获取扫描的结果

@Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);        if(result != null) {            if(result.getContents() == null) {                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();            } else {                String re = result.getContents();            }        } else {            super.onActivityResult(requestCode, resultCode, data);        }    }
  • String re = result.getContents();为获得的二维码结果。

对于开关闪关灯
在网上很多说怎么开关闪光灯的文章,但是那些文章都太老了,说要改源码加方法之类的。而新版的zxing已经做了很好的封装了。这里我们只需要调用下面的方法就可以开关闪光灯。

在自定义界面中调用DecoratedBarcodeView的setTorchOn()和setTorchOff()即可开关。

barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.viewfinder_view);protected void light() {        if (flag) {            flag = false;            // 开闪光灯            barcodeScannerView.setTorchOn();        } else {            flag = true;            // 关闪光灯            barcodeScannerView.setTorchOff();        }    }
0 0
原创粉丝点击