Android USB Development Detailed

Source: Internet
Author: User


Android USB Development Detailed


Please attach the official Android USB document



Android supports a variety of USB peripherals and Android USB accessories (hardware that implements Android accessory protocol) in two modes: USB accessory and USB host. USB development requires Android 3.1 (API level 12) above. Because I only use the host mode in the work, so the focus of this article in the host model development.


    • Android USB Development Detailed
      • Debugging
      • I.. androidmanifest File Settings
      • Second, the USB device connection and use
        • USB in 1.Android
        • Insertion of 2.USB devices
        • 3. Get Usbmanager
        • 4. Get a list of USB devices
        • 5. Get a specific device
        • 6. Request permission to use USB devices
        • 7. Communication
      • Other
Debugging


When using USB connection device debugging, USB peripherals will not be able to connect to the device, you can use WiFi connection debugging, settings, plugin, WiFi ADB plug-in several, choose a suitable for their own OK.



Or... I happen to have an Android emulator attached to the USB device like to order a nice ha!


I.. androidmanifest File Settings
    • Uses-feature that the software needs to use the USB function, stating that this Google Play will not be satisfied with the device filter out, the general use of USB is custom development, ignoring the line
<uses-feature android:name="android.hardware.usb.host"/>
    • 1
    • Set the application's minimum SDK to API level 12 or higher, without the earlier API.
    • If you want your application to be notified when connecting to a specified USB device, you need to specify and element pairs for Android.hardware.usb.action.USB_DEVICE_ATTACHED. This element points to an external XML resource file that declares to recognize information about the device that you want to detect.
<activity
             Android:name=".MainActivity"
             Android:screenOrientation="landscape">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <!-- If this is the startup activity, click on the pop-up window of the USB access will start the page -->
                 <category android:name="android.intent.category.LAUNCHER" />
                 <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> 
    • in the XML resource file, declare the elements of the USB device that you want to filter. The following list describes the properties. Typically, if you want to filter specific devices and use classes, subclasses, and protocols (if you want to filter a set of USB devices, such as mass storage devices or digital cameras), use the vendor (Vendor-id) and product (Product-id) IDs, In development these filter IDs can usually be found in the document, or they may even look at the . You can specify some or all of these properties. The
      saves the resource file in the res/xml/directory. The resource file name (without the. xml extension) must be the same as the file name that you specified in the element. An example of the XML resource file format is as follows:
 
 
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <usb-device
        class="255"
        product-id="5678"
        protocol="1 "
        subclass="66"
        vendor-id="1234" />
</resources>





When a user connects to a device that matches your device's filter when the manifest file is configured, a dialog box is displayed to ask them if they want to launch your application. If the user accepts it, the application automatically has permission to access the device until the device disconnects. If the default is given, the USB device will automatically start the Activity when it is plugged in.





Second, the USB device connection and use


When configured in the manifest file, we go directly to the Java code link.


USB in 1.Android


Android 3.1 (API level 12) above native provides USB developed API, under the ANDROID.HARDWARE.USB package provides the development of related classes.


Class Description
Usbmanager Get the USB manager to communicate with the connected USB device.
Usbdevice USB device Abstraction, each usbdevice represents a USB device.
Usbinterface Defines the set of features for a device, one usbdevice may contain one or more usbinterface, and each Interface is independent.
Usbendpoint The Usbendpoint is the interface communication channel.
Usbdeviceconnection The host establishes a connection with the device and transmits the data in endpoint.
Usbrequest USB Request package.
Usbconstants Definition of USB constants
Insertion of 2.USB devices


In Android, the USB device is plugged in and unplugged in the form of a system broadcast, so we just have to register to listen to this broadcast.


Public class USBReceiver extends BroadcastReceiver {
    Public static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    @Override
    Public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        If (ACTION_USB_PERMISSION.equals(action)) {
            / / Get the broadcast of the permission result
            Synchronized (this) {
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                If (device != null) {
                    //call method to set up device communication
                    If (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        Log.e("USBReceiver", "Get permission succeeded:" + device.getDeviceName());
                    } else {
                        Log.e("USBReceiver", "Get permission failed:" + device.getDeviceName());
                    }
                }
            }
        }else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            // There is a new device plugged in. Here we usually determine if the device is what we want, and if so, request permission.
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            // Some devices are pulled out
        }
    }
} 




3. Get Usbmanager
usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
4. Get a list of USB devices
 
