android USB Host

合集下载

安卓鼠标驱动

安卓鼠标驱动

安卓⿏标驱动linux驱动由浅⼊深系列:usb⼦系统之四(android平台android 个⼈分类:版权声明:本⽂为博主原创⽂章,未经博主允许不得转载。

如本⽂对您有帮助,欢迎点赞评论。

https:///RadianceBlau/article/details/78275434android上的usb⼝是⽀持OTG(on the go)的,USB OTG既可以作为Host⼜可以作为Device,我们本⽂来看⼀下android⼿机作为Host连接⿏标的情况。

OTG是如何做到既可以做Host⼜可以作为Device的呢标准usb接头中有四根线:vbus,gnd,dp(d+),dm(d-),android⼿机上的usb为miniUSB接⼝增加了⼀根id线,⽤来区分Host、Device。

usb是如何检测设备插⼊的呢设备插拔检测都是由hub来进⾏的,即使不外接hub在USB host controler中也集成了⼀个roothub。

hub上的dp、dm线都有⼀个15k的下拉电阻拉到低电平,设备端的dp或dm线上有1.5k的上拉电阻,设备插⼊时就会改变dp、dm线上的电平。

当把⼀个USB设备插⼊到⼀个usb hub的某个端⼝时,集中器就会检测到设备的接⼊,从⽽在下⼀次受到主机通过中断交互查询时就会向其报告。

集中器的端⼝在没有设备接⼊时都处于关闭状态,插⼊设备之后也不会⾃动打开,必须由主机通过控制交互发出命令予以打开。

所以,在得到集中器的报告之后,主机的USB驱动程序就会为新插⼊的设备调度若⼲个控制交互,并向集中器发出打开这个端⼝的命令,这样新插⼊的设备就会出现在USB总线上了,并为该设备分配唯⼀的地址。

⿏标插⼊android⼿机后代码执⾏过程分析1,usb⿏标属于hid设备,linux启动过程中会注册hid总线bus_register(&hid_bus_type)drivers/hid/hid-core.cstatic int __init hid_init(void){int ret;ret = bus_register(&hid_bus_type);ret = hidraw_init();return 0;}2,usb⿏标插⼊后的会调⽤到hub_port_connect()drivers\usb\core\hub.cstatic void hub_port_connect(struct usb_hub *hub, int port1, u16 portstatus,u16 portchange){int status, i;unsigned unit_load;struct usb_device *hdev = hub->hdev;struct usb_hcd *hcd = bus_to_hcd(hdev->bus);struct usb_port *port_dev = hub->ports[port1 - 1];struct usb_device *udev = port_dev->child;static int unreliable_port = -1;printk("radia hub_port_connect\n");//////////////////添加logstatus = 0;for (i = 0; i < SET_CONFIG_TRIES; i++) {/* reallocate for each attempt, since references* to the previous one can escape in various ways*/udev = usb_alloc_dev(hdev, hdev->bus, port1);////////////////创建⼀个usb_device设备if (!udev) {dev_err(&port_dev->dev,"couldn't allocate usb_device\n");goto done;}......../* Run it through the hoops (find a driver, etc) */if (!status) {status = usb_new_device(udev);////////////////////////调⽤usb_new_device-->usb_enumerate_device枚举设备if (status) {mutex_lock(&usb_port_peer_mutex);spin_lock_irq(&device_state_lock);port_dev->child = NULL;spin_unlock_irq(&device_state_lock);mutex_unlock(&usb_port_peer_mutex);} else {if (hcd->usb_phy && !hdev->parent)usb_phy_notify_connect(hcd->usb_phy,udev->speed);}}}其中会调⽤usb_alloc_dev创建⼀个usb_device设备,然后调⽤usb_new_device-->usb_enumerate_device-->usb_get_configuration-->usb_parse_configuration-->usb_parse_interface(会分配struct usb_interface_cache)-->usb_parse_endpoint分析设备各描述符,最后usb_new_device会调⽤device_add 这⾥把这个usb_device注册到usb总线下。

CH341PAR_Android 库接口说明

CH341PAR_Android 库接口说明

CH341PAR Android JAR库接口说明版本: V1.00CH341PAR Android JAR库接口说明版本: 1简介CH341是一个USB总线的转接芯片,通过USB总线提供异步UART、并口、常用的2线和4线同步串行接口等方式。

并口方式下,提供了EPP/MEM 8位并行接口,而常用的同步串行接口主要包含2线IIC、4线SPI等。

本文档主要介绍CH341USB转EPP、MEM、IIC、SPI模式(以下简称CH341PAR)操作的Java Driver 库,以及Android下如何使用APK操作CH341PAR实现数据通讯。

该驱动基于Android USB Host协议完成,用户可调用所提供的相关接口API实现与Android USB Host的通讯。

CH341PAR提供的库需要满足以下两个条件方可实现数据通讯:1、Android 3.1及以上系统版本;2、Android端具有USB Host或OTG接口。

本文档将会重点说明Android USB Host与CH341建立通讯机制的Java包API以及我司提供的演示程序的操作说明。

关于Android USB Host协议说明,可以参考Google官方文档。

1、Android USB Host本文档所描述的演示程序皆是针对Android 3.1及以上版本系统。

Android 应用程序的启动参数是定义在device_filter.xml文件中的product-id和vendor-id。

基于CH341PAR开发的Android应用程序主要分为两个部分,如下图:图1.1 CH341PAR Android ApplicationUser Layout:主要是由用户根据自己的需求完成相关的代码,通过调用CH341PAR相关的接口函数实现EPP、MEM、IIC、SPI的通讯方式。

我司所提供的例程基于Fragment结构设计,在Android手机或平板上会呈现出不同的主界面。

安卓手机host修改方法

安卓手机host修改方法

安卓手机host所在目录:/system/etc/hosts
修改方法:
1.手机root。

修改安卓系统文件必须要有root权限。

打开手机的usb调试,根据机型系统不同,选项位置可能不同。

Root最好根据相应机型使用对应的root工具,网上一键root助手大师也有很多。

2.打开host文件
可以连接电脑,然后将host文件复制到电脑,用电脑对host文件进行编辑。

编辑后复制到原目录覆盖原文件。

或者对手机上文件浏览器(建议re浏览器)开启root授权,然后通过管理器进入相应目录,进行host文件编辑(文本编辑器或脚本编辑器打开)。

建议编辑前对hosts文件进行备份。

USBOTG模式和HOST模式

USBOTG模式和HOST模式

USBOTG模式和HOST模式
Host
USB是由Host端控制整个总线的数据传输的。

单个USB总线上,只能有⼀个Host。

OTG
On The Go,这是在USB2.0引⼊的⼀种mode,提出了⼀个新的概念叫主机协商协议(Host Negotiation Protocol),允许两个设备间商量谁去当Host
USB设备分为HOST(主设备)和SLAVE(从设备),只有当⼀台HOST与⼀台SLAVE连接时,才能实现数据的传输。

B HOST是指主机
B OTG 设备既能当主机,⼜能做设备。

OTG技术就是实现没有HOST的情况下,实现从设备间的数据传输。

USB_ID:输⼊信号,由 USB OTG 协议定义,⽤于识别 USB ⼝所接设备的默认⾓⾊(host or device)。

USB_ID 默认上拉,处于 device 状况,如果要控制器进⼊ host 状态,需外接 mini-A ⼝或 micro-A ⼝将 USB_ID 短接到地。

也可以由软件进⾏强制切换
0: 由硬件即USB ID决定
1:强制 host模式
2:强制 device模式
USB OTG接⼝中有5条线:
2条⽤来传送数据(D+ 、D-);
1条是电源线(VBUS);
1条则是接地线(GND)、
1条是ID线。

ID线—以⽤于识别不同的电缆端点,mini-A插头(即A外设)中的ID引脚接地,mini-B插头(即B外设)中的ID引脚浮空。

当OTG 设备检测到接地的ID引脚时,表⽰默认的是A设备(主机),⽽检测到ID引脚浮空的设备则认为是B设备(外设)。

USB HOST线制作方法

USB HOST线制作方法

USB HOST线制作方法
一、材料准备
1、在电脑城电子市场买个 5PIN 的 MINI USB 插头和带接 USB 设备母口的线材
2、让我们再温习一下 USB HOST 线中插座的定义:
根据 E860MM 的介绍,主机端只需要将 ID 与 GND 短路就可以了。

3、我们手上 5 PIN 的 MINI USB 接口的插座和对应的连线
4、由上面的图,把黑、绿、红、白四根线分别焊接在对应的接脚上,再把 ID 和 GND 焊在一起短路。

在焊接的时候,注意不要四条线不要短路了~~:)
(第一次玩烙铁焊东东,焊的很丑,见笑了~ *^_^* )
5、焊好检查无误后点上热熔胶或绝缘胶布之类材料,防止线之前短路和与金属外壳的短路。

然后装上 MINI USB 口的金属壳,不管里面焊的如何丑陋,出现的依然是一个漂亮的 MINI USB 头,这样,整条红就做好了。

6、把 MINI 口插在 E850 上,另一端接上 U 盘, U 盘上的灯马上就亮了,这时打开 E850 的资源管理器――我的设备,会发现小 E 已经找到了“硬盘”。

至此, USB HOST 线制作算是成功了。

或许有的 U 盘并不会被 E850 支持,大家可以在小 E 上装一个万能 USB 设备驱动,让小 E 可以支持更多的 USB 设备: U 盘、 USB 游戏手柄, USB 键盘。

USB Host介绍与使用

USB Host介绍与使用

USB Host介绍与使用一几个名词的含义USB device:从硬件角度看就是一个带有usb client控制器的设备;从软件角度看,就是一个挂在usb总线上的一个普通意义上的设备,只不过它们的驱动是基于host驱动之上的。

USB host:USB主设备,可以从另外一个USB device中取得数据,包括USB host控制器和USB host协议。

与USB device或USB slave相对应。

USB client:从硬件角度看就是指USB client 控制器,从软件角度看,就是指USB client协议,与USB host协议相对应。

USB OTG:On The Go,正在进行中的意思,也就是可以直接传输,就是可以从一个机器直接传到另一个机器中。

USB HUB:USB扩展/集线器,一种可以将一个USB接口扩展为多个(通常为4个),并可以使这些接口同时使用的装置。

二 USB HOST技术简介USB的通信可以用下图表示。

下图中,左半部分为USB主机端,可以看出,USB主机端由两部分构成,即软件体和硬件体。

实际上是三个软件组件组成了USB HOST解决方案,即USB 客户驱动程序、USB驱动程序和USB主机控制器驱动程序。

应用程序的事务处理是由USB客户驱动程序(设备驱动程序)启动时,客户驱动程序把USB设备当作一个可以被访问的端点集合,它可以被控制并与它的功能单元进行通信。

USB系统软件包括USB驱动程序和USB主控制器驱动程序,USB驱动程序负责配置管理、用户管理、总线管理和数据传输管理;以及数据的位编码、封包、循环校验、发送、错误处理等。

三 USB host实现简单实现:MCU+USB控制器(若MCU中已经包含USB OTG则无需控制器,比如LPC2478,内部包含USB OTG)。

例如下图是由微控制器MSP430F149和USB控制器ISP1161实现USB HOST的电路。

ISP1161是Philips设计的USB主机/设备控制器。

在USB中USBHOST是通过各种描述符来识别设备的

在USB中USBHOST是通过各种描述符来识别设备的

USB HID报告及报告描述符简介在USB中,USB HOST是通过各种描述符来识别设备的,有设备描述符,配置描述符,接口描述符,端点描述符,字符串描述符,报告描述符等等。

USB报告描述符(Report Descriptor)是HID设备中的一个描述符,它是比较复杂的一个描述符。

USB HID设备是通过报告来给传送数据的,报告有输入报告和输出报告。

输入报告是USB设备发送给主机的,例如USB鼠标将鼠标移动和鼠标点击等信息返回给电脑,键盘将按键数据数据返回给电脑等;输出报告是主机发送给USB 设备的,例如键盘上的数字键盘锁定灯和大写字母锁定灯等。

报告是一个数据包,里面包含的是所要传送的数据。

输入报告是通过中断输入端点输入的,而输出报告有点区别,当没有中断输出端点时,可以通过控制输出端点0发送,当有中断输出端点时,通过中断输出端点发出。

而报告描述符,是描述一个报告以及报告里面的数据是用来干什么用的。

通过它,USB HOST可以分析出报告里面的数据所表示的意思。

它通过控制输入端点0返回,主机使用获取报告描述符命令来获取报告描述符,注意这个请求是发送到接口的,而不是到设备。

一个报告描述符可以描述多个报告,不同的报告通过报告ID来识别,报告ID在报告最前面,即第一个字节。

当报告描述符中没有规定报告ID时,报告中就没有ID字段,开始就是数据。

更详细的说明请参看USB HID协议,该协议可从下载。

USB报告描述符可以通过使用HID Descriptor tool来生成,这个工具可以到下载,为了方便大家,我顺便上传了一份。

下面通过由HID Descriptor tool生成的USB鼠标和USB键盘来说明一下报告描述符和报告。

code char KeyBoardReportDescriptor[63] = {//表示用途页为通用桌面设备0x05, 0x01, // USAGE_PAGE (Generic Desktop)//表示用途为键盘0x09, 0x06, // USAGE (Keyboard)//表示应用集合,必须要以END_COLLECTION来结束它,见最后的//END_COLLECTION0xa1, 0x01, // COLLECTION (Application)//表示用途页为按键0x05, 0x07, // USAGE_PAGE (Keyboard)//用途最小值,这里为左ctrl键0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl)//用途最大值,这里为右GUI键,即window键0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI)//逻辑最小值为00x15, 0x00, // LOGICAL_MINIMUM (0)//逻辑最大值为10x25, 0x01, // LOGICAL_MAXIMUM (1)//报告大小(即这个字段的宽度)为1bit,所以前面的逻辑最小值为0,逻辑最大值为10x75, 0x01, // REPORT_SIZE (1)//报告的个数为8,即总共有8个bits0x95, 0x08, // REPORT_COUNT (8)//输入用,变量,值,绝对值。

Androidusb设备权限查询及自动获取详解流程

Androidusb设备权限查询及自动获取详解流程

Androidusb设备权限查询及⾃动获取详解流程看到当上⾯的对话框弹出时,可以使⽤命令查看顶层的活动窗⼝adb shell dumpsys window | findstr mCurrentFocusmCurrentFocus=Window{41ab0ee0 u0 com.android.systemui/bPermissionActivity}这就是应⽤的位置,当然我们也可以是⽤grep命令来查找这个对话框的.xml⽂件,进⼊android源码然后输⼊命令:grep '默认情况下⽤于' ./ -Rn./SystemUI/res/values-zh-rCN/strings.xml:51: <string name="always_use_device" msgid="1450287437017315906">"默认情况下⽤于该 USB 设备"</string>./SystemUI/res/values-zh-rCN/strings.xml:52: <string name="always_use_accessory" msgid="1210954576979621596">"默认情况下⽤于该 USB 配件"</string>那么这个对话框的路径在/android/frameworks/base/packages/SystemUI/res/values-zh-rCN/strings.xml其相关的内容如下:<string name="always_use_device" msgid="1450287437017315906">"默认情况下⽤于该 USB 设备"</string><string name="usb_device_permission_prompt" msgid="834698001271562057">"允许应⽤“<xliff:g id="APPLICATION">%1$s</xliff:g>”访问该 USB 设备吗?"相关应⽤路径找到.java⽂件来修改,其位置在:/android/frameworks/base/packages/SystemUI/src/com/android/systemui/usb/UsbPermissionActivity.java这就是那个讨厌的对话框对应的java程序,那么来看看这个程序如下:/** Copyright (C) 2011 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** /licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package b;import android.app.AlertDialog;import android.app.PendingIntent;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.ApplicationInfo;import android.content.pm.PackageManager;import b.IUsbManager;import bAccessory;import bDevice;import bManager;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.os.ServiceManager;import erHandle;import android.util.Log;import youtInflater;import android.view.View;import android.widget.CheckBox;import poundButton;import android.widget.TextView;import com.android.internal.app.AlertActivity;import com.android.internal.app.AlertController;import com.android.systemui.R;public class UsbPermissionActivity extends AlertActivityimplements DialogInterface.OnClickListener, CheckBox.OnCheckedChangeListener {private static final String TAG = "UsbPermissionActivity";private CheckBox mAlwaysUse;private TextView mClearDefaultHint;private UsbDevice mDevice;private UsbAccessory mAccessory;private PendingIntent mPendingIntent;private String mPackageName;private int mUid;private boolean mPermissionGranted;private UsbDisconnectedReceiver mDisconnectedReceiver;@Overridepublic void onCreate(Bundle icicle) {super.onCreate(icicle);Intent intent = getIntent();mDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);mAccessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); mPendingIntent = (PendingIntent)intent.getParcelableExtra(Intent.EXTRA_INTENT);mUid = intent.getIntExtra(Intent.EXTRA_UID, -1);mPackageName = intent.getStringExtra("package");Log.e(TAG, "mPackageName "+ mPackageName);Log.e(TAG, "mUid "+ mUid);PackageManager packageManager = getPackageManager();ApplicationInfo aInfo;try {aInfo = packageManager.getApplicationInfo(mPackageName, 0);} catch (NotFoundException e) {Log.e(TAG, "unable to look up package name", e);finish();return;}String appName = aInfo.loadLabel(packageManager).toString();Log.e(TAG, "appName "+ appName);final AlertController.AlertParams ap = mAlertParams;ap.mIcon = aInfo.loadIcon(packageManager);ap.mTitle = appName;if (mDevice == null) {ap.mMessage = getString(b_accessory_permission_prompt, appName);mDisconnectedReceiver = new UsbDisconnectedReceiver(this, mAccessory);} else {ap.mMessage = getString(b_device_permission_prompt, appName);mDisconnectedReceiver = new UsbDisconnectedReceiver(this, mDevice);}ap.mPositiveButtonText = getString(android.R.string.ok);ap.mNegativeButtonText = getString(android.R.string.cancel);ap.mPositiveButtonListener = this;ap.mNegativeButtonListener = this;// add "always use" checkboxLayoutInflater inflater = (LayoutInflater)getSystemService(YOUT_INFLATER_SERVICE);ap.mView = inflater.inflate(yout.always_use_checkbox, null);mAlwaysUse = (CheckBox)ap.mView.findViewById(com.android.internal.R.id.alwaysUse);if (mDevice == null) {mAlwaysUse.setText(R.string.always_use_accessory);} else {mAlwaysUse.setText(R.string.always_use_device);}mAlwaysUse.setOnCheckedChangeListener(this);mClearDefaultHint = (TextView)ap.mView.findViewById(com.android.internal.R.id.clearDefaultHint);mClearDefaultHint.setVisibility(View.GONE);if(!mPackageName.equals("bcamera"))setupAlert();else{mPermissionGranted = true;finish();}}@Overridepublic void onDestroy() {IBinder b = ServiceManager.getService(USB_SERVICE);IUsbManager service = IUsbManager.Stub.asInterface(b);// send response via pending intentIntent intent = new Intent();try {if (mDevice != null) {intent.putExtra(UsbManager.EXTRA_DEVICE, mDevice);if (mPermissionGranted) {service.grantDevicePermission(mDevice, mUid);if (mAlwaysUse.isChecked()) {final int userId = UserHandle.getUserId(mUid);service.setDevicePackage(mDevice, mPackageName, userId);}}}if (mAccessory != null) {intent.putExtra(UsbManager.EXTRA_ACCESSORY, mAccessory);if (mPermissionGranted) {service.grantAccessoryPermission(mAccessory, mUid);if (mAlwaysUse.isChecked()) {final int userId = UserHandle.getUserId(mUid);service.setAccessoryPackage(mAccessory, mPackageName, userId);}}}intent.putExtra(UsbManager.EXTRA_PERMISSION_GRANTED, mPermissionGranted); mPendingIntent.send(this, 0, intent);} catch (PendingIntent.CanceledException e) {Log.w(TAG, "PendingIntent was cancelled");} catch (RemoteException e) {Log.e(TAG, "IUsbService connection failed", e);}if (mDisconnectedReceiver != null) {unregisterReceiver(mDisconnectedReceiver);}super.onDestroy();}public void onClick(DialogInterface dialog, int which) {if (which == AlertDialog.BUTTON_POSITIVE) {mPermissionGranted = true;}finish();}public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {if (mClearDefaultHint == null) return;if(isChecked) {mClearDefaultHint.setVisibility(View.VISIBLE);} else {mClearDefaultHint.setVisibility(View.GONE);}}}这段代码是获取应⽤的包名,我们可以通过包名对⽐来决定是否弹出对话框。

android通过usb读取U盘的方法

android通过usb读取U盘的方法

android通过usb读取U盘的⽅法本⽂实例为⼤家分享了android通过usb读取U盘的具体代码,供⼤家参考,具体内容如下1.关联 compile ‘com.github.mjdev:libaums:+'2.权限设置<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="b.host" android:required="false" /><uses-feature android:name="b.host" android:required="true" />3.监听u盘插⼊拔出的⼴播//监听otg插⼊拔出IntentFilter usbDeviceStateFilter = new IntentFilter();usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);mContext.registerReceiver(UDiskMountedReceiver, usbDeviceStateFilter);//注册监听⾃定义⼴播IntentFilter filter = new IntentFilter(Constant.ACTION_USB_PERMISSION);mContext.registerReceiver(UDiskMountedReceiver, filter);4.代码package btest;/*** @项⽬名: UsbTest* @包名: btest* @⽂件名: ReadUDisk* @创建者: 25934* @创建时间: 2018-07-24 13:50* @描述: TODO*/import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import bManager;import android.util.Log;import bMassStorageDevice;import com.github.mjdev.libaums.fs.FileSystem;import bFile;import com.github.mjdev.libaums.partition.Partition;import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import parator;import java.util.List;import static btest.Constant.ACTION_USB_PERMISSION;public class ReadUDisk {private UDiskCallBack.OnUDiskCallBack mOnUDiskCallBack = null;private Context mContext;private UsbMassStorageDevice[] storageDevices;private List<UsbFile> usbFiles = new ArrayList<>();private final UsbManager mUsbManager;public ReadUDisk(Context context) {mContext = context;mUsbManager = (UsbManager) mContext.getSystemService(B_SERVICE);}/*** 接受U盘插⼊和拔出事件* @param onUDiskCallBack*/public void setOnUDiskCallBack(UDiskCallBack.OnUDiskCallBack onUDiskCallBack) {if (mOnUDiskCallBack == null) {registerReceiver();mOnUDiskCallBack = onUDiskCallBack;}}/*** 注册⼴播接收者*/public void registerReceiver() {//监听otg插⼊拔出IntentFilter usbDeviceStateFilter = new IntentFilter();usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);mContext.registerReceiver(UDiskMountedReceiver, usbDeviceStateFilter);//注册监听⾃定义⼴播IntentFilter filter = new IntentFilter(Constant.ACTION_USB_PERMISSION);mContext.registerReceiver(UDiskMountedReceiver, filter);Log.e("ReadUDisk", "registerReceiver: ");}/*** 注销⼴播接收者*/public void unReisterReceiver() {if (UDiskMountedReceiver != null) {mContext.unregisterReceiver(UDiskMountedReceiver);}}/*** 检查usb设备的权限* @param device* @return*/public boolean checkPerssion(UsbMassStorageDevice device) {if (mUsbManager==null){return false;}if (mUsbManager.hasPermission(device.getUsbDevice())) {//有就直接读取设备是否有权限return true;} else {return false;}}/*** 读取当前usb设备的数量* @return*/public int getDeviceCount() {//获取存储设备UsbMassStorageDevice[] storageDevices =UsbMassStorageDevice.getMassStorageDevices(mContext); return storageDevices.length;}/*** 根据position获取usb设备* @param position* @return*/public UsbMassStorageDevice getUsbMassDevice(int position) {//获取存储设备UsbMassStorageDevice[] storageDevices =UsbMassStorageDevice.getMassStorageDevices(mContext); if (position > storageDevices.length) {return null;} else {return storageDevices[position];}}/*** 获取usb上所有的存储设备* @return*/public UsbMassStorageDevice[] getUsbMassAllDevice() {//获取存储设备UsbMassStorageDevice[] storageDevices =UsbMassStorageDevice.getMassStorageDevices(mContext);return storageDevices;}/*** 根据设备获取路径* @param device* @return*/public FileSystem readDevice(UsbMassStorageDevice device) {try {if (!checkPerssion(device)){ //检查是否有权限return null;}device.init();//使⽤设备之前需要进⾏初始化Partition partition = device.getPartitions().get(0); //仅使⽤设备的第⼀个分区FileSystem currentFs = partition.getFileSystem();// currentFs.getCapacity(); //容量⼤⼩// currentFs.getOccupiedSpace(); //已使⽤⼤⼩// currentFs.getFreeSpace(); //未使⽤的⼤⼩UsbFile root = currentFs.getRootDirectory();//获取根⽬录String deviceName = currentFs.getVolumeLabel();//获取设备标签return currentFs;} catch (Exception e) {e.printStackTrace();return null;}}/*** 获取U盘的⽂件和⽂件夹路径* @param fileSystem* @return*/public List<UsbFile> getUsbFiles(FileSystem fileSystem) {usbFiles.clear();try {for (UsbFile file : fileSystem.getRootDirectory().listFiles()) { //将所以⽂件和⽂件夹路径添加到usbFiles数组中usbFiles.add(file);}Collections.sort(usbFiles, new Comparator<UsbFile>() {//简单排序⽂件夹在前⽂件在后 @Overridepublic int compare(UsbFile oFile1, UsbFile oFile2) {return oFile1.isDirectory()-1: 1;}});} catch (IOException e) {e.printStackTrace();}return usbFiles;}private BroadcastReceiver UDiskMountedReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();switch (action) {case ACTION_USB_PERMISSION: //⾃定义权限⼴播if (mOnUDiskCallBack != null) {mOnUDiskCallBack.onPermissionCallBack();}break;case UsbManager.ACTION_USB_DEVICE_ATTACHED: //usb设备插⼊⼴播if (mOnUDiskCallBack != null) {mOnUDiskCallBack.onAttachDeviceCallBack();}break;case UsbManager.ACTION_USB_DEVICE_DETACHED: //usb设备拔出⼴播if (mOnUDiskCallBack != null) {mOnUDiskCallBack.onDetachDeviceCallBack();}break;}}};}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

Android通过两种模式来支持各种USB外设和Android USB配件

Android通过两种模式来支持各种USB外设和Android USB配件

Android 通过两种模式来支持各种 USB 外设和 Android USB 配件(指那些符合 Android 附件协议的 硬件) :USB 配件和 USB 主机。

在 USB 配件的模式之下,外部的 USB 配件就像 USB 主机那样。

这 种配件可以包括机器人控制器,基站连接器,医疗和音乐设备,电话亭以及读卡器这样很多的设备。

这样就使得那些搭载 Android 系统的设备不需要具备主机的特性就可以和 USB 硬件进行交互。

Android USB 配件是指那些专门用来为搭载 Android 系统的设备工作以及符合 Android 附件通信协议 的设备。

在 USB 主机的模式之下, 搭载 Android 的设备就像主机那样工作。

这些设备包括数码相机, 键盘,鼠标以及游戏控制器。

Android USB 设备被设计成具有广泛的应用领域,可以很好的完成人机 互动应用的通信设备。

图 1 就显示了这两种模式的区别。

当搭载 Android 系统的设备处于主机的模式下,它就充当 USB 主机 并且为总线提供能源。

而当搭载 Android 系统的设备处于 USB 配件的模式下时,连接的 USB 硬件(这 种情况下,指的是一个 Android USB 配件)作为主机一样并且为总线提供能源。

在 Android3.1(API12 级)或较新的平台直接支持 USB 配件和主机模式。

USB 配件模式以一个附加 的类库的方式支持范围更广的设备 被移植到 Android 2.3.4(API10 级)。

设备生产商可以决定是否在 系统镜像上附加这个类库。

注意:支持 USB 主机和配件模式主要取决于设备的硬件,而不是平台的等级。

你可以通过一个 [[<uses-feature>]]元素来为设备进行过滤以支持 USB 主机和配件。

看这个 USB 配件和主机文档来 了解更多的详情。

调试注意事项当用 USB 主机或者配件调试应用程序时,你最好有连接到搭载 Android 程序的设备的 USB 硬件。

USBHOST与USBOTG的区别是什么功能上有什么差异

USBHOST与USBOTG的区别是什么功能上有什么差异

这个解释起‎来好麻烦,‎l z慢慢看‎简单地‎说,OTG‎就是On ‎T he G‎o,正在进‎行中的意思‎,也就是可‎以直接传输‎,就是可以‎从一个机器‎直接传到另‎一个机器中‎,举个例子‎未来的一‎天,我拿着‎M EIZU‎最新产品“‎E X”来到‎学校,听着‎“EX”里‎面装着的我‎最新下载的‎一首新歌,‎我的一个好‎朋友夺下我‎的耳塞想听‎听这首歌,‎她一边听一‎边陶醉地说‎:“我找这‎首歌已经很‎久了,可是‎一直都没有‎能down‎l oad到‎,你是在哪‎儿找到的?‎??”我笑‎着要她拿出‎她的Mp3‎,同时我从‎钥匙扣上取‎下一条便携‎的数据线,‎数据线的一‎头插在“E‎X”上,另‎一头插在她‎的Mp3上‎,我打开“‎E X”的菜‎单,选中了‎基于OTG‎技术的传输‎模式,直接‎将这首好听‎但是难找的‎歌“拷”到‎了她Mp3‎上,她非常‎惊讶,直到‎她在自己的‎M p3上听‎到了这首歌‎才相信这一‎切都是是真‎的……,呵‎呵呵‎usb ‎h ost ‎‎ US‎B设备分为‎H OST(‎主设备)和‎S LAVE‎(从设备)‎,只有当一‎台HOST‎与一台SL‎A VE连接‎时才能实现‎数据的传输‎。

简单‎的说,如果‎一个数码设‎备支持US‎B HOS‎T,那么它‎就可以从另‎外一个US‎B设备中取‎得数据。

‎U SB H‎O ST线可‎以使得很多‎智能手机支‎持连接鼠标‎、键盘、硬‎盘、U盘、‎M P3、U‎S B游戏手‎柄、USB‎HUB、‎U SB网卡‎、USB打‎印机、手机‎、USB ‎S IM手机‎卡读卡器等‎一堆设备,‎好处多多‎所以一‎句话来说:‎一般情况下‎OTG和‎H OST的‎区别就是h‎o st支持‎的东西多一‎点,otg‎传输方便点‎,不需要别‎的机器上有‎从设备的接‎口就能传输‎,就说真‎么多了‎什‎么是usb‎host‎?US‎B是英文U‎n iver‎s al S‎e rial‎Bus的‎缩写,中文‎含义是“通‎用串行总线‎”。

在USB中USBHOST是通过各种描述符来识别设备的

在USB中USBHOST是通过各种描述符来识别设备的

在USB中USBHOST是通过各种描述符来识别设备的随着技术的不断发展, USB(通用串行总线)已经成为了连接各种设备的主要方式。

在 USB 中,USBHOST 是用于识别、管理和连接 USB 设备的主机端,而 USB 设备则是被动接受主机指令并执行操作的从属端。

在 USBHOST 与设备之间的通讯过程中,USBHOST 首先需要对设备进行识别,然后才能对其进行管理和使用。

本文将介绍 USBHOST 是如何通过各种描述符来识别设备的。

什么是 USB 描述符?在 USB 中,描述符起着至关重要的作用。

USB 描述符是用于描述 USB 设备的结构,可以理解成USB 设备的一份数据结构,包含了设备的基本信息、功能特点、支持的协议和接口等信息。

插入 USB 设备后,USBHOST 会从设备中读取一些关键的描述符,通过这些描述符,USBHOST 可以识别出连接的设备,并以正确的方式进行管理和控制。

USB 描述符分为设备描述符、配置描述符、接口描述符等。

其中,设备描述符是必须的;而配置描述符和接口描述符则是通过设备描述符间接引用的。

下面将详细介绍每种描述符的作用和结构。

设备描述符设备描述符是用于描述USB 设备的基本信息,包括设备的供应商ID、产品ID、设备版本号、设备类等。

设备描述符有18个字节长,其中,字节1为描述符的长度,字节2为描述符类型(值为0x01表示设备描述符),字节3和字节4表示USB规范的版本号。

字节5和字节6表示USB设备的类别、子类别和协议码,字节7为USB设备可处理的最大数据包大小,字节8为设备的厂商ID,字节9为设备的产品ID,字节10和11为设备的版本号,字节12至18为USB设备的其他描述符。

配置描述符配置描述符用于描述 USB 设备的配置信息,包括该配置的总长度、配置号、接口数、供电方式等。

配置描述符由配置描述符首部和接口描述符组成。

需要注意的是,在 USB 中,配置描述符中的一个设备可以包含多个接口描述符。

USB HOST与 USB OTG的区别是什么,功能上有什么差异

USB HOST与 USB OTG的区别是什么,功能上有什么差异

(2)作为A设备时,需要具有VBUS监视和供电电路;作为B设备初始化SRP时,需要监视和触发VBUS。
(3)具有ID输入引脚。作为两用OTG设备,ASIC、DSP或其它与收发器连接的电路必须具备充当外设和主机的功能,并应按照HNP协议转换其角色。
收发器所需添加的大多数电路用于VBUS引脚的管理。作为主机,它必须能够提供5V、输出电流可达8mA的电源。图3中的模拟开关用于配置收发器的各种功能。
ASIC和控制器还必须包含USB主机逻辑控制功能,包括发送SOF(帧启动)包、发送配置\u36755输入\u36755输出数据包,在USB 1 msec帧内确定传输进程、发送USB复位信号、提供USB电源管理等。
Maxim要提供的USB OTG方案
MAX3301E是Maxim公司研制的一款USB OTG收发器,该器件集成有电荷泵,可将PDA、蜂窝电话和数码相机等移动设备与USB外设直接连接而无需PC机的参与。采用MAX3301E和一个嵌入式USB主机,就可直接将诸如打印机或外部硬盘驱动器这样的外设连接。MAX3301E内部包括USB OTG收发器、UBUS电荷泵、线性稳压器和I2C 2线串行接口。内部电平转换器使MAX3301E能够与采用+1.65至+3.6V逻辑电源电压的器件连接。MAX3301E中的电荷泵工作在+3V至+4.5V输入电源下,可产生符合OTG要求的VBUS输出,且输出电流大于8mA。该器件可利用内部比较器控制并测量VBUS,同时支持USB OTG SRP和HNP。
这个解释起来好麻烦,lz慢慢看
简单地说,OTG就是On The Go,正在进行中的意思,也就是可以直接传输,就是可以从一个机器直接传到另一个机器中,举个例子 未来的一天,我拿着MEIZU最新产品“EX”来到学校,听着“EX”里面装着的我最新下载的一首新歌,我的一个好朋友夺下我的耳塞想听听这首歌,她一边听一边陶醉地说:“我找这首歌已经很久了,可是一直都没有能download到,你是在哪儿找到的???”我笑着要她拿出她的Mp3,同时我从钥匙扣上取下一条便携的数据线,数据线的一头插在“EX”上,另一头插在她的Mp3上,我打开“EX”的菜单,选中了基于OTG技术的传输模式,直接将这首好听但是难找的歌“拷”到了她Mp3上,她非常惊讶,直到她在自己的Mp3上听到了这首歌才相信这一切都是是真的……,呵呵呵

蓝牙 hid

蓝牙 hid

Android USB Host与HID通讯(一)去年9月份来到现在的公司,接到新公司的第一个项目就是Android USB Host与HID通讯,当时也什么都不懂,就拿着google的api 开发指南(/guide/topics/connectivity/usb/host.html)反复的阅读反复的实验,网上的资料也只能发现/枚举到U盘等设备,进行HID通讯、数据传输的资料很少,当时老大给我的时间是整整一个月,听到这我说:我尽量…因为当时发了一两篇博文(Android USB Host 与HID 通讯方法),最近有些Android开发攻城师在我的博客问,说具体要怎么做,如何处理?但最近手上有一大堆TabletSystem Bug,下班后再也不想继续,就一直没怎么回复,今天周六公司调班,想干点别的,就跟大家一起交流交流Android USB Host与HID 通讯。

首先,大家如果想了解啥是USB Host,那大家还是自己去学习学习吧,多看些一手的资料,别总是穿二手鞋(这是前辈对我的忠告)。

跟我之前一样完全不知道Android USB Host的可以反复阅读下上面提到的google api 开发指南,我是反复的看了一遍又一遍,中文的英文的(英文有点戳),除了Host外,还有个Accessory,感兴趣的都可以了解下。

其次,当时公司给我的HID设备既有需要驱动的也有无驱的,而公司给我的板子没有相应的驱动。

只能发现无驱HID,若要发现有驱动的HID设备则需要另加上相应的设备驱动,否则你将无法发现你的HID设备。

至于,怎么添加相应的驱动,这就需要请教写驱动的攻城师同胞,暂时还未向这方面发展,以后有机会可以横向发展下。

先看看AndroidManifest.xml文件,对于刚接触最好从简单入手,在AndroidManifest.xml中加上intent-filter过滤器,可以先不做请求权限的处理,因为intent-filter方式可以自动请求权限。

USBHOST与USBOTG的区...

USBHOST与USBOTG的区...

USB HOST与 USB OTG的区别是什么,功能上有什么差异(What is the difference between USB HOST and USB OTG)Well, that's a lot of trouble. Lz looks at it slowlySay simply, OTG is On The Go, ongoing meaning, namely can directly transfer, is can be from one machine to another machine, for example The future one day, I took my MEIZU latest product "EX" came to the school, listen to the "EX" containing the latest I download a new song, one of my good friends took my earplugs to listen to this song, she listened to the side to say: "I have to find this song for a long time, but always can't download, where did you find it" I smiled and asked her to take out her Mp3 player, at the same time I removed one of the key chains, portable cable plug one end of the cable in the "EX", on the other side in her Mp3, I opened the "EX" menu, select the transfer mode, based on the technology of OTG directly to this nice but hard to find song "kao" in her Mp3 player, she was very surprised, until she heard the song on your Mp3 is to believe in all this is true... Ha ha ha,The usb host usb device is divided into host (main device) and SLAVE (from the device), which can only be transmitted when a host is connected to a SLAVE.Simply put, if a digital device supports USB HOST, it can get data from another USB device.USB HOST line can make many smartphones support to connect the mouse, keyboard, hard disk, U disk, MP3, USB gamepad, USB HUB, USB card, USB printer, such as mobile phones, USB SIM cardreader a heap of equipment, a lot of goodSo words: normally OTG what is the difference between the HOST and the HOST to support more, OTG transmission convenient point, do not need other machine interface can transfer from the device, he said that he really do itWhat is a usb host?USB is the abbreviation of Universal Serial Bus in English, which means "Universal Serial Bus". It is not a new bus standard, but an interface technology applied to the PC domain. USB was jointly proposed by Intel, compaq, IBM, Microsoft and other companies in late 1994. Until recently, however, it was widely used. Since November 11, 1994, when USB V0.7 was released, the USB version has been developing for many years, and now it has been developed as a 2.0 version, which has become the standard extension interface in computers. At present, the main board is mainly USB1.1 and USB2.0, which can be well compatible with each USB version. USB USES a 4 pin plug as the standard plug, and the use of the chrysanthemum chain can connect all the peripherals, can connect up to 127 external devices, and will not lose the bandwidth. USB requires the support of the host hardware, operating system and peripherals to work. The motherboard is generally using the chipset of supports USB function, also install a USB socket on the main board, and, except for the back of the socket on the motherboard have a USB pin reserved, can through the attachment received in front of the chassis as the front USB interface for use (note that should carefully read the motherboard manual when wiring and connection to drawing, never wrong and make the equipmentdamage).And the USB port can be connected by a special USB cable, and more interfaces can be extended through the Hub. USB has the transmission speed (USB1.1 is 12 MBPS, USB2.0 is 480 megabits per second), easy to use, support hot plug, flexible connection, independent power supply etc, and can connect the mouse, keyboard, printer, scanner, camera, USB flash disk, MP3 players, mobile phones, digital cameras, mobile hard disk, floppy disk, USB external light card, ADSL Modem, Cable Modem, etc., almost all the external devices.USB device into the HOST (master) and SLAVE () from the device, only when a HOST in a SLAVE connection to achieve data transmission, OTG equipment is our "EX" can act as the HOST, can act as a SLAVE.What is usb otg?USB1.0 standard since 1996, USB - the IF (Universal Serial Bus Implementers Forums) has released the USB1.0, USB and USB OTG specification, including USB transmission bandwidth up to 480 MBPS, and USB OTG more make the USB device to get rid of the limitation of the original master-slave architecture, realizes the end-to-end transmission mode, with the constant improvement of the USB specification, USB applications has been expanding. USB is to simplify the original of the birth of the computer and its peripherals connection, the first is to use on the keyboard and mouse, and now, the application of the USB is from PC peripherals across the electronics, consumer electronics and communication is the most significantapplications in digital cameras and other consumer electronics products. At present, USB low power consumption, easy connection and high speed transmission have made it a convenient application, and it has been used in combination with other technologies. For example, in mobile storage, the combination of USB and flash drive has created the current popular mobile storage device, the USB flash drive.USB OTG is The abbreviation of USB On - The - Go, is a technology developed in recent years, On December 18, 2001 by The USB Implementers Forum, or mobile device is mainly used in a variety of equipment, The connection between for data exchange. Especially pdas, mobile phones, consumer devices. The change of the digital camera, camera, printer, and other devices of various types of connectors, as many as 7 types of memory card data interchange inconvenience. The development of USB technology, makes the PC and peripheral devices can be made through a simple way, the moderate cost will be connected together, the above we mentioned application, can through the USB bus, as PC peripheral, under the control of the PC for data exchange. But this convenient exchange, once you leave the PC, can't operate on the USB port, because no device can act as a PC's Host. On - The - Go, OTG technology is to realize data transfer between devices without Host. For example, a digital camera connects directly to a printer, connects two devices to a USB port via OTG technology, and prints the photos immediately. It can also be used to send data from a digital camera through an OTG to a USB port. In the wild, there is no need to carry an expensive memory card or carry a portable computer."In-stat/MDR In February the statistics also show that In thenext few years USB OTG interface of peripheral devices will grow from $2002 In 2002 to 2007, 168 million, 1527 times growth. It can be seen that as the diversification of peripheral equipment and the demand of the high-speed transmission, future development trend of USB OTG 2.0 optimism." In terms of industry applications, Qualcomm inc. has announced that it will use the USB OTG in its latest 3G mobile phone baseband. Sony Electronics also announced that it will use the philips USB OTG chip to provide USB OTG connectivity for its latest portable devices. SONY CLIE is the first portable device in the industry that has a USB OTG feature that can be used to communicate with other USB devices. It is foreseeable that USB OTG will become the basic configuration function of future electronic products.Host communication protocol and dialog request protocolUSB OTG standard is fully compatible with the USB2.0 standard, adding power management (saving power consumption), which allows the device to be both a host and a peripheral operation (dual-use OTG). The OTG dual-purpose device is fully compliant with the USB2.0 standard, and can provide certain host detection capabilities, supporting the host communication protocol (HNP) and the dialogue request protocol (SRP). In OTG, the initial host device is called A device, and the peripherals are called B devices. The connection mode of the available cable determines the initial role. Is shown in figure 2 with the fifth ID determine the schematic diagram of the default host, dual-use equipment to use the new mini - AB outlet, which makes the mini - A plug, mini - B plug and mini - AB added the fifth socket pin (ID), to identify the different cable endpoint. The ID pin in the mini - A plug is grounded, and the ID in the mini-bplug is floating. When the OTG device detects the ID pin of the grounding, it is indicated that the default is A device (host), while the device that detects the ID pin float is considered to be B device (peripheral). Once the system is connected, OTG characters can be replaced. The host and peripherals adopt the new HNP, A device provides the VBUS power supply as the default host, and the bus, enumeration and configuration of B devices are detected when the device is connected. The second new protocol that the OTG standard adds to USB is called the dialog request protocol (SRP). SRP allows B devices to request A device to open VBUS power and initiate A conversation. An OTG dialogue can be used to determine the time of VBUS power supply through A device. It is also important to use A device to close the VBUS power supply to end A flash session to save power, which is very important in battery powered products. For example, when two cellular phones communicate with each other through A connection, A device connected to the electric utility's mini-a is A device, which is the host. The other is B device, which is peripheral. When USB communication is not required, A device can turn off the VBUS line when the B device detects the state and enters the work low consumption mode.The construction of OTG functionsCircuit shown in figure 3 shows the build OTG functions need to be added to the circuit on the basis of USB peripherals, universal serial bus (USB) controller in the circuit may be is a microprocessor and USB SIE (serial interface engine),It can also be an integrated mu P/USB chip or ASIC connected to a USB transceiver. Provide power supply for bus externaldevices need to have a 3.3 V voltage regulator output voltage, so as to logic circuit and the connection in the D + and D - 1500 Ωresistance to provide power supply pins. The upper pull resistance on D +, D - pins can send the signal to the host and indicate the speed of the equipment. The resistance up to D + means full speed running, and the resistance is pulled to D - indicating low speed operation. Other endpoints (including 15 k D + and D - Ω pulldown resistor) used to detect the state of resistance. Because USB design needs to provide hot plug function. Therefore, its ESD protection circuit is mainly used to provide protection for D +, D - and VBUS pins.In order to increase the dual-use function of OTG, it is necessary to extend the function of transceiver to make the OTG device both as a host and as a peripheral. And on the need to achieve the above functions, is added in the circuit shown in figure 3 D + and D - the 15 k Ωpulldown resistor and provide power supply for VBUS. In addition, the transceiver needs to have the following three conditions:(1) the upper and lower pull resistance of D + / D - line can be switched to provide peripheral and host functions.(2) as A device, A VBUS monitoring and supply circuit is required; When initializing SRP for B devices, you need to monitor and trigger the VBUS.(3) have ID input pins. As a dual-purpose OTG device, ASIC, DSP, or other circuits connected to transceivers must have functions as peripherals and hosts, and should be converted to the role of the HNP protocol.Most of the circuitry added to the transceiver is used for the management of VBUS pins. As the host, it must be able to provide 5V and output current to 8mA power. The analog switch in figure 3 is used to configure various functions of the transceiver.ASIC must also contain the USB host and controller logic control functions, including sending SOF (frame) packages, send configuration \ \ u36755 u36755 input and output data, to determine the transmission process in a USB 1 msec frame, send a USB reset signal and provide USB power management, etc.Maxim to provide USB OTG solutionMAX3301E is Maxim company developed a USB OTG transceiver, the device integrated with charge pump, to mobile devices such as pdas, cellular phones and digital cameras with USB peripherals connected directly without the participation of PC. Using MAX3301E and an embedded USB host, you can directly connect peripherals such as printers or external hard drives. The MAX3301E includes USB OTG transceiver, UBUS charge pump, linear voltage stabilizer and I2C 2 line serial interface. The internal level converter enables MAX3301E to be connected to a device with a + 1.65 to + 3.6 V logic power supply voltage. The charge pump in MAX3301E works in the input power of + 3V to + 4.5v, which can produce the VBUS output which conforms to OTG requirement, and the output current is greater than 8mA. The device can control and measure VBUS with an internal comparator, while supporting USB OTG SRP and HNP.。

USB host 工作流程

USB host 工作流程

USB枚举步骤USB协议定义了设备的6种状态,仅在枚举过程种,设备就经历了4个状态的迁移:上电状态(Powered),默认状态(Default),地址状态(Address)和配置状态(Configured)(其他两种是连接状态(Attached)和挂起状态(Suspend))。

Attached和Powered状态不难理解:当一个设备被正确插入到主机的USB接口时,就处于Attached(连接)的状态。

设备连接好了,USB主机识别了设备,同时没有对设备进行请求,USB 设备就处于Suspended(挂起)状态.下面步骤是Windows系统下典型的枚举过程,但是固件不能依此就认为所有的枚举操作都是按照这样一个流程行进。

设备必须在任何时候都能正确处理所有的主机请求.1. 用户把USB设备插入USB端口或给系统启动时设备上电这里指的USB端口指的是主机下的根hub或主机下行端口上的hub端口。

Hub给端口供电,连接着的设备处于上电状态。

2. Hub监测它各个端口数据线上(D+/D-)的电压在hub端,数据线D+和D-都有一个阻值在14.25k到24.8k的下拉电阻Rpd,而在设备端,D+(全速,高速)和D-(低速)上有一个1.5k的上拉电阻Rpu。

当设备插入到hub端口时,有上拉电阻的一根数据线被拉高到幅值的90%的电压(大致是3V)。

hub检测到它的一根数据线是高电平,就认为是有设备插入,并能根据是D+还是D-被拉高来判断到底是什么设备(全速/低速)插入端口(全速、高速设备的区分在后面的章节中描述)。

检测到设备后,hub继续给设备供电,但并不急于与设备进行USB传输。

3. Host了解连接的设备每个hub利用它自己的中断端点向主机报告它的各个端口的状态(对于这个过程,设备是看不到的,也不必关心),报告的内容只是hub端口的设备连接/断开的事件。

如果有连接/断开事件发生,那么host会发送一个Get_Port_Status请求(request)以了解更多hub上的信息。

android setusbtethering方法

android setusbtethering方法

android setusbtethering方法可以使用以下代码来设置Android设备的USB网络共享(USB Tethering):```javaConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);// 检查是否支持网络共享if (cm != null) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 检查用户是否授予了网络共享权限if (cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_E NABLED) {// 提示用户启用网络共享权限Intent intent = newIntent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RE STRICTIONS_SETTINGS);context.startActivity(intent);}}// 检查当前网络连接状态NetworkInfo activeNetwork = cm.getActiveNetworkInfo();boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();// 检查设备是否支持USB网络共享if (isConnected && cm.getTetherableIfaces() != null) {// 启用USB网络共享cm.startTethering(ConnectivityManager.TETHERING_USB, true, new ConnectivityManager.OnStartTetheringCallback() {@Overridepublic void onTetheringStarted() {// USB网络共享已成功启用}@Overridepublic void onTetheringFailed() {// 启用USB网络共享失败}});}}```请注意,启用网络共享可能需要特定的权限。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

USB HostUSB Host,中文意思是USB主模式,是相对于USB accessory(USB副模式)来说的,前者是在android设备上插入一USB设备,android设备做为主机运行;后者也是在android设备上通过USB数据线插入另外一个设备,但插入的设备可以是一个完整的独立主机,也就是可以是另外一个android设备。

需要注意的是以上两种模式在android API level-12以下是不支持的,也就是说只有android3.1及更高的版本才支持这两种模式,下面对USB主模式做一简介:bManager负责管理USB设备的类,你可以在相应代码中通过以下方法获得此对象的一个实例:UsbManager manager = (UsbManager) getSystemService(B_SERVICE);该类提供的主要方法有:1) getDeviceList()获得设备列表,返回的是一个HashMap.;2) hasPermission(UsbDevice device)判断你的应用程序是否有接入此USB设备的权限,如果有则返回真,否则返回false.3) openDevice(UsbDevice device)打开USB设备,以便向此USB设备发送和接受数据,返回一个关于此USB设备的连接。

4) requestPermission(UsbDevice device, PendingIntent pi)向USB设备请求临时的接入权限。

