Android send data to usb

USB Host

In this document

When your Android-powered device is in USB host mode, it acts as the USB host, powers the bus, and enumerates connected USB devices. USB host mode is supported in Android 3.1 and higher.

API Overview

Before you begin, it is important to understand the classes that you need to work with. The following table describes the USB host APIs in the android.hardware.usb package.

Table 1. USB Host APIs

Class Description
UsbManager Allows you to enumerate and communicate with connected USB devices.
UsbDevice Represents a connected USB device and contains methods to access its identifying information, interfaces, and endpoints.
UsbInterface Represents an interface of a USB device, which defines a set of functionality for the device. A device can have one or more interfaces on which to communicate on.
UsbEndpoint Represents an interface endpoint, which is a communication channel for this interface. An interface can have one or more endpoints, and usually has input and output endpoints for two-way communication with the device.
UsbDeviceConnection Represents a connection to the device, which transfers data on endpoints. This class allows you to send data back and forth sychronously or asynchronously.
UsbRequest Represents an asynchronous request to communicate with a device through a UsbDeviceConnection .
UsbConstants Defines USB constants that correspond to definitions in linux/usb/ch9.h of the Linux kernel.

In most situations, you need to use all of these classes ( UsbRequest is only required if you are doing asynchronous communication) when communicating with a USB device. In general, you obtain a UsbManager to retrieve the desired UsbDevice . When you have the device, you need to find the appropriate UsbInterface and the UsbEndpoint of that interface to communicate on. Once you obtain the correct endpoint, open a UsbDeviceConnection to communicate with the USB device.

Android Manifest Requirements

The following list describes what you need to add to your application’s manifest file before working with the USB host APIs:

  • Because not all Android-powered devices are guaranteed to support the USB host APIs, include a element that declares that your application uses the android.hardware.usb.host feature.
  • Set the minimum SDK of the application to API Level 12 or higher. The USB host APIs are not present on earlier API levels.
  • If you want your application to be notified of an attached USB device, specify an and element pair for the android.hardware.usb.action.USB_DEVICE_ATTACHED intent in your main activity. The element points to an external XML resource file that declares identifying information about the device that you want to detect.

In the XML resource file, declare elements for the USB devices that you want to filter. The following list describes the attributes of . In general, use vendor and product ID if you want to filter for a specific device and use class, subclass, and protocol if you want to filter for a group of USB devices, such as mass storage devices or digital cameras. You can specify none or all of these attributes. Specifying no attributes matches every USB device, so only do this if your application requires it:

  • vendor-id
  • product-id
  • class
  • subclass
  • protocol (device or interface)

Save the resource file in the res/xml/ directory. The resource file name (without the .xml extension) must be the same as the one you specified in the element. The format for the XML resource file is in the example below.

Manifest and resource file examples

The following example shows a sample manifest and its corresponding resource file:

In this case, the following resource file should be saved in res/xml/device_filter.xml and specifies that any USB device with the specified attributes should be filtered:

Working with Devices

When users connect USB devices to an Android-powered device, the Android system can determine whether your application is interested in the connected device. If so, you can set up communication with the device if desired. To do this, your application has to:

  1. Discover connected USB devices by using an intent filter to be notified when the user connects a USB device or by enumerating USB devices that are already connected.
  2. Ask the user for permission to connect to the USB device, if not already obtained.
  3. Communicate with the USB device by reading and writing data on the appropriate interface endpoints.

Discovering a device

Your application can discover USB devices by either using an intent filter to be notified when the user connects a device or by enumerating USB devices that are already connected. Using an intent filter is useful if you want to be able to have your application automatically detect a desired device. Enumerating connected USB devices is useful if you want to get a list of all connected devices or if your application did not filter for an intent.

Using an intent filter

To have your application discover a particular USB device, you can specify an intent filter to filter for the android.hardware.usb.action.USB_DEVICE_ATTACHED intent. Along with this intent filter, you need to specify a resource file that specifies properties of the USB device, such as product and vendor ID. When users connect a device that matches your device filter, the system presents them with a dialog that asks if they want to start your application. If users accept, your application automatically has permission to access the device until the device is disconnected.

