Start with two open source projects one is Google's Open source project: https://code.google.com/archive/p/android-serialport-api/
The other is the open source project we introduced this time: https://github.com/mik3y/usb-serial-for-android
First step: Get all the plugged-in serial drivers
1 Usbmanager manager = (usbmanager) Getsystemservice (context.usb_service); 2 list<usbserialdriver> availabledrivers = usbserialprober.getdefaultprober (). FindAllDrivers ( Manager); 3 if (Availabledrivers.isempty ()) {4 return ; 5 }
We then select the first dirver to connect the device
1 usbserialdriver driver = availabledrivers.get (0); 2 usbdeviceconnection connection = Manager.opendevice (Driver.getdevice ()); 3 if NULL {4 // probably need to call Usbmanager.requestpermission (Driver.getdevice (), ..) 5 return ; 6 }
Then we can read the data.
1 //Read some data! Most of the just one port (port 0).2Usbserialport port = driver.getports (). Get (0);3 Try {4 Port.open (connection);5 //set the baud rate, data bit, stop bit, check digit of serial port6Port.setparameters (115200, 8, Usbserialport.stopbits_1, usbserialport.parity_none);7 8 byteBuffer[] =New byte[16];9 intNumbytesread = port.read (buffer, 1000);TenLOG.D (TAG, "Read" + Numbytesread + "bytes.")); One}Catch(IOException e) { A //Deal with error. -}finally { - port.close (); the}
Of course, we can add a monitor to the serial port.
11Private FinalExecutorservice Mexecutor =executors.newsinglethreadexecutor ();22PrivateSerialinputoutputmanager Mserialiomanager;3344Private FinalSerialinputoutputmanager.listener Mlistener =55NewSerialinputoutputmanager.listener () {66@Override77 Public voidOnrunerror (Exception e) {88 Log.d (TAG, "Runner stopped.");99 }Ten10 One11@Override A12 Public voidOnnewdata (Final byte[] data) { -13//TODO New Data -14 } the15 }; -16 -Mserialiomanager =NewSerialinputoutputmanager (SPort, Mlistener);//Add Listener - //Monitor the data changes of the serial port in the new thread +Mexecutor.submit (Mserialiomanager);
If you need to accept large data, you may encounter a problem: the data cache and receive time is not enough, so that the data is overwritten or lost, we need to modify the serial port read cache
Change the Read_wait_millis and Bufsiz in Serialinputoutputmanager to the right size.
The operation of writing data is the method of calling port
Port.write (bytes, 1000);
In fact, this open source project has encapsulated a lot of drivers for us, all under the driver package, we can directly use it.
I have time for cp21xx-driven USB port to tell how to differentiate multiple USB serial ports
Android device uses USB serial port to transfer data