bDevice代表一个USB设备的类,每个设备都包含了一个或多个接口,每个接口又包含一个或多个节点用来与此设备传输数据。

该类的主要方法有:1) getDeviceClass()返回此USB设备的类别,用一个整型来表示。

2) getDeviceId()返回唯一标识此设备的ID号,也用一个整型来表示。

3) getDeviceName()返回此设备的名称,用一个字符串来表示。

4) getDeviceProtocol()返回此设备的协议类别,用一个整型来表示。

5) getDeviceSubclass()返回此设备的子类别,用一个整型来表示。

6) getVendorId()返回生产商ID7) getProductId()返回产品ID8) getInterfaceCount()返回此设备的接口数量9) getInterface(int index)得到此设备的一个接口,返回一个UsbInterface。

bInterface代表USB设备的一个接口,注意:UsbInterface本身是一个类,并不是一个接口。

此类的主要方法有以下:1) getId()得到给接口的id号。

2) getInterfaceClass()得到该接口的类别。

3) getInterfaceSubclass()得到该接口的子类。

4) getInterfaceProtocol()得到该接口的协议类别。

5) getEndpointCount()获得关于此接口的节点数量。

6) getEndpoint(int index)对于指定的index获得此接口的一个节点,返回一个UsbEndpoint.bEndpoint代表一个接口的某个节点的类。

