標籤:lte equals manager compile 輸出 eof 需要 ems receiver
項目中有一個新的需求,要求可以串連一個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 檔案
<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>
使用
範例程式碼解析:
// 擷取系統服務得到UsbManager執行個體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) { // You probably need to call UsbManager.requestPermission(driver.getDevice(), ..) 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) { // Deal with error.} finally { port.close();}
上述代碼是庫作者寫的一段範例程式碼,可以看出使用上非常簡單,下面的代碼示範了如何將USB操作都封裝到一個類裡。
public class TemperatureUsbControl { private static final String TAG = TemperatureUsbControl.class.getSimpleName(); private static final String TEMPERATURE_USB_VENDOR_ID = "067B"; //供應商id private static final String TEMPERATURE_USB_PRODUCT_ID = "2303"; //產品id private Context mContext; private UsbManager mUsbManager; //USB管理器 private UsbSerialPort sTemperatureUsbPort = null; //接體溫槍的usb連接埠 private SerialInputOutputManager mSerialIoManager; //輸入輸出管理器(本質是一個Runnable) 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; //校正裝置,裝置是 2303裝置 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) { // Ignore. } sTemperatureUsbPort = null; return; } } else { //提示未檢測到裝置 } } public void onDeviceStateChange() { //重新開啟USB管理器 stopIoManager(); startIoManager(); } private void startIoManager() { if (sTemperatureUsbPort != null) { Log.i(TAG, "Starting io manager .."); mSerialIoManager = new SerialInputOutputManager(sTemperatureUsbPort, mListener); mExecutor.submit(mSerialIoManager); //實質是用一個線程不斷讀取USB連接埠 } } 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) { // Ignore. } sTemperatureUsbPort = null; } }}
在Activity中使用:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_punch); initUsbControl(); //初始化USB控制器 } /** * 初始化USB */ 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); } /** * 用於檢測usb插入狀態的BroadcasReceiver */ 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來完成~
一步一步教你簡單完成 Android USB開發