Usbmanger operating mode of USB under Android

Source: Internet
Author: User

Android USB Development Trouble is still more.

First Type: Host mode

This mode is good, powered by an Android device, and then communicates with the external device. For example: A computer connected to a USB device is a very common mode of this mode.

But there is a vicious question, what happens when Android is connected to an external USB device? There is also the chip dare to say that the Android system to support their home chip, and which manufacturers say that the Android system installed on their home drive, their home devices can be used on Android, perhaps this is difficult for Android to surpass Windows.

Think of the status quo: Want to add external devices, want to: re-do the underlying driver---> compile system---> Brush---> Write android program---> Access hardware implementation capabilities.

The whole set came down to eat a few meals. Still hope that the development of Android in the future can support the multi-device driver like window.

The second type: Accessory mode

This mode is more anxious, external equipment to supply power, data communication: Computer---Mobile phone is this mode, mobile phone as accessory device, the computer supplies its power, and data communication.

It happened that I was using this pattern:

What the program needs to do:

(1) Add action Boardcast

private static final String action_usb_permission = "Com.ukey.USB_PERMISSION";

[Java]
        /***********************usb handling******************************************/Usbmanager=(Usbmanager) Context.getsystemservice (Context.usb_service); Mpermissionintent= Pendingintent.getbroadcast (Context,0,NewIntent (action_usb_permission),0); Intentfilter Filter=NewIntentfilter (action_usb_permission);                Filter.addaction (usbmanager.action_usb_accessory_detached);        Context.registerreceiver (musbreceiver, filter); InputStream=NULL; OutputStream=NULL;

(2) write the corresponding boradcaset information

    /***********USB Broadcast receiver*******************************************/    PrivateFinal Broadcastreceiver Musbreceiver =NewBroadcastreceiver () {@Override Public voidOnReceive (Context context, Intent Intent) {String action=intent.getaction (); if(Action_usb_permission.equals (ACTION)) {synchronized ( This) {usbaccessory accessory=(usbaccessory) Intent.getparcelableextra (usbmanager.extra_accessory); if(Intent.getbooleanextra (usbmanager.extra_permission_granted,false) {toast.maketext (Global_context,"Allow USB Permission", Toast.length_short). Show ();                                                Openaccessory (accessory); }Else{toast.maketext (Global_context,"Deny USB Permission", Toast.length_short). Show (); } mpermissionrequestpending=false; }            }             Else if(UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals (ACTION)) {destroyaccessory (true); }Else{LOG.D ("LED","...."); }        }    };

(3) A more troublesome thing to do.

Android will ask you to allow device access every time you use accessory, which will click Yes or no results and (2) in the code

if false))

Start the request.

