Android设备蓝牙连接扫描枪获取扫描内容

 更新时间:2021年09月28日 15:27:34   作者:weixin_40283969  
这篇文章主要为大家详细介绍了Android设备蓝牙连接扫描枪获取扫描内容,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

条形扫描枪主要可以扫描条形码和二维码等,扫描速度比手机扫描设备快得多,本文简单介绍android 通过蓝牙监听蓝牙连接,当扫描设备连接完成后,扫描设备相当于外接键盘,通过监听外接键盘输入事件,获取扫描出的内容。
其他参照文档:Android设备获取扫码枪扫描内容

1.蓝牙配对

打开系统设置,蓝牙配对扫描枪, 一般扫描枪说明书都有写,配对完成后,显示已连接

2.AndroidManifest中配置权限

在中配置蓝牙连接所需要的权限

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

3.获取设备信息,判断是否连接

这里蓝牙设备返回的设备类型是BluetoothClass.Device.Major.PERIPHERAL

/**
     * 扫描枪是否连接
     * @return
     */
    public boolean hasScanGun() {
        if (mBluetoothAdapter == null) {
            return false;
        }
        Set<BluetoothDevice> blueDevices = mBluetoothAdapter.getBondedDevices();
        if (blueDevices == null || blueDevices.size() <= 0) {
            return false;
        }
        for (Iterator<BluetoothDevice> iterator = blueDevices.iterator(); iterator.hasNext(); ) {
            BluetoothDevice bluetoothDevice = iterator.next();

            if (bluetoothDevice.getBluetoothClass().getMajorDeviceClass() == BluetoothClass.Device.Major.PERIPHERAL) {

                mDeviceName = bluetoothDevice.getName();
                return isInputDeviceExist(mDeviceName);
            }
        }
        return false;
    }
    /**
     * 输入设备是否存在
     * @param deviceName
     * @return
     */
    private boolean isInputDeviceExist(String deviceName) {
        int[] deviceIds = InputDevice.getDeviceIds();

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

4.构建扫描枪解析类ScanGunKeyEventHelper

使用扫描枪解析类需要在相关类中调用 analysisKeyEvent(KeyEvent event) ,传入监听事件,当解析相对应事件获得输入内容,通过OnScanSuccessListener 接口回调返回

/**
 * 扫码枪事件解析类 by chen
 */
public class ScanGunKeyEventHelper {
    private final static long MESSAGE_DELAY = 500;//延迟500ms,判断扫码是否完成。
    private StringBuffer mStringBufferResult;//扫码内容
    private boolean mCaps;//大小写区分
    private final Handler mHandler;
    private final BluetoothAdapter mBluetoothAdapter;
    private final Runnable mScanningFishedRunnable;
    private OnScanSuccessListener mOnScanSuccessListener;
    private String mDeviceName;

    public ScanGunKeyEventHelper(OnScanSuccessListener onScanSuccessListener) {
        mOnScanSuccessListener = onScanSuccessListener ;
        //获取系统蓝牙适配器管理类
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//        BluetoothDevice printerdevice = mBluetoothAdapter.getRemoteDevice("ssss");
//        BluetoothSocket btSocket = printerdevice.createRfcommSocketToServiceRecord("ssss");
        mStringBufferResult = new StringBuffer();
        mHandler = new Handler();
        mScanningFishedRunnable = new Runnable() {
            @Override
            public void run() {
                performScanSuccess();
            }
        };
    }
    /**
     * 返回扫码成功后的结果
     */
    private void performScanSuccess() {
        String barcode = mStringBufferResult.toString();
        if (mOnScanSuccessListener != null)
            mOnScanSuccessListener.onScanSuccess(barcode);
        mStringBufferResult.setLength(0);
    }
    /**
     * 扫码枪事件解析
     * @param event
     */
    public void analysisKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
        //字母大小写判断
        checkLetterStatus(event);
        if (event.getAction() == KeyEvent.ACTION_DOWN) {

            char aChar = getInputCode(event);;

            if (aChar != 0) {
                mStringBufferResult.append(aChar);
            }
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                //若为回车键,直接返回
                mHandler.removeCallbacks(mScanningFishedRunnable);
                mHandler.post(mScanningFishedRunnable);
            } else {
                //延迟post,若500ms内,有其他事件
                mHandler.removeCallbacks(mScanningFishedRunnable);
                mHandler.postDelayed(mScanningFishedRunnable, MESSAGE_DELAY);
            }

        }
    }

    //检查shift键
    private void checkLetterStatus(KeyEvent event) {
        int keyCode = event.getKeyCode();
        if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT || keyCode == KeyEvent.KEYCODE_SHIFT_LEFT) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                //按着shift键,表示大写
                mCaps = true;
            } else {
                //松开shift键,表示小写
                mCaps = false;
            }
        }
    }
    //获取扫描内容
    private char getInputCode(KeyEvent event) {
        int keyCode = event.getKeyCode();
        char aChar;
        if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) {
            //字母
            aChar = (char) ((mCaps ? 'A' : 'a') + keyCode - KeyEvent.KEYCODE_A);
        } else if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
            //数字
            aChar = (char) ('0' + keyCode - KeyEvent.KEYCODE_0);
        } else {
            //其他符号
            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() {
        mHandler.removeCallbacks(mScanningFishedRunnable);
        mOnScanSuccessListener = null;
    }
    //部分手机如三星,无法使用该方法
//    private void hasScanGun() {
//        Configuration cfg = getResources().getConfiguration();
//        return cfg.keyboard != Configuration.KEYBOARD_NOKEYS;
//    }
    /**
     * 扫描枪是否连接
     * @return
     */
    public boolean hasScanGun() {
        if (mBluetoothAdapter == null) {
            return false;
        }
        Set<BluetoothDevice> blueDevices = mBluetoothAdapter.getBondedDevices();
        if (blueDevices == null || blueDevices.size() <= 0) {
            return false;
        }
        for (Iterator<BluetoothDevice> iterator = blueDevices.iterator(); iterator.hasNext(); ) {
            BluetoothDevice bluetoothDevice = iterator.next();

            if (bluetoothDevice.getBluetoothClass().getMajorDeviceClass() == BluetoothClass.Device.Major.PERIPHERAL) {

                mDeviceName = bluetoothDevice.getName();
                return isInputDeviceExist(mDeviceName);
            }
        }
        return false;
    }
    /**
     * 输入设备是否存在
     * @param deviceName
     * @return
     */
    private boolean isInputDeviceExist(String deviceName) {
        int[] deviceIds = InputDevice.getDeviceIds();

        for (int id : deviceIds) {
            if (InputDevice.getDevice(id).getName().equals(deviceName)) {
                return true;
            }
        }
        return false;
    }
    /**
     * 是否为扫码枪事件(部分机型KeyEvent获取的名字错误)
     * @param event
     * @return
     */
    @Deprecated
    public boolean isScanGunEvent(KeyEvent event) {
        return event.getDevice().getName().equals(mDeviceName);
}


    /**
     * 检测蓝牙是否开启
     */
    public int checkBluetoothValid() {

        if(mBluetoothAdapter == null) {//你的设备不具备蓝牙功能!
            return 1;
        }

        if(!mBluetoothAdapter.isEnabled()) {//蓝牙设备未打开,请开启此功能后重试!
            return 2;
        }
        return 3;//蓝牙正常工作
    }


}

5.在Activity中使用解析类ScanGunKeyEventHelper

Activity中重写dispatchKeyEvent方法,截取Key事件。

  /**
     * 截获按键事件.发给ScanGunKeyEventHelper
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if (mScanGunKeyEventHelper.isScanGunEvent(event)) {
            mScanGunKeyEventHelper.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

获取扫描结果回调,详细代码请查看TestScanner

/**
 * @author Wu JianCheng
 * @date on   2018/12/18 14:44
 * 测试蓝牙连接扫描枪功能
 */
public class BleAct extends Activity implements ScanGunKeyEventHelper.OnScanSuccessListener {

    ...
    
    /**
     * 扫描结果回调
     * @param barcode
     */
    @Override
    public void onScanSuccess(String barcode) {
        showToast(barcode);
    }
    
    ...

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

最新评论