使用 ZXing 生成二维码
在您的应用级别build.gradle 文件中添加以下ZXing 核心依赖项。
implementation 'com.google.zxing:core:3.4.0'
生成 512x512 像素 WiFi QR 码的示例代码。您可以在 ImageView 中设置生成的位图。
fun getQrCodeBitmap(ssid: String, password: String): Bitmap {
val size = 512 //pixels
val qrCodeContent = "WIFI:S:$ssid;T:WPA;P:$password;;"
val hints = hashMapOf<EncodeHintType, Int>().also { it[EncodeHintType.MARGIN] = 1 } // Make the QR code buffer border narrower
val bits = QRCodeWriter().encode(qrCodeContent, BarcodeFormat.QR_CODE, size, size)
return Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565).also {
for (x in 0 until size) {
for (y in 0 until size) {
it.setPixel(x, y, if (bits[x, y]) Color.BLACK else Color.WHITE)
}
}
}
}
要生成其他类型的二维码,例如 SMS、VCard 等,您可以查看这个有用的ZXing Wiki。
使用 Google Mobile Vision API 扫描二维码
将以下 GMS 依赖项添加到您的应用级别 build.gradle。
implementation 'com.google.android.gms:play-services-vision:20.1.2'
第 1 步:设置条码处理器回调。
private val processor = object : Detector.Processor<Barcode> {
override fun receiveDetections(detections: Detector.Detections<Barcode>?) {
detections?.apply {
if (detectedItems.isNotEmpty()) {
val qr = detectedItems.valueAt(0)
// Parses the WiFi format for you and gives the field values directly
// Similarly you can do qr.sms for SMS QR code etc.
qr.wifi?.let {
Log.d(TAG, "SSID: ${it.ssid}, Password: ${it.password}")
}
}
}
}
override fun release() {}
}
第 2 步: 使用条形码处理器回调设置 BardcodeDetector,并将其添加到 CameraSource,如下所示。不要忘记在运行时检查 Manifest.permission.CAMERA 并将其添加到您的 AndroidManifest.xml。
private fun setupCameraView() {
if (ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
BarcodeDetector.Builder(requireContext()).setBarcodeFormats(QR_CODE).build().apply {
setProcessor(processor)
if (!isOperational) {
Log.d(TAG, "Native QR detector dependencies not available!")
return
}
cameraSource = CameraSource.Builder(requireContext(), this).setAutoFocusEnabled(true)
.setFacing(CameraSource.CAMERA_FACING_BACK).build()
}
} else {
// Request camers permission from user
// Add <uses-permission android:name="android.permission.CAMERA" /> to AndroidManifest.xml
}
}
第 3 步:将SurfaceView 添加到您的布局中以托管您的CameraSource。
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
第 4 步:创建回调以在创建/销毁表面时启动和停止 CameraSource。
private val callback = object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
// Ideally, you should check the condition somewhere
// before inflating the layout which contains the SurfaceView
if (isPlayServicesAvailable(requireActivity()))
cameraSource?.start(holder)
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
cameraSource?.stop()
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { }
}
// Helper method to check if Google Play Services are up to-date on the phone
fun isPlayServicesAvailable(activity: Activity): Boolean {
val code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(applicationContext)
if (code != ConnectionResult.SUCCESS) {
GoogleApiAvailability.getInstance().getErrorDialog(activity, code, code).show()
return false
}
return true
}
第 5 步:将所有内容与生命周期方法链接在一起。
// Create camera source and attach surface view callback to surface holder
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_camera_sheet, container, false).also {
setupCamera()
it.surfaceView.holder.addCallback(callback)
}
}
// Free up camera source resources
override fun onDestroy() {
super.onDestroy()
cameraSource?.release()
}