SoFunction
Updated on 2025-03-01

Android device Bluetooth connection scan gun to get scan content

The bar scanner can mainly scan barcodes and QR codes, etc., and the scanning speed is much faster than that of mobile phone scanning devices. This article briefly introduces android to monitor Bluetooth connection through Bluetooth. When the scanning device is connected, the scanning device is equivalent to an external keyboard. By monitoring the input event of the external keyboard, the scanned content is obtained.
Other reference documents:Get scan content of scan code gun for Android device

1. Bluetooth pairing

Turn on the system settings, Bluetooth pairing scanner, generally the scanner instructions are written, after the pairing is completed, it is displayed that it is connected

Configure permissions

Configure the permissions required for Bluetooth connection

<!-- Bluetooth -->
    <uses-permission android:name="" />
    <uses-permission android:name=".BLUETOOTH_ADMIN" />
    <uses-permission android:name=".ACCESS_FINE_LOCATION" />
    <uses-permission android:name=".ACCESS_COARSE_LOCATION" />

3. Obtain device information and determine whether to connect

The device type returned by the Bluetooth device here is

/**
      * Is the scanner connected?
      * @return
      */
    public boolean hasScanGun() {
        if (mBluetoothAdapter == null) {
            return false;
        }
        Set<BluetoothDevice> blueDevices = ();
        if (blueDevices == null || () <= 0) {
            return false;
        }
        for (Iterator<BluetoothDevice> iterator = (); (); ) {
            BluetoothDevice bluetoothDevice = ();

            if (().getMajorDeviceClass() == ) {

                mDeviceName = ();
                return isInputDeviceExist(mDeviceName);
            }
        }
        return false;
    }
    /**
      * Whether the input device exists
      * @param deviceName
      * @return
      */
    private boolean isInputDeviceExist(String deviceName) {
        int[] deviceIds = ();

        for (int id : deviceIds) {
            if ((id).getName().equals(deviceName)) {
                return true;
            }
        }
        return false;
}

4. Build the scan gun resolution class ScanGunKeyEventHelper

Use a scanner to parse the class to use a scanner to call analysisKeyEvent(KeyEvent event) in the related class to pass in the listening event. When parsing the corresponding event, the input content is obtained, and the OnScanSuccessListener interface callback is returned.

/**
  * Scan code gun event analysis class by chen
  */
public class ScanGunKeyEventHelper {
    private final static long MESSAGE_DELAY = 500;//Depend 500ms, determine whether the scanning code is completed.    private StringBuffer mStringBufferResult;//Scan the QR code content    private boolean mCaps;//Case difference    private final Handler mHandler;
    private final BluetoothAdapter mBluetoothAdapter;
    private final Runnable mScanningFishedRunnable;
    private OnScanSuccessListener mOnScanSuccessListener;
    private String mDeviceName;