(4) Openaccessory function

     Public intopenaccessory () {//Intent Intent = Getintent ();        if(InputStream! =NULL&& OutputStream! =NULL) {            return 1; } usbaccessory[] Accessories=usbmanager.getaccessorylist (); if(Accessories! =NULL) {Toast.maketext (Global_context,"Accessory attached", Toast.length_short). Show (); }Else{            //return 2 for accessory detached case            return 2; } usbaccessory Accessory= (Accessories = =NULL?NULL: accessories[0]); if(Accessory! =NULL) {            if( -1==accessory.tostring (). IndexOf (manufacturerstring)) {Toast.maketext (Global_context,"manufacturer is not matched!", Toast.length_short). Show (); return 1; }            if( -1= = Accessory.tostring (). IndexOf (ModelString1) &&-1==accessory.tostring (). IndexOf (ModelString2)) {Toast.maketext (Global_context,"Model is not matched!", Toast.length_short). Show (); return 1; }if( -1==accessory.tostring (). IndexOf (versionstring)) {Toast.maketext (Global_context,"Version is not matched!", Toast.length_short). Show (); return 1; } toast.maketext (Global_context,"manufacturer, Model & Version is matched!", Toast.length_short). Show (); if(usbmanager.haspermission (Accessory)) {openaccessory (accessory); }Else{synchronized (musbreceiver) {if(!mpermissionrequestpending) {Toast.maketext (Global_context,"Request USB Permission", Toast.length_short). Show ();                        Usbmanager.requestpermission (accessory,mpermissionintent); Mpermissionrequestpending=true; }                }            }        }        return 0; }

Android Connectivity---USB host mode (ii)

Working with the device

When a user connects a USB device to an Android device, the Android system can tell if your application is interested in the device you're accessing. If it is a device of interest to your application, you can establish communication with the device you expect. Here are the things your application must do:

1. Use one of the following two methods to discover the incoming UDB device:

A. Using the intent filter, filter the user to access the USB device notification issued;

B. Enumerate the USB devices that are already plugged in.

2. If you do not have access to the USB device, you will be asked to access the USB device.

3. Communicate with the USB device by reading and writing the data on the corresponding interface endpoint.

Discover devices

The user can either use the intent filter notification when the user accesses the USB device, or they can find the USB device by enumerating the USB devices that are already plugged in. If you want your application to automatically detect the USB device you expect, use the intent filter. If you want to have access to all of the connected devices list, or if your application does not filter the corresponding intent object, then use the enumeration method.

Using the intent Filter

In order for your application to discover a special USB device, you can specify a Android.hardware.usb.action.USB_DEVICE_ATTACHED type of intent filter. Along with this intent filter, you also need to specify a resource file that specifies the properties of the USB device, if the product and vendor ID. When a user accesses a device that matches your device's filter, a dialog box appears asking if you want to allow them to launch your application. If the user receives, the application is automatically granted permission to access the device until the device disconnects.

The following example demonstrates how to declare a intent filter:

<activity ...> ... <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>

The following example shows how to declare a resource file that corresponds to a USB device that you are interested in:

<?xml version="1.0" encoding="utf-8"?> <resources ><usb-device vendor-id="1234" product-id="5678" / ></resources>

In your activity, you can obtain a Usbdevice object from the intent object that represents the device being accessed, as follows:

Usbdevice device= (Usbdevice) Intent.getparcelableextra (Usbmanager.extra_device);

Enumerating Devices

When your application detects all USB devices that are currently plugged in at run time, it can enumerate the devices on the bus. Use the Getdevicelist () method to obtain a hash map of all USB devices that have been plugged in. The hash map uses the name of the USB device to do key:

Usbmanager manager = (usbmanager) Getsystemservice (Context.usb_service); HashMap<string, usbdevice> devicelist == devicelist. Get ("devicename");

If you prefer, you can also use the hash map iterator to process each device:

Usbmanager manager = (usbmanager) Getsystemservice (Context.usb_service); HashMap<string, usbdevice> devicelist = manager.getdevicelist (); Iterator<UsbDevice> Deviceiterator = devicelist.values (). iterator ();  while  = deviceiterator.next ()//your code}

Working with the device

When a user connects a USB device to an Android device, the Android system can tell if your application is interested in the device you're accessing. If it is a device of interest to your application, you can establish communication with the device you expect. Here are the things your application must do:

1. Use one of the following two methods to discover the incoming UDB device:

A. Using the intent filter, filter the user to access the USB device notification issued;

B. Enumerate the USB devices that are already plugged in.

2. If you do not have access to the USB device, you will be asked to access the USB device.

3. Communicate with the USB device by reading and writing the data on the corresponding interface endpoint.

Discover devices

The user can either use the intent filter notification when the user accesses the USB device, or they can find the USB device by enumerating the USB devices that are already plugged in. If you want your application to automatically detect the USB device you expect, use the intent filter. If you want to have access to all of the connected devices list, or if your application does not filter the corresponding intent object, then use the enumeration method.

Using the intent Filter

In order for your application to discover a special USB device, you can specify a Android.hardware.usb.action.USB_DEVICE_ATTACHED type of intent filter. Along with this intent filter, you also need to specify a resource file that specifies the properties of the USB device, if the product and vendor ID. When a user accesses a device that matches your device's filter, a dialog box appears asking if you want to allow them to launch your application. If the user receives, the application is automatically granted permission to access the device until the device disconnects.

The following example demonstrates how to declare a intent filter:

<activity ...> ... <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"

The following example shows how to declare a resource file that corresponds to a USB device that you are interested in:

<?xml version="1.0" encoding="utf-8"?> <resources ><usb-device vendor-id="1234" product-id="5678" / ></resources>

In your activity, you can obtain a Usbdevice object from the intent object that represents the device being accessed, as follows:

Usbdevice device= (Usbdevice) Intent.getparcelableextra (Usbmanager.extra_device);

Enumerating Devices

When your application detects all USB devices that are currently plugged in at run time, it can enumerate the devices on the bus. Use the Getdevicelist () method to obtain a hash map of all USB devices that have been plugged in. The hash map uses the name of the USB device to do key:

Usbmanager manager = (usbmanager) Getsystemservice (Context.usb_service); HashMap<string, usbdevice> devicelist == devicelist. Get ("devicename");

If you prefer, you can also use the hash map iterator to process each device:

Usbmanager manager = (usbmanager) Getsystemservice (Context.usb_service); HashMap<string, usbdevice> devicelist = manager.getdevicelist (); Iterator<UsbDevice> Deviceiterator = devicelist.values (). iterator ();  while  = deviceiterator.next ()//your code}

Usbmanger operating mode of USB under Android

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.