The following example shows how to declare the intent filter:

The following example shows how to declare the corresponding resource file that specifies the USB devices that you’re interested in:

In your activity, you can obtain the UsbDevice that represents the attached device from the intent like this:

Enumerating devices

If your application is interested in inspecting all of the USB devices currently connected while your application is running, it can enumerate devices on the bus. Use the getDeviceList() method to get a hash map of all the USB devices that are connected. The hash map is keyed by the USB device’s name if you want to obtain a device from the map.

If desired, you can also just obtain an iterator from the hash map and process each device one by one:

Obtaining permission to communicate with a device

Before communicating with the USB device, your application must have permission from your users.

Note: If your application uses an intent filter to discover USB devices as they’re connected, it automatically receives permission if the user allows your application to handle the intent. If not, you must request permission explicitly in your application before connecting to the device.

Explicitly asking for permission might be neccessary in some situations such as when your application enumerates USB devices that are already connected and then wants to communicate with one. You must check for permission to access a device before trying to communicate with it. If not, you will receive a runtime error if the user denied permission to access the device.

To explicitly obtain permission, first create a broadcast receiver. This receiver listens for the intent that gets broadcast when you call requestPermission() . The call to requestPermission() displays a dialog to the user asking for permission to connect to the device. The following sample code shows how to create the broadcast receiver:

To register the broadcast receiver, add this in your onCreate() method in your activity:

To display the dialog that asks users for permission to connect to the device, call the requestPermission() method:

When users reply to the dialog, your broadcast receiver receives the intent that contains the EXTRA_PERMISSION_GRANTED extra, which is a boolean representing the answer. Check this extra for a value of true before connecting to the device.

Communicating with a device

Communication with a USB device can be either synchronous or asynchronous. In either case, you should create a new thread on which to carry out all data transmissions, so you don’t block the UI thread. To properly set up communication with a device, you need to obtain the appropriate UsbInterface and UsbEndpoint of the device that you want to communicate on and send requests on this endpoint with a UsbDeviceConnection . In general, your code should:

  • Check a UsbDevice object’s attributes, such as product ID, vendor ID, or device class to figure out whether or not you want to communicate with the device.
  • When you are certain that you want to communicate with the device, find the appropriate UsbInterface that you want to use to communicate along with the appropriate UsbEndpoint of that interface. Interfaces can have one or more endpoints, and commonly will have an input and output endpoint for two-way communication.
  • When you find the correct endpoint, open a UsbDeviceConnection on that endpoint.
  • Supply the data that you want to transmit on the endpoint with the bulkTransfer() or controlTransfer() method. You should carry out this step in another thread to prevent blocking the main UI thread. For more information about using threads in Android, see Processes and Threads.

The following code snippet is a trivial way to do a synchronous data transfer. Your code should have more logic to correctly find the correct interface and endpoints to communicate on and also should do any transferring of data in a different thread than the main UI thread:

To send data asynchronously, use the UsbRequest class to initialize and queue an asynchronous request, then wait for the result with requestWait() .

For more information, see the AdbTest sample, which shows how to do asynchronous bulk transfers, and the MissileLauncher sample, which shows how to listen on an interrupt endpoint asynchronously.

Terminating communication with a device

When you are done communicating with a device or if the device was detached, close the UsbInterface and UsbDeviceConnection by calling releaseInterface() and close() . To listen for detached events, create a broadcast receiver like below:

Creating the broadcast receiver within the application, and not the manifest, allows your application to only handle detached events while it is running. This way, detached events are only sent to the application that is currently running and not broadcast to all applications.

Источник

Android-er

For Android development, from beginner to beginner.

Monday, September 1, 2014

Send data from Android to Arduino Uno, in USB Host Mode

This example show how to send String from Android to Arduino Uni via USB Serial, in USB Host mode. Actually, it is modified from the example of «Send Hello to Arduino from Android in USB Host Mode», but target to Arduino Uno, instead of Esplora.

In Arduino Uno, the String received from USB port will be displayed on the equipped 2×16 LCD Module.


