二维码的生成和扫描

孔磊
2023-12-01

1.所需依赖

implementation 'cn.yipianfengye.android:zxing-library:2.2'

2.所需权限

<!--网络权限-->
    <uses-permission android:name="android.permission.INTERNET"/>
    <!--震动权限-->
    <uses-permission android:name="android.permission.VIBRATE"/>
    <!--摄像头权限-->
    <uses-permission android:name="android.permission.CAMERA"/>
    <!--自动聚焦权限-->
    <uses-feature android:name="android.hardware.camera.autofocus"/>

3.需要手动写的请求权限

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.VIBRATE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
        }

4. 创建app并初始化

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //初始化Zxing库
        ZXingLibrary.initDisplayOpinion(this);
    }
}

       初始化完成在清单文件里加入app

5. 二维码的生成

//生成二维码
    private void create() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.love);
        Bitmap code = CodeUtils.createImage("杨浩鑫不会的二维码", 400, 400, bitmap);
        iv.setImageBitmap(code);
    }

6.扫描二维码

//扫描二维码
    private void sao() {
        Intent intent = new Intent(this, CaptureActivity.class);
        startActivityForResult(intent,101);
    }
//处理结果
 @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 101 && resultCode == Activity.RESULT_OK &&data != null){
            Bundle bundle = data.getExtras();
            if(bundle == null){
                return;
            }
            if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS){
                String string = bundle.getString(CodeUtils.RESULT_STRING);
                Toast.makeText(this, "扫描结果"+string, Toast.LENGTH_SHORT).show();
            }
        }
    }

最后声明 两个Button按钮和一个ImageView  一个按钮操作生成二维码,一个按钮操作扫描,ImageView为显示二维码所用

 类似资料: