说明:这里使用的是zxing,目前还有在更新维护,如果对速度要求高可以使用zbar,不过zbar没有更新维护了
1、gradle添加依赖
implementation 'cn.yipianfengye.android:zxing-library:2.2'
2、添加权限
<!-- 获取手机相机的权限 --> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.VIBRATE" />
3、xml文件添加按钮
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开启相机扫描" android:id="@+id/btn"/>
4、修改Activity文件
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //隐藏系统默认的标题 val actionBar = supportActionBar actionBar?.hide() //初始化相机权限 ZXingLibrary.initDisplayOpinion(this) btn.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View) { //先判断手机版本是否在6.0以上,如果在6.0以上则需要动态申请权限 if (Build.VERSION.SDK_INT > 22) { if (ContextCompat.checkSelfPermission( this@MainActivity, Manifest.permission.CAMERA ) != PackageManager.PERMISSION_GRANTED ) { //先判断有没有权限 ,没有就在这里进行权限的申请 ActivityCompat.requestPermissions( this@MainActivity, arrayOf(Manifest.permission.CAMERA), 1 ) } else { //已经获取到摄像头权限,执行自定义操作 val intent = Intent(this@MainActivity, CaptureActivity::class.java) startActivityForResult(intent, 1) } } else { //系统版本在6.0之下,不需要动态获取权限。 val intent = Intent(this@MainActivity, CaptureActivity::class.java) startActivityForResult(intent, 1) } } }) } //获取手机相机权限 override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == 1) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { val intent = Intent(this, CaptureActivity::class.java) startActivityForResult(intent, 1) } else { Toast.makeText(this@MainActivity, "请打开相机权限", Toast.LENGTH_SHORT).show() } } } //处理扫描结果 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { if (data != null) { val bundle = data.extras ?: return if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) { //获取到扫描结果 val result = bundle.getString(CodeUtils.RESULT_STRING) if (result != null) { Log.d("res:", result) } } } } }