Step by step to teach you the simple completion of Android USB development

Source: Internet
Author: User

There is a new requirement in the project that a USB thermometer can be connected, the app can read the body temperature data from the thermometer, and a search has found a great USB communication library.
GitHub Address: Usb-serial-for-android

Preparatory work
    1. Clone This library's source file from GitHub
    2. Introducing modules in Android Studio

    3. adding dependencies in Build.gradlecompile project(path: ‘:usbSerialForAndroid‘)

    4. Copy Device_filter.xml to the project's res/xml/folder

    5. Configuring the Androidmanifest.xml File

<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>
Use

Sample code parsing:

Get system service Get Usbmanager instance Usbmanager Manager = (Usbmanager) getsystemservice (Context.usb_service);Find all plugged-in devices list<usbserialdriver> availabledrivers = Usbserialprober.getdefaultprober (). FindAllDrivers ( Manager);if (Availabledrivers.isempty ()) {return;}Open the device and establish a communication connection usbserialdriver driver = availabledrivers.Get0); Usbdeviceconnection connection = Manager.opendevice (Driver.getdevice ());if (connection = =NULL) {You probably need-to-call Usbmanager.requestpermission (Driver.getdevice (),..)return;}//open port, set port parameters, read data usbserialport port = Driver.getports (). get (0); 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 ();}            

The code above is a sample code written by the library author, which shows that it is very simple to use, and the following code demonstrates how to encapsulate a USB operation in a class.

PublicClassTemperatureusbcontrol {PrivateStaticFinal String TAG = TemperatureUsbControl.class.getSimpleName ();PrivateStaticFinal String temperature_usb_vendor_id ="067B";Vendor IDPrivateStaticFinal String temperature_usb_product_id ="2303";Product IDPrivate Context Mcontext;Private Usbmanager Musbmanager;USB ManagerPrivate Usbserialport Stemperatureusbport =NullUSB port for temperature gunPrivate Serialinputoutputmanager Mserialiomanager;Input and output manager (essentially a runnable)PrivateFinal Executorservice mexecutor = Executors.newsinglethreadexecutor ();Used to continuously read data from the portData input/Output listenerPrivateFinal Serialinputoutputmanager.listener Mlistener =New Serialinputoutputmanager.listener () {@OverridePublicvoidOnrunerror (Exception e) {log.d (TAG,"Runner stopped."); }@OverridePublicvoidOnnewdata (FinalByte[] data) {LOG.D (TAG,"New data."); } };PublicTemperatureusbcontrol (Context context) {Mcontext = context;}PublicvoidInitusbcontrol () {Musbmanager = (Usbmanager) mcontext.getsystemservice (Context.usb_service);All devices list<usbserialdriver> usbserialdrivers = Usbserialprober.getdefaultprober (). FindAllDrivers ( Musbmanager);All ports 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;Calibration equipment, equipment is 2303 equipmentfor (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) {Successfully get port, open connection Usbdeviceconnection connection = Musbmanager.opendevice (Stemperatureusbport.getdriver (). GetDevice ()) ;if (connection = =NULL) {LOG.E (TAG,"Opening device Failed");Return }try {stemperatureusbport.open (connection);Set the baud rate stemperatureusbport.setparameters (4800,8, Usbserialport.stopbits_1, Usbserialport.parity_none); }catch (IOException e) {Open port failed, shut down! LOG.E (TAG,"Error Setting up Device:" + e.getmessage (), E);try {stemperatureusbport.close ();}catch (IOException E2) {Ignore. } Stemperatureusbport =NullReturn } }else {Prompt not detected device}}PublicvoidOndevicestatechange () {Re-open the USB manager Stopiomanager (); Startiomanager (); }PrivatevoidStartiomanager () {if (stemperatureusbport! =NULL) {LOG.I (TAG,"Starting IO Manager.."); Mserialiomanager =New Serialinputoutputmanager (Stemperatureusbport, Mlistener); Mexecutor.submit (Mserialiomanager);//essence is to read the USB port continuously with a thread}} 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;      }}} 

Use in activity:

    @OverrideProtectedvoidOnCreate (Bundle savedinstancestate) {Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_punch); Initusbcontrol ();Initialize the USB controller}/** * Initialize USB */PrivatevoidInitusbcontrol () {Mtemperatureusbcontrol =New Temperatureusbcontrol (Mcontext); Mtemperatureusbcontrol.initusbcontrol (); }@OverrideProtectedvoidOnresume () {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 (); }@OverrideProtectedvoidOnPause () {Super.onpause (); Mtemperatureusbcontrol.onpause (); Unregisterreceiver (Musbreceiver); }/** * Broadcasreceiver to detect the USB insertion status */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)) {//device insertion Mtemperatureusbcontrol.initusbcontrol (); Mtemperatureusbcontrol.ondevicestatechange (); LOG.E (TAG,  "action_usb_device_attached");} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals ( Action) {//device removal mtemperatureusbcontrol.onpause (); LOG.E (TAG,  "action_usb_device_detached");}} };

Read the data if you need to use it in the activity, you can use Eventbus to complete the ~

Step by step to teach you the simple completion of Android USB development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.