sineverba
sineverba

Reputation: 5172

Android and external USB Barcode Scanner: how catch the enter?

I have an edittext in a form.

I connect a barcode reader USB, seen as a hardware keyboard.

When I scan a barcode, edittext create new line, instead of push the "Send" button.

How I can catch the "Enter" from barcode? Thank you

Upvotes: 0

Views: 2825

Answers (2)

RAKHMATILLA TUGANOV
RAKHMATILLA TUGANOV

Reputation: 21

If you are in an activity use dispatchKeyEvent

import android.os.Bundle
import android.view.KeyEvent
import androidx.appcompat.app.AppCompatActivity

class BarcodeScannerActivity : AppCompatActivity() {

    private var scannedData = ""

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

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (event?.action == KeyEvent.ACTION_DOWN) {
            when (event.keyCode) {
                KeyEvent.KEYCODE_ENTER -> {
                    handleBarcodeScan(scannedData)
                    scannedData = ""
                    return true
                }
                else -> {
                    val keyChar = event.unicodeChar.toChar()
                    scannedData += keyChar
                    return true
                }
            }
        }
        return super.dispatchKeyEvent(event)
    }

    private fun handleBarcodeScan(barcodeData: String) {
        // Process the scanned barcode data
        // You can perform actions such as database lookups, API calls, etc.
        // For this example, we'll just print the barcode data
        println("Scanned barcode: $barcodeData")
    }
}

If you are in Fragment then use setOnKeyListener

import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class BarcodeScannerFragment : Fragment() {

    private var scannedData = ""

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_barcode_scanner, container, false)
        rootView.isFocusableInTouchMode = true
        rootView.requestFocus()
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                when (keyCode) {
                    KeyEvent.KEYCODE_ENTER -> {
                        handleBarcodeScan(scannedData)
                        scannedData = ""
                        return@setOnKeyListener true
                    }
                    else -> {
                        val keyChar = event.unicodeChar.toChar()
                        scannedData += keyChar
                        return@setOnKeyListener true
                    }
                }
            }
            return@setOnKeyListener false
        }
    }

    private fun handleBarcodeScan(barcodeData: String) {
        // Process the scanned barcode data
        // You can perform actions such as database lookups, API calls, etc.
        // For this example, we'll just print the barcode data
        println("Scanned barcode: $barcodeData")
    }
}

This approach captures key events within the fragment's UI, and you need to ensure that the fragment's view has focus for this to work correctly.

Upvotes: 0

djdance
djdance

Reputation: 3209

this is the duplicate from How to integrate barcode scanner with android application? , not the same but maybe help

Important! on android 2.3 you can catch barcode in OnKeyDown event, but in 4.3 your real scanner will press on any focused button, so put the code into dispatchKeyEvent and return true.

Some button still will be focused (selected, pre-pressed, highlighted, only god knows what is it), but press event won't be fired. If anybody knows how to avoid this (except auto moving focus...) tell me

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    //barcode scanner
    int c=event.getUnicodeChar();
    //accept only 0..9 and ENTER
    if ((c>=48 && c<=57) || c==10){
        if (event.getAction()==0) {
            if (c >= 48 && c <= 57)
                barcode += "" + (char) c;
            else {
                if (!barcode.equals("")) {
                    final String b = barcode;
                    barcode = "";
                    new Thread(new Runnable() {
                        public void run() {
                            checkBarcode(b); 
                            //there you get a string and compare it or store etc
                        }
                    }).start();
                }
            }
        }
        return true;
    }
    return super.dispatchKeyEvent(event);
}

Upvotes: 1

Related Questions