这是我看的大神的github:https://github.com/yipianfengye/android-zxingLibrary
先在build中添加
implementation 'cn.yipianfengye.android:zxing-library:2.2'
在配置里添加
创建一个App类
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
ZXingLibrary.initDisplayOpinion(this);
}
在MainActivity里
//输入内容
private EditText et;
private ImageView scanIv;
点击扫描二维码按钮
public void xmewm(View view) {
Intent intent = new Intent(this, CaptureActivity.class);
startActivityForResult(intent,0);
}
回调一个onActivityResult方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//处理扫描结果(在界面上显示)
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String result = bundle.getString(CodeUtils.RESULT_STRING);
resultTextView.setText(result);
Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
}
}
生成二维码
public void scewm(View view) {
String content = et.getText().toString();
//输入内容不为空
if (TextUtils.isEmpty(content)) {
Toast.makeText(this, "请输入关键字", Toast.LENGTH_SHORT).show();
return;
}
Bitmap mBitmap = CodeUtils.createImage(content, 400, 400, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
scanIv.setImageBitmap(mBitmap);
}
添加权限
if(Build.VERSION.SDK_INT >= 23){//判断当前系统的版本
if(ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.CAMERA},CAMERA_OK);
}else {
dtewmsc();//扫描二维码
}
}
回调的方法
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case CAMERA_OK:
if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
//这里已经获取到了摄像头的权限,想干嘛干嘛了可以
dtewmsc();//扫描二维码
}else {
//这里是拒绝给APP摄像头权限,给个提示什么的说明一下都可以。
Toast.makeText(MainActivity.this,"请手动打开相机权限",Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}