项目中有一个新的需求,要求可以连接一个USB体温枪,APP可以从体温枪中读取到体温数据,一番搜寻之后发现一个封装很棒的USB通信库。
github地址:usb-serial-for-android
准备工作
从 github 上 clone 这个库的源文件
在Android Studio中引入模块
在build.gradle中添加依赖compile project(path: ':usbSerialForAndroid')
复制 device_filter.xml 到项目的 res/xml/ 文件夹下
配置 AndroidManifest.xml 文件
1 2 3 4 5 6 7 8 9 10 11 12 13
| <uses-feature android:name="android.hardware.usb.host" /> <application> <activity android:name="..." ...> <intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> </intent-filter> <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" /> </activity> </application>
|
使用
示例代码解析:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager); if (availableDrivers.isEmpty()) { return; }
UsbSerialDriver driver = availableDrivers.get(0); UsbDeviceConnection connection = manager.openDevice(driver.getDevice()); if (connection == null) { return; }
UsbSerialPort port = driver.getPorts().get(0); try { port.open(connection);
port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
byte buffer[] = new byte[16]; int numBytesRead = port.read(buffer, 1000); Log.d(TAG, "Read " + numBytesRead + " bytes."); } catch (IOException e) { } finally { port.close(); }
|
上述代码是库作者写的一段示例代码,可以看出使用上非常简单,下面的代码演示了如何将USB操作都封装到一个类里。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| public class TemperatureUsbControl {
private static final String TAG = TemperatureUsbControl.class.getSimpleName(); private static final String TEMPERATURE_USB_VENDOR_ID = "067B"; private static final String TEMPERATURE_USB_PRODUCT_ID = "2303"; private Context mContext; private UsbManager mUsbManager; private UsbSerialPort sTemperatureUsbPort = null; private SerialInputOutputManager mSerialIoManager; private final ExecutorService mExecutor = Executors.newSingleThreadExecutor(); private final SerialInputOutputManager.Listener mListener = new SerialInputOutputManager.Listener() {
@Override public void onRunError(Exception e) { Log.d(TAG, "Runner stopped."); }
@Override public void onNewData(final byte[] data) { Log.d(TAG, "new data."); } };
public TemperatureUsbControl(Context context) { mContext = context; }
public void initUsbControl() { mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE); List<UsbSerialDriver> usbSerialDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager); List<UsbSerialPort> usbSerialPorts = new ArrayList<UsbSerialPort>(); for (UsbSerialDriver driver : usbSerialDrivers) { List<UsbSerialPort> ports = driver.getPorts(); Log.d(TAG, String.format("+ %s: %s port%s", driver, Integer.valueOf(ports.size()), ports.size() == 1 ? "" : "s")); usbSerialPorts.addAll(ports); } String vendorId; String productId; for (UsbSerialPort port : usbSerialPorts) { UsbSerialDriver driver = port.getDriver(); UsbDevice device = driver.getDevice(); vendorId = HexDump.toHexString((short) device.getVendorId()); productId = HexDump.toHexString((short) device.getProductId()); if (vendorId.equals(TEMPERATURE_USB_VENDOR_ID) && productId.equals(TEMPERATURE_USB_PRODUCT_ID)) { sTemperatureUsbPort = port; } } if (sTemperatureUsbPort != null) { UsbDeviceConnection connection = mUsbManager.openDevice(sTemperatureUsbPort.getDriver().getDevice()); if (connection == null) { Log.e(TAG, "Opening device failed"); return; } try { sTemperatureUsbPort.open(connection); sTemperatureUsbPort.setParameters(4800, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
} catch (IOException e) { Log.e(TAG, "Error setting up device: " + e.getMessage(), e); try { sTemperatureUsbPort.close(); } catch (IOException e2) { } sTemperatureUsbPort = null; return; } } else { } }
public void onDeviceStateChange() { stopIoManager(); startIoManager(); }
private void startIoManager() { if (sTemperatureUsbPort != null) { Log.i(TAG, "Starting io manager .."); mSerialIoManager = new SerialInputOutputManager(sTemperatureUsbPort, mListener); mExecutor.submit(mSerialIoManager); } }
private void stopIoManager() { if (mSerialIoManager != null) { Log.i(TAG, "Stopping io manager .."); mSerialIoManager.stop(); mSerialIoManager = null; } }
public void onPause() { stopIoManager(); if (sTemperatureUsbPort != null) { try { sTemperatureUsbPort.close(); } catch (IOException e) { } sTemperatureUsbPort = null; } } }
|
在Activity中使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_punch); initUsbControl(); }
private void initUsbControl() { mTemperatureUsbControl = new TemperatureUsbControl(mContext); mTemperatureUsbControl.initUsbControl(); }
@Override protected void onResume() { super.onResume(); IntentFilter usbFilter = new IntentFilter(); usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); registerReceiver(mUsbReceiver, usbFilter); mTemperatureUsbControl.onDeviceStateChange(); }
@Override protected void onPause() { super.onPause(); mTemperatureUsbControl.onPause(); unregisterReceiver(mUsbReceiver); }
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { mTemperatureUsbControl.initUsbControl(); mTemperatureUsbControl.onDeviceStateChange(); Log.e(TAG, "ACTION_USB_DEVICE_ATTACHED"); } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { mTemperatureUsbControl.onPause(); Log.e(TAG, "ACTION_USB_DEVICE_DETACHED"); } } };
|
读到的数据如果需要在Activity中使用,可以使用EventBus来完成~