Android connectivity-USB Host Mode (III)

Source: Internet
Author: User

Get the permission to communicate with the device

Before you can communicate with a USB device, your application must be licensed by the user.

Note:If your application uses the intent filter to discover the connected USB device and the user allows your application to process the intent, it will automatically receive the permission. Otherwise, before your application can access the device, you must explicitly apply for permissions.

Explicit permission application is required in some cases, such as when your application lists connected USB devices and wants to communicate with one of them. Before trying to communicate with a device, you must check whether you have the permission to access the device. Otherwise, if the user rejects your request to access the device, you will receive a runtime error.

To obtain this permission explicitly, you must first create a broadcast receiver. This receiver is used to listen to the intent object issued by the system when you call the requestpermission () method. When you call the requestpermission () method, the system displays a dialog box asking you if you are allowed to connect to the USB device. The following code creates a broadcast receiver:

Private Static final string action_usb_permission =


"Com. Android. example. usb_permission ";

Private Final broadcastreceiver musbreceiver = new broadcastreceiver (){

 


Public void onreceive (context, intent ){


String action = intent. getaction ();


If (action_usb_permission.equals (Action )){


Synchronized (this ){


Usbdevice device = (usbdevice) intent. getparcelableextra (usbmanager. extra_device );

 


If (intent. getbooleanextra (usbmanager. extra_permission_granted, false )){


If (device! = NULL ){


// Call method to set up device Communication


}


}


Else {


Log. D (TAG, "Permission denied for device" + device );


}


}


}


}

};

Add the code to register the broadcast receiver in the oncreate () method of your activity:

Usbmanager musbmanager = (usbmanager) getsystemservice (context. usb_service );

Private Static final string action_usb_permission =


"Com. Android. example. usb_permission ";

...

Mpermissionintent = pendingintent. getbroadcast (this, 0, new intent (action_usb_permission), 0 );

Intentfilter filter = new intentfilter (action_usb_permission );

Registerreceiver (musbreceiver, filter );

Call the requestpermission () method to display the dialog box for applying for the permission to access the device:

USB device;

...

Musbmanager. requestpermission (device, mpermissionintent );

When you reply to this dialog box, your broadcast receiver will receive an intent object containing the extra_permissino_granted type additional field. This field uses a Boolean value to represent the answer result. Before connecting to the device, check whether the value of this field is true.

Communicate with devices

Communication with USB devices can be either asynchronous or synchronous. In asynchronous mode, you should create a thread to execute all data transmission, so as not to block the UI thread. To correctly establish the communication with the device, you need to obtain the USB interface and USB endpoint object corresponding to the device to which the communication is prepared, and send the request to this endpoint using the USB deviceconnection object. The general steps are as follows:

1. Check the attributes of the USB device object, such as the product ID, supplier ID, or device category to determine whether the device is the device you want;

2. When you confirm that it is the device you want to communicate with, you need to find the USB interface object corresponding to the device and the USB endpoint object along with the interface object. An interface can have one or more endpoints, which are usually used for duplex communication;

3. When you find the correct endpoint, you can open a USB deviceconnection object on the endpoint;

4. Use the bulktransfer () or controltransfer () method to provide the data you want To transmit to the endpoint. You should execute this step in another thread to prevent blocking the main UI thread.

The following code snippet is a common method for synchronous data transmission. Your code should have more logic for finding the correct interfaces and endpoints for communication, and data transmission should also be performed in a thread different from the main UI thread:

Private byte [] bytes

Private Static int timeout = 0;

Private Boolean forceclaim = true;

 

...

 

Usbinterface INTF = device. getinterface (0 );

Usbendpoint endpoint = INTF. getendpoint (0 );

Usbdeviceconnection connection = musbmanager. opendevice (device );

Connection. claiminterface (INTF, forceclaim );

Connection. bulktransfer (endpoint, bytes, bytes. length, timeout); // do in another thread

To send data asynchronously, you must use the usbrequest class for initialization and send an asynchronous request to wait for the result using the requestwait () method.

For more information, see ADB test sample, which shows how to Implement Asynchronous block data transmission, misslelauncher
Sample shows how to listen to asynchronous interrupt endpoints.

Interrupt communication with the device

Call the releaseinterface () and close () Methods to disable the USB interface and USB deviceconnection objects when you complete communication with the device or when the device is separated. Create the following broadcast receiver to listen to the separation event:

Broadcastreceiver musbreceiver = new broadcastreceiver (){


Public void onreceive (context, intent ){


String action = intent. getaction ();

 


If (usbmanager. action_usb_device_detached.equals (Action )){


Usbdevice device = (usbdevice) intent. getparcelableextra (usbmanager. extra_device );


If (device! = NULL ){


// Call your method that cleans up and closes communication with the device


}


}


}

};

If you create a broadcast receiver in the application but are not registered in the list, you can allow your application to process the separation event only at runtime. In this case, the separation event is only sent to the currently running application, and is not broadcast to all applications.

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.