欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-07-08 16:08:35
条形扫描枪主要可以扫描条形码和二维码等,扫描速度比手机扫描设备快得多,本文简单介绍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);
    }
    
    ...

}

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