Android

在 Android (Kotlin) 中使用华为 ML Kit

2022-08-26  本文已影响0人  安安_660c

介绍

在本文中,我们可以学习如何使用华为ML Kit银行卡识别功能来识别银行卡。银行卡识别服务可识别摄像机流中15度角偏移范围内的银行卡,并提取卡号有效期等关键信息。该服务与身份证识别服务相结合,提供身份验证、银行卡号输入等一系列热门功能,让用户操作变得前所未有的简单。

用例

银行卡识别服务可以提取原始结构中的银行卡信息,这对于金融服务中的身份验证和电子商务应用中的银行卡绑定支付非常有用。例如,以往在绑定银行卡进行在线支付时,用户必须手动输入卡号。很容易出错。目前,通过银行卡识别服务,银行卡号的输入实现自动化,快速准确,大大提升了用户体验。

预防措施

当前版本仅支持基于摄像头流的银行卡识别。

要求

  1. 任何操作系统(MacOS、Linux 和 Windows)。

  2. 必须有 HMS 4.0.0.300 或更高版本的华为手机。

  3. 必须有安装了 Android Studio、Jdk 1.8、SDK 平台 26 和 Gradle 4.6 及更高版本的笔记本电脑或台式机。

  4. 最低 API 级别 21 是必需的。

  5. 需要 EMUI 9.0.0 及更高版本的设备。

如何集成 HMS 依赖

注意:项目名称取决于用户创建的名称。

maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.5.0.300'
// ML Kit Bank Card Recognition
implementation 'com.huawei.hms:ml-computer-card-bcr:3.5.0.300'
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

让我们走向发展

我在 Android Studio 上创建了一个空活动项目,让我们开始编码。

在MainActivity.kt我们可以找到按钮的业务逻辑。

class MainActivity : AppCompatActivity() {

    var startCapture: Button? = null
    var permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)

    private val callback: MLBcrCapture.Callback = object : MLBcrCapture.Callback {
        override fun onSuccess(bankCardResult: MLBcrCaptureResult) {
            // Processing for successful recognition.
            val stringBuffer = StringBuffer()
            stringBuffer.append("Issuer Name :" + bankCardResult.issuer)
            stringBuffer.append("\n")
            stringBuffer.append("Organization Name :" + bankCardResult.organization)
            stringBuffer.append("\n")
            stringBuffer.append("Card Number :" + bankCardResult.number)
            stringBuffer.append("\n")
            stringBuffer.append("Expiery Date :" + bankCardResult.expire)
            stringBuffer.append("\n")
            stringBuffer.append("Card Type :" + bankCardResult.type)
            stringBuffer.append("\n")
            createDialog(stringBuffer.toString())
        }
        override fun onCanceled() {
            // Processing for recognition request cancellation.
            Toast.makeText(this@MainActivity, "Cancelled", Toast.LENGTH_SHORT).show()
        }
        // Callback method used when no text is recognized or a system exception occurs during recognition.
        // retCode: result code.
        // bitmap: bank card image that fails to be recognized.
        override fun onFailure(retCode: Int, bitmap: Bitmap) {
            // Processing logic for recognition failure.
            Toast.makeText(this@MainActivity, retCode.toString(), Toast.LENGTH_SHORT).show()
        }
        override fun onDenied() {
            // Processing for recognition request deny scenarios, for example, the camera is unavailable.
            Toast.makeText(this@MainActivity, "Denied", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        requestPermission()
        startCapture = findViewById(R.id.start_capture)
        startCapture!!.setOnClickListener(View.OnClickListener { startCaptureActivity(callback) })

    }

    private fun startCaptureActivity(callback: MLBcrCapture.Callback) {
        val config = MLBcrCaptureConfig.Factory() // Set the expected result type of bank card recognition.
                // MLBcrCaptureConfig.RESULT_NUM_ONLY: Recognize only the bank card number.
                // MLBcrCaptureConfig.RESULT_SIMPLE: Recognize only the bank card number and validity period.
                // MLBcrCaptureConfig.ALL_RESULT: Recognize information such as the bank card number, validity period, issuing bank, card organization, and card type.
                .setResultType(MLBcrCaptureConfig.RESULT_ALL) // Set the recognition screen display orientation.
                // MLBcrCaptureConfig.ORIENTATION_AUTO: adaptive mode. The display orientation is determined by the physical sensor.
                // MLBcrCaptureConfig.ORIENTATION_LANDSCAPE: landscape mode.
                // MLBcrCaptureConfig.ORIENTATION_PORTRAIT: portrait mode.
                .setOrientation(MLBcrCaptureConfig.ORIENTATION_AUTO)
                .create()
        val bankCapture = MLBcrCaptureFactory.getInstance().getBcrCapture(config)
        bankCapture.captureFrame(this, callback)
    }

    private fun requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, permissions, 111)
        }
    }

    @SuppressLint("InflateParams")
    private fun createDialog(retrievedText: String) {
        val wm = this@MainActivity.getSystemService(WINDOW_SERVICE) as WindowManager
        val width = wm.defaultDisplay.width
        val height = wm.defaultDisplay.height
        val dialog = Dialog(this@MainActivity, R.style.MyDialog)
        val view: View = LayoutInflater.from(this@MainActivity).inflate(R.layout.layout_for_dialog, null)
        (view.findViewById<View>(R.id.retrieved_information) as TextView).text = retrievedText
        val params = dialog.window!!.attributes
        params.width = WindowManager.LayoutParams.MATCH_PARENT
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        dialog.setContentView(view)
        dialog.window!!.setGravity(Gravity.CENTER)
        dialog.window!!.setWindowAnimations(R.style.MyDialog)
        dialog.show()
    }


}

在activity_main.xml我们可以创建 UI 屏幕。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/start_capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Capture"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

对话框的布局是layout_for_dialog.xml。

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/retrieved_information"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:scrollbars="vertical"
            android:textColor="@color/black" />
    </LinearLayout>

</ScrollView>

演示

技巧和窍门

  1. 确保您已经注册为华为开发者。

  2. 将 minSDK 版本设置为 21 或更高版本,否则会出现 AndriodManifest 合并问题。

  3. 确保您已将 agconnect-services.json 文件添加到 app 文件夹。

  4. 确保您已添加 SHA-256 指纹,但不会失败。

  5. 确保正确添加了所有依赖项。

结论

在本文中,我们学习了如何使用华为ML Kit的银行卡识别功能来识别银行卡。银行卡识别服务可识别摄像机流中15度角偏移范围内的银行卡,并提取卡号和有效期等 关键信息。该服务与身份证识别服务相结合,提供身份验证、银行卡号输入等一系列热门功能,让用户操作变得前所未有的简单。

我希望你已经阅读了这篇文章。如果觉得有帮助,请点赞和评论。

文章来源:https://dev.to/hmscommunity/capture-the-bank-cards-using-bank-card-recognition-feature-by-huawei-ml-kit-in-android-kotlin-544k

上一篇下一篇

猜你喜欢

热点阅读