public List<UsbDevice> getDeviceList() {
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        List<UsbDevice> usbDevices = new ArrayList<>(); while (deviceIterator.hasNext()) {
            UsbDevice device = deviceIterator.next();
            usbDevices.add(device);
            Log.e("USBUtil", "getDeviceList: " + device.getDeviceName());
        } return usbDevices;
    }




5. Get a specific device
 
/**
      * mVendorId=1137,mProductId=85 Jiabo 3150T Label Printer
      *
      * @param vendorId Vendor ID
      * @param productId Product ID
      * @return device
      */
     Public UsbDevice getUsbDevice(int vendorId, int productId) {
         HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
         Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
         While (deviceIterator.hasNext()) {
             UsbDevice device = deviceIterator.next();
             If (device.getVendorId() == vendorId && device.getProductId() == productId) {
                 Log.e("USBUtil", "getDeviceList: " + device.getDeviceName());
                 Return device;
             }
         }
         Toast.makeText(context, "There is no corresponding device", Toast.LENGTH_SHORT).show();
         Return null;
     } 
6. Request permission to use USB devices


The use of the USB device by the Android system requires the appropriate permissions to be granted manually by the user, or to be applied to your app when the device is plugged in. Before using a USB device, we must first confirm that the device in the previous section has been granted permission, and if not, request permission:


/**
      * Determine if the corresponding USB device has permission
      */
     Public boolean hasPermission(UsbDevice device) {
         Return usbManager.hasPermission(device);
     }

     /**
      * Request permission to specify USB device
      */
     Public void requestPermission(UsbDevice device) {
         If (device != null) {
             If (usbManager.hasPermission(device)) {
                 Toast.makeText(context, "has obtained permission", Toast.LENGTH_SHORT).show();
             } else {
                 If (mPermissionIntent != null) {
                     usbManager.requestPermission(device, mPermissionIntent);
                     Toast.makeText(context, "Request USB Permissions", Toast.LENGTH_SHORT).show();
                 } else {
                     Toast.makeText(context, "Please register for USB broadcast", Toast.LENGTH_LONG).show();
                 }
             }
         }
     } 





To register a broadcast:


/**
      * Determine if the corresponding USB device has permission
      */
     Public boolean hasPermission(UsbDevice device) {
         Return usbManager.hasPermission(device);
     }

     /**
      * Request permission to specify USB device
      */
     Public void requestPermission(UsbDevice device) {
         If (device != null) {
             If (usbManager.hasPermission(device)) {
                 Toast.makeText(context, "has obtained permission", Toast.LENGTH_SHORT).show();
             } else {
                 If (mPermissionIntent != null) {
                     usbManager.requestPermission(device, mPermissionIntent);
                     Toast.makeText(context, "Request USB Permissions", Toast.LENGTH_SHORT).show();
                 } else {
                     Toast.makeText(context, "Please register for USB broadcast", Toast.LENGTH_LONG).show();
                 }
             }
         }
     } 




7. Communication


Communication with a USB device can be synchronous or asynchronous. In either case, you should create a new thread to perform all data transfers and avoid blocking the UI thread.



The first step is to open the communication port


Public boolean openPort(UsbDevice device) {
        / / Get the device interface, generally only one, multiple research
        usbInterface = device.getInterface(0);

        / / Determine whether there is permission
        If (hasPermission(device)) {
            // Open the device, get the UsbDeviceConnection object, connect the device, for later communication
            usbConnection = usbManager.openDevice(device);

            If (usbConnection == null) {
                Return false;
            }
            If (usbConnection.claimInterface(usbInterface, true)) {
                Toast.makeText(Utils.getContext(), "Found USB Device Interface", Toast.LENGTH_SHORT).show();
            } else {
                usbConnection.close();
                Toast.makeText(Utils.getContext(), "No USB device interface found", Toast.LENGTH_SHORT).show();
                Return false;
            }
        } else {
            Toast.makeText(Utils.getContext(), "No USB Permissions", Toast.LENGTH_SHORT).show();
            Return false;
        }

        / / Get the two endpoints on the interface, corresponding to OUT and IN
        For (int i = 0; i < usbInterface.getEndpointCount(); ++i) {
            UsbEndpoint end = usbInterface.getEndpoint(i);
            If (end.getDirection() == UsbConstants.USB_DIR_IN) {
                usbEndpointIn = end;
            } else {
                usbEndpointOut = end;
            }
        }
        Return true;
    } 





The second step, send the data


500);
Other


The remaining APIs will be updated as the project continues to evolve.



Attached: Demo Portal



Android USB Development Detailed


Related Article

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.