背景:近期公司一个项目对接第三方支付设备(类似平板的设备外接usb转串口设备),需要使用usb转串口,实现通信和交互,今天记下过程。
有引用这个库 https://github.com/mik3y/usb-serial-for-android,感谢开源的大佬。
这个库已经集合了一般的芯片协议,就不需要自己再配置了。我们设备是用的ProlificSerialDriver.
唯一要注意的是配置设备的参数:波特率,数据位,体制位,奇偶校验等。其中我就在奇偶校验的参数配置上坑了一把。
只需要按照流程,注意些细节就能跑。
贴下核心的几段代码:
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
class ZYDataSource(){
var mUsbSeriaPortManager: USBSerialPortManager? = null
private var usbDeviceConnection: UsbDeviceConnection? = null
private var mDevice: UsbDevice? = null
private var mUsbSerialPort: UsbSerialPort? = null
private var usbPermissionReceiver: UsbPermissionReceiver? = null
private var mUsbManager: UsbManager? = null
/**
* 初始化
*/
override fun initCompletable(context: Context): Completable {
return Completable.create() {
mUsbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
//查找所有设备
val driversList = Usb