android host usb

http://blog.csdn.net/androidlinuxg/article/details/17069173

还在百度Google导出搜索如何进行USB接口的HID进行开发吗?网站上很多文章并不完善,这方便的也介绍的不多,我看了很多资料,借助网上的一些代码,整理了以下信息,希望能给大家提供便捷

首先请大家仔细看看Google官方并不详细的SDK文档http://developer.android.com/guide/topics/connectivity/usb/host.html

Android系统3.1及以上版本才能支持USBHOST,这样我们才能连接HID设备进行通讯

项目新建完成之后,AndroidManifest.xml中加入以下代码

然后res下增加xml文件夹,新建device_filter.xml,并加入一下代码,这里是声明HID设备VID以及PID,注意是10进制

下面就是java代码了,直接贴完整代码吧

001./*
002.* Copyright (C) 2011 The Android Open Source Project
003.*
004.* Licensed under the Apache License, Version 2.0 (the "License");
005.* you may not use this file except in compliance with the License.
006.* You may obtain a copy of the License at
007.*
009.*
010.* Unless required by applicable law or agreed to in writing, software
011.* distributed under the License is distributed on an "AS IS" BASIS,
012.* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013.* See the License for the specific language governing permissions and
014.* limitations under the License.
015.*/
016. 
017.package com.android.missilelauncher;
018. 
019.import java.nio.ByteBuffer;
020.import java.util.ArrayList;
021.import java.util.Arrays;
022.import java.util.HashMap;
023.import java.util.Iterator;
024. 
025.import android.app.Activity;
026.import android.content.Context;
027.import android.content.Intent;
028.import android.hardware.Sensor;
029.import android.hardware.SensorEvent;
030.import android.hardware.SensorEventListener;
031.import android.hardware.SensorManager;
032.import android.hardware.usb.UsbConstants;
033.import android.hardware.usb.UsbDevice;
034.import android.hardware.usb.UsbDeviceConnection;
035.import android.hardware.usb.UsbEndpoint;
036.import android.hardware.usb.UsbInterface;
037.import android.hardware.usb.UsbManager;
038.import android.hardware.usb.UsbRequest;
039.import android.os.Bundle;
040.import android.util.Log;
041.import android.view.Gravity;
042.import android.view.View;
043.import android.view.View.OnClickListener;
044.import android.widget.ArrayAdapter;
045.import android.widget.Button;
046.import android.widget.ListView;
047.import android.widget.TextView;
048.import android.widget.Toast;
049. 
050.public class MissileLauncherActivity extends Activity {
051. 
052.private static final String TAG = "MissileLauncherActivity";
053. 
054.private Button btsend; // 发送按钮
055.private UsbManager manager; // USB管理器
056.private UsbDevice mUsbDevice; // 找到的USB设备
057.private ListView lsv1; // 显示USB信息的
058.private UsbInterface mInterface;
059.private UsbDeviceConnection mDeviceConnection;
060. 
061.@Override
062.public void onCreate(Bundle savedInstanceState) {
063.super.onCreate(savedInstanceState);
064. 
065.setContentView(R.layout.launcher);
066. 
067.btsend = (Button) findViewById(R.id.btsend);
068.btsend.setOnClickListener(btsendListener);
069. 
070.lsv1 = (ListView) findViewById(R.id.lsv1);
071. 
072.// 获取USB设备
073.manager = (UsbManager) getSystemService(Context.USB_SERVICE);
074.if (manager == null) {
075.return;
076.else {
077.Log.i(TAG, "usb设备:" + String.valueOf(manager.toString()));
078.}
079.HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
080.Log.i(TAG, "usb设备:" + String.valueOf(deviceList.size()));
081.Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
082.ArrayList<String> USBDeviceList = new ArrayList<String>(); // 存放USB设备的数量
083.while (deviceIterator.hasNext()) {
084.UsbDevice device = deviceIterator.next();
085. 
086.USBDeviceList.add(String.valueOf(device.getVendorId()));
087.USBDeviceList.add(String.valueOf(device.getProductId()));
088. 
089.// 在这里添加处理设备的代码
090.if (device.getVendorId() == 6790 && device.getProductId() == 57360) {
091.mUsbDevice = device;
092.Log.i(TAG, "找到设备");
093.}
094.}
095.// 创建一个ArrayAdapter
096.lsv1.setAdapter(new ArrayAdapter<String>(this,
097.android.R.layout.simple_list_item_1, USBDeviceList));
098.findIntfAndEpt();
099.}
100. 
101.// 寻找接口和分配结点
102.private void findIntfAndEpt() {
103.if (mUsbDevice == null) {
104.Log.i(TAG, "没有找到设备");
105.return;
106.}
107.for (int i = 0; i < mUsbDevice.getInterfaceCount();) {
108.// 获取设备接口,一般都是一个接口,你可以打印getInterfaceCount()方法查看接
109.// 口的个数,在这个接口上有两个端点,OUT 和 IN
110.UsbInterface intf = mUsbDevice.getInterface(i);
111.Log.d(TAG, i + " " + intf);
112.mInterface = intf;
113.break;
114.}
115. 
116.if (mInterface != null) {
117.UsbDeviceConnection connection = null;
118.// 判断是否有权限
119.if (manager.hasPermission(mUsbDevice)) {
120.// 打开设备,获取 UsbDeviceConnection 对象,连接设备,用于后面的通讯
121.connection = manager.openDevice(mUsbDevice);
122.if (connection == null) {
123.return;
124.}
125.if (connection.claimInterface(mInterface, true)) {
126.Log.i(TAG, "找到接口");
127.mDeviceConnection = connection;
128.// 用UsbDeviceConnection 与 UsbInterface 进行端点设置和通讯
129.getEndpoint(mDeviceConnection, mInterface);
130.else {
131.connection.close();
132.}
133.else {
134.Log.i(TAG, "没有权限");
135.}
136.else {
137.Log.i(TAG, "没有找到接口");
138.}
139.}
140. 
141.private UsbEndpoint epOut;
142.private UsbEndpoint epIn;
143. 
144.// 用UsbDeviceConnection 与 UsbInterface 进行端点设置和通讯
145.private void getEndpoint(UsbDeviceConnection connection, UsbInterface intf) {
146.if (intf.getEndpoint(1) != null) {
147.epOut = intf.getEndpoint(1);
148.}
149.if (intf.getEndpoint(0) != null) {
150.epIn = intf.getEndpoint(0);
151.}
152.}
153. 
154.private byte[] Sendbytes; // 发送信息字节
155.private byte[] Receiveytes; // 接收信息字节
156.private OnClickListener btsendListener = new OnClickListener() {
157.int ret = -100;
158. 
159.@Override
160.public void onClick(View v) {
161.String testString = "010A";
162.//String testString = "C783CC30";
163.byte[] bt = clsPublic.HexString2Bytes(testString);
164. 
165.Sendbytes = Arrays.copyOf(bt, bt.length);
166. 
167.// 1,发送准备命令
168.ret = mDeviceConnection.bulkTransfer(epOut, Sendbytes,
169.Sendbytes.length, 5000);
170.Log.i(TAG, "已经发送!");
171. 
172.// 2,接收发送成功信息
173.Receiveytes = new byte[32];
174.ret = mDeviceConnection.bulkTransfer(epIn, Receiveytes,
175.Receiveytes.length, 10000);
176.Log.i(TAG, "接收返回值:" + String.valueOf(ret));
177.if (ret != 32) {
178.DisplayToast("接收返回值" + String.valueOf(ret));
179.return;
180.else {
181.// 查看返回值
182.DisplayToast(clsPublic.Bytes2HexString(Receiveytes));
183.Log.i(TAG, clsPublic.Bytes2HexString(Receiveytes));
184.}
185.}
186.};
187. 
188.public void DisplayToast(CharSequence str) {
189.Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);
190.// 设置Toast显示的位置
191.toast.setGravity(Gravity.TOP, 0200);
192.// 显示Toast
193.toast.show();
194.}
195. 
196.}
      
   

步骤五:我在步骤四的代码中包含有个类clsPublic,这个类是用来转换十六进制和字符串的,一般来说大家也不需要,但是考虑代码完整性,我也贴上来。这个类和MainActivity是在同一个包名下的文件clsPublic.java。

package com.example.usbmanager;
       
public class clsPublic {
    // 整数到字节数组转换
     public static byte[] int2bytes(int n) {
     byte[] ab = new byte[4];
     ab[0] = (byte) (0xff & n);
     ab[1] = (byte) ((0xff00 & n) >> 8);
     ab[2] = (byte) ((0xff0000 & n) >> 16);
     ab[3] = (byte) ((0xff000000 & n) >> 24);
     return ab;
     }
       
     // 字节数组到整数的转换
     public static int bytes2int(byte b[]) {
     int s = 0;
     s = ((((b[0] & 0xff) << 8 | (b[1] & 0xff)) << 8) | (b[2] & 0xff)) << 8
     | (b[3] & 0xff);
     return s;
     }
       
     // 字节转换到字符
     public static char byte2char(byte b) {
     return (char) b;
     }
       
     private final static byte[] hex = "0123456789ABCDEF".getBytes();
       
     private static int parse(char c) {
     if (c >= 'a')
     return (c - 'a' + 10) & 0x0f;
     if (c >= 'A')
     return (c - 'A' + 10) & 0x0f;
     return (c - '0') & 0x0f;
     }
       
     // 从字节数组到十六进制字符串转换
     public static String Bytes2HexString(byte[] b) {
     byte[] buff = new byte[2 * b.length];
     for (int i = 0; i < b.length; i++) {
     buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
     buff[2 * i + 1] = hex[b[i] & 0x0f];
     }
     return new String(buff);
     }
       
     // 从十六进制字符串到字节数组转换
     public static byte[] HexString2Bytes(String hexstr) {
     byte[] b = new byte[hexstr.length() / 2];
     int j = 0;
     for (int i = 0; i < b.length; i++) {
     char c0 = hexstr.charAt(j++);
     char c1 = hexstr.charAt(j++);
     b[i] = (byte) ((parse(c0) << 4) | parse(c1));
     }
     return b;
     }
}

步骤六:

          制作完成软件后,安装到设备上,或者直接用Eclipse调试运行。然后插入USB-HID设备,幸运的话,你会看到系统弹出一个打开方式的提示(我的设备是这样的,其他设备不知道是什么结果)。

原文地址:https://www.cnblogs.com/I-L-o-v-e-z-h-o-u/p/4476445.html