该类主要提供了一下方法供你使用:1) getAddress()获得此节点的地址2) getAttributes()获得此节点的属性3) getDirection()获得此节点的数据传输方向bDeviceConnection代表USB连接的一个类。

用此连接可以想USB设备发送和接收数据,可以通过调用该方法openDevice(UsbDevice) 来得到该类的一个实例。

该类提供了以下方法供你使用:1)bulkTransfer(UsbEndpoint endpoint, byte[] buffer, int length, int timeout)通过给定的endpoint来进行大量的数据传输,传输的方向取决于该节点的方向,buffer是要发送或接收的字节数组,length是该字节数组的长度。

传输成功则返回所传输的字节数组的长度,失败则返回负数。

2)controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout)该方法通过0节点向此设备传输数据,传输的方向取决于请求的类别,如果requestType为USB_DIR_OUT则为写数据,USB_DIR_IN, 则为读数据Android配置文件要求在你使用以上API进行开发之前,你需要在你的AndroidManifest.xml文件中添加以下内容:1.因为并不能保证所有的安卓设备都支持以上API,所以你需要声明:<uses-sdk android:minSdkVersion="12"/>12以下的版本是不支持以上APId的。

<uses-feature android:name="b.host"/>2.如果你想有一个USB设备接入你的安卓设备时能够通知你的应用程序,那么你需要在你的Activity标签中声明以下内容<intent-filter><actionandroid:name="B_DEVICE_ ATTACHED"/></intent-filter><meta-dataandroid:name="B_DEVIC E_ATTACHED" android:resource="@xml/device_filter"/>Resource属性指定了要过滤的数据设备信息,包括:1) vendor-id 设备生产商id2) product-id 设备id3) class 设备类别4) subclass 设备子类5) protocol(device or interface) 协议类别device_filter.xml文件放在res\xml目录下,其中文件名不包括扩展名部分需要与<meta-data/> 标签中声明的一致。