    public ScanGunKeyEventHelper(OnScanSuccessListener onScanSuccessListener) {
        mOnScanSuccessListener = onScanSuccessListener ;
        //Get system Bluetooth adapter management class        mBluetoothAdapter = ();
//        BluetoothDevice printerdevice = ("ssss");
//        BluetoothSocket btSocket = ("ssss");
        mStringBufferResult = new StringBuffer();
        mHandler = new Handler();
        mScanningFishedRunnable = new Runnable() {
            @Override
            public void run() {
                performScanSuccess();
            }
        };
    }
    /**
      * Return the result after the code is successfully scanned
      */
    private void performScanSuccess() {
        String barcode = ();
        if (mOnScanSuccessListener != null)
            (barcode);
        (0);
    }
    /**
      * Analysis of QR code scan gun incident
      * @param event
      */
    public void analysisKeyEvent(KeyEvent event) {
        int keyCode = ();
        //Case judgment of letters        checkLetterStatus(event);
        if (() == KeyEvent.ACTION_DOWN) {

            char aChar = getInputCode(event);;

            if (aChar != 0) {
                (aChar);
            }
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                //If it is the Enter key, return directly                (mScanningFishedRunnable);
                (mScanningFishedRunnable);
            } else {
                //Delay post, if there are other events within 500ms                (mScanningFishedRunnable);
                (mScanningFishedRunnable, MESSAGE_DELAY);
            }

        }
    }

    //Check shift key    private void checkLetterStatus(KeyEvent event) {
        int keyCode = ();
        if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT || keyCode == KeyEvent.KEYCODE_SHIFT_LEFT) {
            if (() == KeyEvent.ACTION_DOWN) {
                //Press shift key to indicate capitalization                mCaps = true;
            } else {
                //Release shift key to lowercase                mCaps = false;
            }
        }
    }
    //Get scanned content    private char getInputCode(KeyEvent event) {
        int keyCode = ();
        char aChar;
        if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) {
            //letter            aChar = (char) ((mCaps ? 'A' : 'a') + keyCode - KeyEvent.KEYCODE_A);
        } else if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
            //number            aChar = (char) ('0' + keyCode - KeyEvent.KEYCODE_0);
        } else {
            //Other symbols            switch (keyCode) {
                case KeyEvent.KEYCODE_PERIOD:
                    aChar = '.';
                    break;
                case KeyEvent.KEYCODE_MINUS:
                    aChar = mCaps ? '_' : '-';
                    break;
                case KeyEvent.KEYCODE_SLASH:
                    aChar = '/';
                    break;
                case KeyEvent.KEYCODE_BACKSLASH:
                    aChar = mCaps ? '|' : '\\';
                    break;
                default:
                    aChar = 0;
                    break;
            }
        }
        return aChar;
    }

    public interface OnScanSuccessListener {
        void onScanSuccess(String barcode);
    }

    public void onDestroy() {
        (mScanningFishedRunnable);
        mOnScanSuccessListener = null;
    }
    // Some mobile phones such as Samsung cannot use this method//    private void hasScanGun() {
//        Configuration cfg = getResources().getConfiguration();
//        return  != Configuration.KEYBOARD_NOKEYS;
//    }
    /**
      * Is the scanner connected?
      * @return
      */
    public boolean hasScanGun() {
        if (mBluetoothAdapter == null) {
            return false;
        }
        Set<BluetoothDevice> blueDevices = ();
        if (blueDevices == null || () <= 0) {
            return false;
        }
        for (Iterator<BluetoothDevice> iterator = (); (); ) {
            BluetoothDevice bluetoothDevice = ();

            if (().getMajorDeviceClass() == ) {

                mDeviceName = ();
                return isInputDeviceExist(mDeviceName);
            }
        }
        return false;
    }
    /**
      * Whether the input device exists
      * @param deviceName
      * @return
      */
    private boolean isInputDeviceExist(String deviceName) {
        int[] deviceIds = ();

        for (int id : deviceIds) {
            if ((id).getName().equals(deviceName)) {
                return true;
            }
        }
        return false;
    }
    /**
      * Is it a QR code scan gun event (the name obtained by some models KeyEvent is incorrect)
      * @param event
      * @return
      */
    @Deprecated
    public boolean isScanGunEvent(KeyEvent event) {
        return ().getName().equals(mDeviceName);
}


    /**
      * Check whether Bluetooth is on
      */
    public int checkBluetoothValid() {

        if(mBluetoothAdapter == null) {//Your device does not have Bluetooth function!            return 1;
        }

        if(!()) {//The Bluetooth device is not turned on, please enable this function and try again!            return 2;
        }
        return 3;//Bluetooth works normally    }


}

5. Use parsing class ScanGunKeyEventHelper in Activity

Rewrite the dispatchKeyEvent method in the Activity to intercept the Key event.

  /**
      * Intercept the key press event. Send to ScanGunKeyEventHelper
      *
      * @param event
      * @return
      */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if ((event)) {
            (event);
            return true;
        }
        return (event);
    }

Get the scan result callback. For detailed code, please check TestScanner

/**
  * @author Wu JianCheng
  * @date on 2018/12/18 14:44
  * Test Bluetooth connection scanner function
  */
public class BleAct extends Activity implements  {

    ...
    
    /**
      * Scan result callback
      * @param barcode
      */
    @Override
    public void onScanSuccess(String barcode) {
        showToast(barcode);
    }
    
    ...

}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.