原文地址:android USB
作者:sinde
google 在推出API 3.0后 就增加啦USB通讯这块
同时为API
2.3提供啦一个USB通讯吧,这样也让2.3有啦USB通讯功能
不过只支持USBAccessory模式
USB通讯分为两种模式:(1)附载模式 USBAccessory (2)主机模式 USBHost
什么叫主机模式?
android官方文档解释为
When your Android-powered device is in USB host mode, it acts as the USB host, powers the bus, and enumerates connected USB devices
个人理解为谁提供power 谁就USBHost
打个比方 你手上有台 音响 可以和 android手机 进行通讯 这里手机为USBAccessory模式
1. 首先需要在manifest中添加一些元素和一些过滤器:
<uses-feature
android:name
=
"android.hardware.usb.accessory"
/>
如果是2.3时为:
<uses-feature
android:name
=
"com.android.future.usb.accessory"
/>
同时还要在application 中添加USB库
<
uses-library
android:name
=
"
com.android.future.usb.accessory
"
/>
添加过滤器:
<?
xml version
=
"1.0"
encoding
=
"utf-8"
?>
<resources>
<usb-accessory
model
=
"DemoKit"
manufacturer
=
"Google"
version
=
"1.0"
/>
</resources>
UsbManager
manager
=
(
UsbManager
)
getSystemService
(
Context
.
USB_SERVICE
);
2.3 时:
UsbManager
manager
=
UsbManager
.
getInstance
(
this
);
既我们在 manifest里面注册的 当我们接受到这个广播后就可以获取连接的设备
UsbAccessory
accessory
=
(
UsbAccessory
)
intent
.
getParcelableExtra
(
UsbManager
.
EXTRA_ACCESSORY
);
2.3时 为:
UsbAccessory
accessory
=
UsbManager
.
getAccessory
(
intent
);
我们则开启一个diallog 来提示用户是否来接设备
首先要包装一个pendingintent来实现提示对话框
mPermissionIntent
= PendingIntent.getBroadcast(
mContext
, 0,
new
Intent(
ACTION_USB_PERMISSION
), 0);
接着实现
mUsbManager
.requestPermission(usbAccessory,
mPermissionIntent
);
action与
UsbManager.
ACTION_USB_ACCESSORY_ATTACHED
匹配
我们就可以打开通信通道:
注意 :通信通道不能在主线程中开启
mIsStopped=false;
下面为USB的相关代码 与 流程 :
<activity ...> ... <intent-filter> <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" /> </intent-filter> <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" android:resource="@xml/accessory_filter" /> </activity>
2 . 获取一个usb管理者:
3. 获取 USBAccessory 当我们的设备连接到到另外的一个设备时 系统会给我们发送一个系统广播
4. 在这个广播中我们获取他的action如果action与
UsbManager.
EXTRA_ACCESSORY 匹配
5.当我们按下确定后, 我们会在次接到系统广播 ,来打开通信通道
以下为具体代码:
package hk.com.harbourlight.compones;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.library.Utility;
import android.os.ParcelFileDescriptor;
public class USBController {
// --------------------------------------------------
// ----- enums -----
// --------------------------------------------------
public enum ConnectionState {
Connecting, Connected, Disconnected
}
// --------------------------------------------------
// ----- constants -----
// --------------------------------------------------
public static final String ACTION_CONNECTIONSTATE_CHANGED = "BluetoothControllerConne
ctionStateChangedAction";
private static final int TIMEOUT_DISCOVERY = 30000;
public final static String ACTION_USB_PERMISSION = "hk.com.harbourlight.USB_PERMISSION";
public final static String ACTION_OPENACCESSORY_FAIL="USBControllerOpenAccesso
ryFail";
public final static String ACTION_SHOWTOAST="USBControllerShowToast";
// --------------------------------------------------
// ----- properties -----
// --------------------------------------------------
private final Context mContext;
private HarbourLightController mHarbourLightController;
private HarbourLightUpgradeContr
oller mHarbourLightUpgradeCont
roller;
private ConnectionState mConnectionState;
private Boolean mIsStopped;
private PendingIntent mPendingIntent;
private UsbManager mUsbManager;
private ParcelFileDescriptor mFileDescriptor;
private FileInputStream mInputStream;
private FileOutputStream mOutputStream;
private boolean mIsRequestingPermission;
//---------------------------------------------------
//----- extends --------
//---------------------------------------------------
public USBController(final Context context,final UsbManager usbManager){
this.mContext=context;
this.mUsbManager=usbManager;
mHarbourLightController = new HarbourLightController(mContext, null, null);
mConnectionState = ConnectionState.Disconnected;
mIsStopped = false;
mPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
mHarbourLightUpgradeCont
roller = new HarbourLightUpgradeContr
oller(mContext, null, null);
}
public void start(){
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
mContext.registerReceiver(mBroadcastReceiver, filter);
mIsStopped=false;
mIsRequestingPermission=false;
}
public void stop(){
mIsRequestingPermission=false;
mIsStopped=true;
mContext.unregisterReceiver(mBroadcastReceiver);
}
public void disConnect(){
mIsStopped=true;
mHarbourLightController.closeSession();
mConnectionState = ConnectionState.Disconnected;
mContext.sendBroadcast(new Intent(ACTION_CONNECTIONSTATE_CHANGED));
}
public HarbourLightController getHarbourLightControlle
r(){
if(mHarbourLightController==null){
mHarbourLightController= new HarbourLightController(mContext, null, null);
}
return mHarbourLightController;
}
public HarbourLightUpgradeContr
oller getHarbourLightUpgradeCo
ntroller(){
if(mHarbourLightUpgradeCont
roller==null){
mHarbourLightUpgradeCont
roller = new HarbourLightUpgradeContr
oller(mContext, null, null);
}
return mHarbourLightUpgradeCont
roller;
}
public ConnectionState getConnectionState(){
return mConnectionState;
}
public boolean getIsRequrstingPermissio
n(){
return mIsRequestingPermission;
}
public void setIsRequrstingPermissio
n(final boolean isRequrstingPermission){
this.mIsRequestingPermission=isRequrstingPermission;
}
public boolean hasPermission(final UsbAccessory accessory){
return mUsbManager.hasPermission(accessory);
}
public void requestPermission(final UsbAccessory accessory){
synchronized (mBroadcastReceiver) {
mUsbManager.requestPermission(accessory, mPendingIntent);
}
}
public UsbAccessory[] getUsbAccessories(){
return mUsbManager.getAccessoryList();
}
//---------------------------------------------------
//----processes------
//---------------------------------------------------
public void openAccessory(final UsbAccessory usbAccessory){
try
{
new Thread(){
public void run(){
mFileDescriptor = mUsbManager.openAccessory(usbAccessory);
if (mFileDescriptor != null)
{
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
if(fd!=null){
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
if(mInputStream!=null && mOutputStream!=null){
mHarbourLightController = new HarbourLightController(mContext, mInputStream, mOutputStream);
mContext.sendBroadcast(Utility.creatBroadCastReceiverIn
tent(USBAccessoryController.ACTION_USB_UPDATEDATA_FILEOUTPUTSTREAM, "open Accessory"));
// mHarbourLightController.openSession();
// mHarbourLightController.handshake();
mContext.sendBroadcast(Utility.creatBroadCastReceiverIn
tent(HarbourLightController.ACTION_OPENSESSIONSUCCESS, "open Session success"));
mHarbourLightUpgradeCont
roller = new HarbourLightUpgradeContr
oller(mContext, mInputStream, mOutputStream);
mHarbourLightUpgradeCont
roller.openSession();
int timeOut=0;
while (!mIsStopped && timeOut < 10000) {
mContext.sendBroadcast(Utility.creatBroadCastReceiverIn
tent(ACTION_CONNECTIONSTATE_CHANGED, "wait connect"));
// if (mHarbourLightController.isConnected()) {
if(mHarbourLightUpgradeCont
roller.isConnected()){
mConnectionState = ConnectionState.Connected;
mContext.sendBroadcast(Utility.creatBroadCastReceiverIn
tent(ACTION_CONNECTIONSTATE_CHANGED, "connect"));
return;
}
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
timeOut += 500;
}
}
}
}else {
mContext.sendBroadcast(new Intent(ACTION_OPENACCESSORY_FAIL));
}
}
}.start();
}
catch (Exception e)
{
}
}
private void closeAccessory() {
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
if (mHarbourLightController != null) {
mHarbourLightController.closeSession();
}
if (mInputStream != null) {
mInputStream = null;
}
if (mOutputStream != null) {
mOutputStream = null;
}
mHarbourLightController.closeSession();
disConnect();
setIsRequrstingPermissio
n(false);
mConnectionState=ConnectionState.Disconnected;
mContext.sendBroadcast(new Intent(ACTION_SHOWTOAST));
}
catch (final Exception ex) {
}
}
//--------------------------------------------------
//--------- BroadcastReceiver --------
//--------------------------------------------------
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(action.equalsIgnoreCase(ACTION_USB_PERMISSION)){
synchronized (this) {
UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
if(accessory==null){
accessory=getUsbAccessories()[0];
}
if(accessory!=null){
if(hasPermission(accessory)){
openAccessory(accessory);
}
}
}
}else if (action.equalsIgnoreCase(UsbManager.ACTION_USB_ACCESSORY_DETACHED)) {
closeAccessory();
}
}
};
}