public class UsbKeyBoard {private static volatile UsbKeyBoard usbKeyBoard;private UsbEndpoint inEndpoint;private UsbEndpoint outEndpoint;private UsbDeviceConnection connection;private KeyBoardListener keyBoardListener;private boolean isNeedRead=false;private boolean isConnect=false;public static UsbKeyBoard getInstance(Context context) {if (usbKeyBoard == null) {synchronized (UsbKeyBoard.class) {if (usbKeyBoard == null) {usbKeyBoard = new UsbKeyBoard();/*try {if (!openUsb(context)){return null;}} catch (Exception e) {e.printStackTrace();}*/}}}return usbKeyBoard;}public boolean openUsb(Context context) throws Exception {UsbManager usbManager = (UsbManager) context.getApplicationContext().getSystemService(Context.USB_SERVICE);if (usbManager == null) {//throw new Exception(\"no usb service\");ToastUtil.showToastWithImg(\"暂无键盘设备\", R.drawable.ico_fail);return false;}else {//获取usb设备列表Map<String, UsbDevice> devices = usbManager.getDeviceList();if (devices.size()==0){ToastUtil.showToastWithImg(\"暂无键盘设备\", R.drawable.ico_fail);return false;}else {for (UsbDevice device : devices.values()) {//判断是否为意锐键盘if (device.getProductName().equals(\"INSPIRY READER\")){UsbInterface usbInterface = device.getInterface(0);//USBEndpoint为读写数据所需的节点inEndpoint = usbInterface.getEndpoint(0); //读数据节点outEndpoint = usbInterface.getEndpoint(1); //写数据节点connection = usbManager.openDevice(device);if (!connection.claimInterface(usbInterface, true)) {Log.e(\"键盘连接\",\"失败\");return false;}if (Build.VERSION.SDK_INT >= 21) {connection.setInterface(usbInterface);}break;}}this.keyBoardListener=keyBoardListener;new ReadThread().start();return true;}}}public void regist(KeyBoardListener keyBoardListener){this.keyBoardListener=keyBoardListener;new ReadThread().start();}public void unRegist(){this.keyBoardListener=null;isNeedRead=false;}class ReadThread extends Thread{public void run() {while (AppApplication.getInstance().isConnectHID()){byte[] buffer = new byte[8];try {int bytesRead = connection.bulkTransfer(inEndpoint, buffer, 8, -1);Log.e(\"inEndpoint\",inEndpoint+\"\");if (bytesRead < 8) {buffer = Arrays.copyOfRange(buffer, 0, bytesRead);//Log.e(\"是否插上键盘\", AppApplication.getInstance().isConnectHID()+\"\");}}catch (Exception e){handler.sendEmptyMessage(0);return;}Log.d(\"全部\",HexBin.encode(buffer).substring(4,6));if (!HexBin.encode(buffer).substring(4,6).equals(\"00\")){keyBoardListener.read(Integer.parseInt(HexBin.encode(buffer).substring(4,6),16));}}}}private Handler handler=new Handler(){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);ToastUtil.showToastWithImg(\"键盘已拔出\",R.drawable.ico_fail);}};public void Write(byte[] data){try{int result=connection.controlTransfer(0x21, 0x09, 0x02, 0, data, 2, 20000);if (result!=-1){Log.e(\"发送键盘指令result\",result+\"\");}else {Log.e(\"发送键盘指令result\",result+\"\");}}catch (Exception e){handler.sendEmptyMessage(0);return;}}}
android usb HID意锐键盘sdk封装
未经允许不得转载:爱站程序员基地 » android usb HID意锐键盘sdk封装