Android - QR 生成器 API

标签 android kotlin qr-code zxing

我正在尝试从我的应用程序中生成一些 QR,但我看到有很多类型的 QR,例如联系人、Wi-Fi 等。我想知道是否有免费的 API 或库来实现这一点,我已经看到一些网站已经在生成它,所以我想知道对于 Android 是否有任何 API 或库可供使用。
我检查过的内容:
http://goqr.me/api
Zxing
但我不确定是否有一个功能可以说我想要一个联系人的二维码,这样我就可以添加它的所有信息。

最佳答案

使用 ZXing 生成二维码
在您的应用程序级别添加以下 ZXing 核心依赖项 build.gradle文件。

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'
第一步:设置条形码处理器回调。
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() {}
} 
第二步:设置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
    }
}
第三步:添加 SurfaceView到您的布局来托管您的CameraSource .
<SurfaceView
    android:id="@+id/surfaceView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" /> 
第四步:创建回调以启动和停止 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
}
第五步:将所有内容与生命周期方法链接在一起。
// 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()
}

关于Android - QR 生成器 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64443791/

相关文章:

android - 如何在我的 React-Native 开发环境中指定 Metro Bundler IP 地址?

java - 在 Android 中使用图像检测裁剪人脸

java - ListView.CHOICE_MODE_SINGLE Unresolved 引用

ios - 处理从 QR 码读取的数据

javascript - 解码二维码

android - 在 MaterialDrawer Android 的 expandableitem 中更新徽章

android - 将 AS 项目迁移到 IDEA 时,无法将 com.android.build.gradle.internal.model.ApiVersionImpl 转换为 java.lang.Integer

android - 如何在使用导航组件导航时保存 fragment 状态

kotlin - 如何在 Kotlin 中继承 MutableList?

java - 如何使 InputStream 跳过以 '#' 开头的行?