Android Kotlin – how to capture input data from external barcode scanner/reader

I just bought a handheld bluetooth barcode scanner to test with my Android project which is written in Kotlin. The scanner can read both 1D and 2D (linear barcode and QR code). Since the barcode scanner is detected as a keyboard, in order to implement the scanning function we can use dispatchKeyEvent method as follow:

var barcode = ""

override fun dispatchKeyEvent(event: KeyEvent): Boolean {
    val dispatchFirst = super.dispatchKeyEvent(event)

    if(event.action == KeyEvent.ACTION_UP) {
        val pressedKey = event.unicodeChar.toChar()
        Log.d("PRESS_KEY", "PressedKey=${pressedKey}")
        barcode += pressedKey.toString()

        if (event.keyCode == KeyEvent.KEYCODE_ENTER) {
            
            Log.d("MyEditText", "onKey input=${barcode}")

            val textView: TextView = findViewById<TextView>(R.id.textview_scan)
            textView.text = ""
            textView.text = barcode

            Toast.makeText(applicationContext, "onKey keyCode=${barcode}", Toast.LENGTH_LONG)
                .show()
            barcode = ""
        }
    }
    return dispatchFirst
}

Leave a Reply

Your email address will not be published. Required fields are marked *