Because you have to connect Arduino Uno to your Android device with USB port (with USB OTG cable), you are suggested to enable WiFi debugging for ADB.

To target to Arduino Uno, you have to «Check idVendor and idProduct of Arduino Uno». It should be:
vendor-id=»9025″
product-id=»0067″

Create /res/xml/device_filter.xml to specify vendor-id and product-id.

For Arduino Uno side, refer to «Read from Arduino Serial port, and write to 2×16 LCD» of my another blog for Arduino.

13 comments:

Hello. Is it possible to send data from arduino to android via USB?

But I have not success in doing so:(

It is showing Unfortunaely app has stopped.
I think the problem is with the Thread
as all has been done on main UI

can you use Wifi not USB?
to connect arduino and receive data from arduino to android?

how can i control arduino matrix with android?

Hello and thx for this nice article.
I tried this project but ran into some problems so I would appreciate it if anyone could help me.
I used an Arduino UNO for this one and connected it to my phone with the help of an USB OTG Adapter connected to the printer-like cable u get with an Arduino. when I plug the cable into the phone, I get a device not found error in the Toast as well as in the TextView.
I Have already change the Product and Vendor ID’s(changed to 2341 and 0043) in the device_filter.xml as well as in the MainActivity.java file.
I wonder what could be the issue.

This code may I use transfer data
android to pc ?

hello Eiphyu phwe,

In this example Android act as host, and Arduino as slave.

PC cannot act as slave, as I understand. So cannot.

Hello Eric,
i wanna turn on a led using android and arduino with usb and otg cable. please would you help me ? or just give some references.

Hey !!
what is the code for uno ??

Is just simple lcd code if yes .. then is your app send data to serial monitor ?

Источник

Android send data to usb

When it comes to Android data transfer , many will choose the commonly used way, Bluetooth, NFC, USB cable and PC for example. Nonetheless, when using these methods, connection issues always occur. And transmission is quite slow. So, in today’s guide, a new solution – USB OTG will be introduced.

USB OTG or OTG, actually short for USB on-the-go, empowers USB devices like Android phones to act as a host and then allows other USB device to be attached to them. You can make direct connection between two Android phones/tablets and transfer data between Android via USB OTG. By using USB OTG, Android phones plugged-in can communicate with each other without the need to be connected to a computer.

Data Supported: Photos (.jpg, .png, .jepg, etc.) Videos (.mp4, etc.) Music(.mp3, etc.) Documents (PDF, etc.)

Devices Compatible: Samsung Galaxy S6 Edge+/S6 Edge/S6/S5 /S4/ Note 5/Edge/Note 4, etc. Google Nexus 6/5/4, etc. LG G4/G3/LG G2, etc. HTC One M9 +/M9/M8 s/M8 EYE/M8, etc. Sony Xperia Z3/Z2, etc. Motorola X/G/E, etc. HUAWEI Mate 7/P8 Lite/P8/P7, etc. Lenovo A600, etc.

Example: Transfer Files from HTC One M8 to Samsung Galaxy S6

Step 1. Connect Android Phones to OTG

To start with, directly connect the destination phone Samsung Galaxy S6 to the OTG. Then plug in another Android device HTC One M8 to the OTG as source phone with a USB cable. Then enable USB debugging on the HTC One.

Step 2. Select Folder to Transfer

Go the Samsung Galaxy, «Just Once» or «Always» choose a place where files are stored, «Gallery» for example. You will receive a pop-up that says «Allow the app Gallery to access the USB device«. Click the button «OK«.

Step 3. Select Files to Import to the Target Phone

When in the Gallery of the Samsung, select files you want and long tap on them. Then press the button «IMPORT» at the upper-right corner. You can view the importing progress via the bar. When the bar is 100% completed, all selected items are imported from the source phone –HTC One. 22 selected items will be stored in the folder «HTC One» in your Samsung Galaxy.

That’s it. You can also transfer videos, music, movies, and documents between Android phones with OTG. Plus, data in the USB can be read when the USB is connected to the Android/PC via OTG.

is the p8 lite really compatible for otg?? if it is compatible how and what should I do for my phone??

Hi Gerome, sorry that I can’t make sure whether it’s well compatible or not. But I found it in the Amazon, and it says that OTG well support P8 Lite.

DID YOU TRY IT. THE PRODUCT IN AMAZON THAT SUPPORTS OTG IN P8 LITE?? This email has been sent from a virus-free computer protected by Avast.
http://www.avast.com

Received from Huawei, : “Unfortunately, the P8 and P8 lite doesn’t support OTG”

is it possible to use the OTG to connect a flash drive to my HTC Desire 626 and move data to the flash drive? and if so what steps do i take to do this, and what files can be transferred?

Received from Huawei, : “Unfortunately, the P8 doesn’t support OTG”

hey i am Ankush,

When I connect two devices host device is not detecting other device.but the host device is charging other device.please help me to resolve this issue .this is my email id ankushextc@gmail.com

Really pretty cool, But I have already used of lot of APP for transferring data, but nothing gave perfect transfer. Will try this once

Have you tried Reliance JioSwitch?

I tried to transfer my data from phone to pc using data cable..when I cut one folder from phone then paste to pc…I happened to cancel it by mistake…. Now I can find my data neither on phone nor on pc….can someone help. Where I can find my lost data.

Suggest you use Android Data Recovery to scan your device to check if the data is really gone. If no, you can use the registered version of the software to restore the data on your phone.

i tried…but the pics that were retrieved were corrupted..

Can you share the source code ?if yes please email to fengdreampeak@gmail.com

I have a phone that is screen dead. Can I transfer data from that phone to my new phone?

What is the model and system version of your phone?

I have a phone which I am not able to switch on. Can I transfer files to other phone or PC?

If you need any hacking solution concerning your relationship, company
or lost files. just contact N E T S E R V E R S P Y 107 at g mail .com he helped me revealed
all the infidelities concerning my ex-husband, now I know he was really
cheating on me the whole years we shared together. let him know from
Garcia,he will reply you…

Do you need the right help on how to catch a cheating husband/ wife? Text +1 (678) 753-7260 or reach HACKWHALES107 atgmail. com…. Get the peace of mind you deserve…

Never you look down on someone when is referring hacker and specialty when he come to be some body like H A C K W H A L E S 107 @ gmail. com who is professional and have the best quality of hacker and can give the be tools to trace your spouse without them getting detected. I will advice you hire H A C K W H A L E S 107 @gmail. com and get everything you want to solve that concern hacking like whatsapp, facebook, school grade, retrieving of deleted messages and more..

I know of particular hacker who is well know all over the word, and that provide good services when comes to hacking of any such, they are only hacker that i can recommend in this website because have use them couple of time and i will say was awesome. They provide the following service such as school grade, whatsapp hacking, criminal record, facebook account, retriever of lost document and more contact them via
HACKWHALES107 @GMAIL*COM…

I thank Hackwhales107 professional hacker they are the best hacker have ever see. If you need any service contact Hackwhales107@gmail. com to help you solve your worried.

I thank c o m p u t e r g u r u 3 2 2 professional hacker they are the best hacker have ever see. If you need any service contact c o m p u t e r g u r u 3 2 2 @gmail. com to help you solve your worried

THIS TEAM HELPED ME WITHOUT PHYSICAL ACCESS TO THE PHONE.
Do you need cheating proof?
This team Would give you access to the following;
WhatsApp
Instagram
Kik
• Imessage or text message
call records
voicemails
WhatsApp
Live recordings
Facebook
tinder
Viber
camera
emails and e.t.c.
You can reach this team via
H A C K W H A L E S 107@GMAIL.COM
You can also contact for;
Hacking of database………..

He’s a reliable and competent hacker ready to performed any given task
Erase Criminal Records
Hack any Email Account
Hack or Increased Credit card
Social Media Accounts: Facebook,Instagram,Twitter,WhatsApp etc
contact them c o m p u t e r g e e k 3 5 1@ Gmail .Com…..

Источник

Читайте также:  Android google play services dependency
Оцените статью