Android實現掃描二維碼

weixin_34208283發表於2017-03-13

PS:有的朋友可能會掃描出現問題,如果報異常“SecurityException”同時讀者又確切的把相機許可權加上去了,這時候請檢查,你的裝置是不是6.0,或者6.0以後,這裡面牽扯到一個動態許可權的問題。需要增加一段程式碼。在文章裡我註釋掉了,開啟註釋即可。
這個是安卓6.0 以後的需要呼叫某些裝置的時候需要動態增加許可權,是安全問題提升的一個表現

開發工具:AS

作為伸手黨,首先感謝開源庫的作者GuoJinyu,有興趣的可以前去學習,

1.新增依賴

compile 'com.acker:simplezxing:1.2'

2.在需要的地方呼叫:(這裡需要注意,如果你的設別API很高,在6.0,可能需要動態申請許可權)

if (Build.VERSION.SDK_INT >= 23) {
        int checkCallPhonePermission = 
ContextCompat.checkSelfPermission(ZXingActivity.this,Manifest.permission.CAMERA);
        if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(ZXingActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
        return;
        } else {
        startCamera();
        }
        } else {
        startCamera();
}

startCamera() 方法如下:

private void startCamera() {
        Intent intent = new Intent(this, CaptureActivity.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean(CaptureActivity.KEY_NEED_BEEP, CaptureActivity.VALUE_BEEP);
        bundle.putBoolean(CaptureActivity.KEY_NEED_VIBRATION, CaptureActivity.VALUE_VIBRATION);
        bundle.putBoolean(CaptureActivity.KEY_NEED_EXPOSURE, CaptureActivity.VALUE_NO_EXPOSURE);
        bundle.putByte(CaptureActivity.KEY_FLASHLIGHT_MODE, CaptureActivity.VALUE_FLASHLIGHT_OFF);
        bundle.putByte(CaptureActivity.KEY_ORIENTATION_MODE, CaptureActivity.VALUE_ORIENTATION_AUTO);
        intent.putExtra(CaptureActivity.EXTRA_SETTING_BUNDLE, bundle);
        startActivityForResult(intent, CaptureActivity.REQ_CODE);
    }

3.重寫onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String scanInfo;
        switch (requestCode) {
            case CaptureActivity.REQ_CODE:
                scanInfo = data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT);
                switch (resultCode) {
                    case RESULT_OK:
                        Log.d(TAG,scanInfo);  //or do sth
                        mTextView.setText(scanInfo);
                        break;
                    case RESULT_CANCELED:
                        if (data != null) {
                            // for some reason camera is not working correctly
                            Log.d(TAG,data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        }
                        break;
                }
                break;
        }
    }

對"第3步"onActivityResult 方法中 data 解釋:

data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT); //這行用來接收二維碼資訊

startCaptureActivityForResult()方法的配置資訊在bundle引數描述的很詳細,可以參閱

最後別忘了許可權問題

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

相關文章