当前位置: 首页 > news >正文

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代码了,直接贴完整代码吧

 

view source print ?
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. *
008. *      http://www.apache.org/licenses/LICENSE-2.0
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

相关文章:

  • Fighting
  • 基于Cocos2d-x学习OpenGL ES 2.0系列——OpenGL ES渲染之Shader准备(7)
  • Swing基础
  • php post
  • poj--1517
  • Midas Civil的钢束生成器
  • 练习写一个工资结算系统
  • linux的各个子系统
  • 域名注冊以及域名解析设置
  • 约瑟夫环实现之非递归
  • 微信公众号-开发者-自定义菜单-CLICK事件处理
  • “我爱淘”冲刺阶段Scrum站立会议6
  • 我们还需要兼容IE样式问题吗?
  • modernizr框架之表单验证
  • jquery easyUI DataGrid 初始化的时候就显示可排序的字段
  • C++回声服务器_9-epoll边缘触发模式版本服务器
  • CSS3 变换
  • ES6 学习笔记(一)let,const和解构赋值
  • JS变量作用域
  • JS实现简单的MVC模式开发小游戏
  • js作用域和this的理解
  • MySQL常见的两种存储引擎:MyISAM与InnoDB的爱恨情仇
  • Netty 4.1 源代码学习:线程模型
  • Nginx 通过 Lua + Redis 实现动态封禁 IP
  • PhantomJS 安装
  • Promise面试题,控制异步流程
  • Spark学习笔记之相关记录
  • 老板让我十分钟上手nx-admin
  • 力扣(LeetCode)22
  • 思维导图—你不知道的JavaScript中卷
  • 微信小程序开发问题汇总
  • 线上 python http server profile 实践
  • 一个普通的 5 年iOS开发者的自我总结,以及5年开发经历和感想!
  • 用mpvue开发微信小程序
  • Unity3D - 异步加载游戏场景与异步加载游戏资源进度条 ...
  • 浅谈sql中的in与not in,exists与not exists的区别
  • 数据库巡检项
  • ​软考-高级-系统架构设计师教程(清华第2版)【第20章 系统架构设计师论文写作要点(P717~728)-思维导图】​
  • # centos7下FFmpeg环境部署记录
  • (C语言版)链表(三)——实现双向链表创建、删除、插入、释放内存等简单操作...
  • (Java实习生)每日10道面试题打卡——JavaWeb篇
  • (附源码)springboot宠物医疗服务网站 毕业设计688413
  • (附源码)计算机毕业设计大学生兼职系统
  • (三)elasticsearch 源码之启动流程分析
  • (转)程序员技术练级攻略
  • (转载)VS2010/MFC编程入门之三十四(菜单:VS2010菜单资源详解)
  • .NET MVC、 WebAPI、 WebService【ws】、NVVM、WCF、Remoting
  • .NET MVC第五章、模型绑定获取表单数据
  • .net on S60 ---- Net60 1.1发布 支持VS2008以及新的特性
  • .NET 中使用 Mutex 进行跨越进程边界的同步
  • .Net(C#)常用转换byte转uint32、byte转float等
  • .net获取当前url各种属性(文件名、参数、域名 等)的方法
  • .net连接oracle数据库
  • .net网站发布-允许更新此预编译站点
  • .NET下ASPX编程的几个小问题