1. 程式人生 > >Android開發中的二維碼掃描功能

Android開發中的二維碼掃描功能

Android開發中的二維碼掃描

現在Android開發中使用二維碼掃描功能越來越多,本篇部落格具體講一下其使用方法:

  • 新增依賴
  • 在自己的Activity或者Fragment中使用新增關於掃描的連結
  • 新增二維碼掃描的相關Activity
  • 對掃描資料進行解析
  • 在返回Activity中做相應處理

新增依賴

首先在gradle中新增所要依賴的jar包,在github中有一個評價比較高的開源庫,zxing。 [ 傳送門 ]

     repositories {
        jcenter()
    }
dependencies {
     compile 'com.google.zxing:core:3.3.0'
compile 'com.journeyapps:zxing-android-embedded:3.3.0' }

具體的版本則根據最新的版本使用。

新增掃描連結

一般情況下,我們在自己的Activity中通過一個點選事件來進入二維碼掃描頁面,在這裡,我就用一個Button來表示:

      Button button = (Button) findViewById(R.id.erweima);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
public void onClick(View v) { customScan(); } }); public void customScan() { //Activity中的初始化方式 new IntentIntegrator(this) .setOrientationLocked(false) .setCaptureActivity(CustomScanActivity.class) // 設定自定義的activity是CustomActivity
.initiateScan(); // 初始化掃描 //Fragment中的初始化方式 IntentIntegrator.forSupportFragment(this) .setOrientationLocked(false) .setCaptureActivity(CustomScanActivity.class) .initiateScan();

可以看出,在Activity中與在Fragment中兩者的初始化方式是有很大的區別的。

二維碼介面

檢視

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.customscan.CustomScanActivity">


    <com.journeyapps.barcodescanner.DecoratedBarcodeView
        android:id="@+id/dbv_custom"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:zxing_framing_rect_height="250dp"
        app:zxing_framing_rect_width="250dp"
        app:zxing_preview_scaling_strategy="fitXY"
        app:zxing_use_texture_view="true">
    </com.journeyapps.barcodescanner.DecoratedBarcodeView>
    <Button
        android:id="@+id/btn_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:textColor="#fff"
        android:text="開啟閃光燈"
        android:layout_marginBottom="10dp"
        android:background="@drawable/button"/>
</RelativeLayout>

程式碼

public class CustomScanActivity extends AppCompatActivity implements DecoratedBarcodeView.TorchListener{
    private DecoratedBarcodeView mDBV;
    private CaptureManager captureManager;
    private boolean isLightOn = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_scan);

        Button swichLight = (Button) findViewById(R.id.btn_switch);
        mDBV = (DecoratedBarcodeView) findViewById(R.id.dbv_custom);
        mDBV.setTorchListener(this);
        swichLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isLightOn){
                    mDBV.setTorchOff();
                }else{
                    mDBV.setTorchOn();
                }
            }
        });

        if(!hasFlash()) {
            swichLight.setVisibility(View.GONE);
        }

        //重要程式碼,初始化捕獲
        captureManager = new CaptureManager(this,mDBV);
        captureManager.initializeFromIntent(getIntent(),savedInstanceState);
        captureManager.decode();
    }

    @Override
    public void onTorchOn() {
        Toast.makeText(this,"torch on",Toast.LENGTH_LONG).show();
        isLightOn = true;
    }

    @Override
    public void onTorchOff() {
        Toast.makeText(this,"torch off",Toast.LENGTH_LONG).show();
        isLightOn = false;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        captureManager.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        captureManager.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        captureManager.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        captureManager.onDestroy();
    }

    private boolean hasFlash() {
        return getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

}

這裡就是二維碼Activity中的操作了, 在這裡,我加了一個開啟閃光燈的按鈕,這個功能也在越來越多的專案中用到了。

回撥方法

接下來就是在MainActivity中的回調了,我們在Activity中的onActivityResult方法中進行回撥。

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
            IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (intentResult != null) {
                if (intentResult.getContents() == null) {
                    Toast.makeText(this, "內容為空", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "掃描成功", Toast.LENGTH_LONG).show();
                    String ScanResult = intentResult.getContents();
                    Toast.makeText(this, ScanResult, Toast.LENGTH_LONG).show();
                }
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        }

好了,到這裡掃描二維碼的功能就可以實現了,但是在這個中我們可以看到,在掃描介面最下方有一行字提示將二維碼放到掃描框中,但是這裡字太小,也特別靠底部,所以我們來更改一下他的型別,但是在自己寫的二維碼掃描介面上沒有這個設定,那麼它應該在哪裡更改呢,就在這裡:

這裡寫圖片描述

開打這個資原始檔,更改它的TextView就可以改變下面那一行字的位置以及大小了。

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <com.journeyapps.barcodescanner.BarcodeView
        android:id="@+id/zxing_barcode_surface"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.journeyapps.barcodescanner.ViewfinderView
        android:id="@+id/zxing_viewfinder_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:id="@+id/zxing_status_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:background="@color/zxing_transparent"
        android:text="@string/zxing_msg_default_status"
        android:textColor="@color/zxing_status_text"
        android:textSize="18sp"
        android:layout_marginBottom="100dp"/>
</merge>

以上就是關於二維碼掃描功能的全部介紹了,希望可以幫到大家。