1. 程式人生 > >android studio 使用zxing實現掃碼功能

android studio 使用zxing實現掃碼功能

1、新增依賴

在專案的build.gradle新增:maven { url 'https://jitpack.io' }

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

在app的build.gradle 新增:

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support:support-vector-drawable:26.1.0'
    implementation 'com.github.yuzhiqiang1993:zxing:2.0.0'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    /*新增依賴*/
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support:support-vector-drawable:26.1.0'
    implementation 'com.github.yuzhiqiang1993:zxing:2.0.0'

}

在AndroidMainfest申請相機許可權

<uses-permission android:name="android.permission.CAMERA"/>

 

 

2、好可以使用了

佈局介面就是一個button和一個顯示掃碼結果的Edittext,程式碼就不貼了,圖如下:

呼叫掃碼功能程式碼如下:

button的響應事件:其中REQUEST_CODE_SCAN=0,就是一個請求的標誌。

getPrimission():android6.0以上需要動態申請許可權

scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //android6.0以上需要動態申請相機等許可權,
                getPrimission();

                //啟動掃碼
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);//REQUEST_CODE_SCAN=0
            }
        });

掃碼返回後填充EditView,倆常量REQUEST_CODE_SCAN =0; RESULT_OK=-1

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 掃描二維碼/條碼回傳
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {//RESULT_OK=-1
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                result.setText(content);
            }
        }
    }

申請許可權的函式:其中android.permission.CAMERA表示相機許可權com.zhengyuan.learningqrscan表示包名,需要改成自己專案的包名

//動態申請許可權
    private void getPrimission() {
        PackageManager pm = getPackageManager();
        boolean permission = (PackageManager.PERMISSION_GRANTED ==
                pm.checkPermission("android.permission.CAMERA", "com.zhengyuan.learningqrscan"));
        if (permission) {
            //"有這個許可權"
            Toast.makeText(MainActivity.this, "有許可權", Toast.LENGTH_SHORT).show();
        } else {
            //"木有這個許可權"
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 15);
            }
        }
    }

點選button的執行效果如下

其中還能呼叫閃光燈,相簿,震動等效果