示例如下:<?xml version="1.0" encoding="utf-8"?><resources><usb-device vendor-id="1234" product-id="5678" class="255" subclass="66" protocol="1" /></resources>开发步骤1.检测设备你的应用可以通过两种方式来发现USB设备,一种是用一个意图过滤器在用户连接一个设备时对其进行通知,另一种则是通过枚举您已经连接的所有USB设备。

如果你希望你的应用能够自动的探测到你想要的设备,请使用一个意图过滤器来做。

但是,如果你希望得到一个已连接设备的列表或者你不希望过滤意图,枚举所有的设备会是一个更好的选择。

1)Intent Filter为了让应用可以发现一个特定的USB设备,你可以为B_DEVICE_A TTACHED这个意图指定一个意图来进行过滤。

伴随着这个意图过滤器,您需要指定一个资源文件来特别说明这个USB设备的属性,例如供应商和产品ID。

当用户连接到一个符合你配件过滤条件的配件时,这个系统会谈出一个对话框询问他们是否希望开始你的应用。

如果用户同意,那么你的应用在失去连接之前会自动获取和设备连接的权限。

下面的例子告诉你该如何声明这个意图过滤器:<activity ...>...<intent-filter><action android:name="B_DEVICE_A TTACHED" /> </intent-filter><meta-data android:name="B_DEVICE_A TTACHED"android:resource="@xml/device_filter" /></activity>下面的例子告诉你怎么样声明指定你希望连接的USB设备的相关资源文件:<?xml version="1.0"encoding="utf-8"?><resources><usb-device vendor-id="1234"product-id="5678"/></resources>2)列举设备你可以通过UsbMnanger来列举已经连接的USB设备:代码如下首先,得到UsbMnanger的一个实例UsbManager manager = (UsbManager) getSystemService(B_SERVICE);其次,通过此类的getDeviceList()方法得到包含所有已连接的USB设备的列表HashMap<String, UsbDevice> deviceList = manager.getDeviceList();最后,通过设备名称来得到给设备对象UsbDevice device = deviceList.get("deviceName");如果你想一个一个的列举所有的设备,可以实用迭代器,代码实例如下:UsbManager manager = (UsbManager) getSystemService(B_SERVICE);HashMap<String, UsbDevice> deviceList = manager.getDeviceList();Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();while(deviceIterator.hasNext()){UsbDevice device = deviceIterator.next()//在这里添加处理设备的代码}2.获得和设备通信的权限如果你实用intent filter来发现一个USB设备,即上述方法1)那么应用程序可以自动的获取权限;如果是使用方法2)来检测USB设备,则你需要显示声明权限。

相关文档
最新文档