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"/>