【转】android usb accessory

KingMing 发布于 2014/07/16 21:12
阅读 2K+
收藏 3
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模式
     

下面为USB的相关代码 与 流程 :

 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 " />
      添加过滤器:

<activity ...> ... <intent-filter> <actionandroid:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" /> </intent-filter> <meta-dataandroid:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"android:resource="@xml/accessory_filter" /> </activity>

   <? xml version = "1.0"   encoding = "utf-8" ?>   <resources>   <usb-accessory   model = "DemoKit" manufacturer = "Google"   version = "1.0" /> </resources>
2 . 获取一个usb管理者:
  UsbManager   manager   =   ( UsbManager )   getSystemService ( Context . USB_SERVICE );
  2.3 时:   UsbManager   manager   =   UsbManager . getInstance ( this );

3. 获取 USBAccessory  当我们的设备连接到到另外的一个设备时  系统会给我们发送一个系统广播
    既我们在  manifest里面注册的  当我们接受到这个广播后就可以获取连接的设备
     UsbAccessory   accessory   =   ( UsbAccessory ) intent . getParcelableExtra ( UsbManager . EXTRA_ACCESSORY );
  
   2.3时 为: UsbAccessory   accessory   =   UsbManager . getAccessory ( intent );

4. 在这个广播中我们获取他的action如果action与 UsbManager. EXTRA_ACCESSORY 匹配
  我们则开启一个diallog 来提示用户是否来接设备
  首先要包装一个pendingintent来实现提示对话框
     mPermissionIntent   = PendingIntent.getBroadcast( mContext , 0,   new   Intent( ACTION_USB_PERMISSION ), 0);
  接着实现
    mUsbManager .requestPermission(usbAccessory,   mPermissionIntent );
5.当我们按下确定后, 我们会在次接到系统广播 ,来打开通信通道
     action与    UsbManager. ACTION_USB_ACCESSORY_ATTACHED   匹配
  我们就可以打开通信通道:
  
   注意 :通信通道不能在主线程中开启
  


以下为具体代码:

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 = "BluetoothControllerConnectionStateChangedAction";
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="USBControllerOpenAccessoryFail";
public final static String ACTION_SHOWTOAST="USBControllerShowToast";
// --------------------------------------------------
// ----- properties -----
// --------------------------------------------------
private final Context mContext;
private HarbourLightController mHarbourLightController;
private HarbourLightUpgradeController mHarbourLightUpgradeController;
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);
mHarbourLightUpgradeController = new HarbourLightUpgradeController(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  getHarbourLightController(){
if(mHarbourLightController==null){
mHarbourLightController= new HarbourLightController(mContext, null, null);
}
return mHarbourLightController;
}
public HarbourLightUpgradeController getHarbourLightUpgradeController(){
if(mHarbourLightUpgradeController==null){
mHarbourLightUpgradeController = new HarbourLightUpgradeController(mContext, null, null);
}
return mHarbourLightUpgradeController;
}
public ConnectionState getConnectionState(){
return mConnectionState;
}
public boolean getIsRequrstingPermission(){
return mIsRequestingPermission;
}
public void setIsRequrstingPermission(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.creatBroadCastReceiverIntent(USBAccessoryController.ACTION_USB_UPDATEDATA_FILEOUTPUTSTREAM, "open Accessory"));
// mHarbourLightController.openSession();
// mHarbourLightController.handshake();
mContext.sendBroadcast(Utility.creatBroadCastReceiverIntent(HarbourLightController.ACTION_OPENSESSIONSUCCESS, "open Session success"));
mHarbourLightUpgradeController = new HarbourLightUpgradeController(mContext, mInputStream, mOutputStream);
mHarbourLightUpgradeController.openSession();
int timeOut=0;
while (!mIsStopped && timeOut < 10000) {
mContext.sendBroadcast(Utility.creatBroadCastReceiverIntent(ACTION_CONNECTIONSTATE_CHANGED, "wait connect"));
// if (mHarbourLightController.isConnected()) {
if(mHarbourLightUpgradeController.isConnected()){
mConnectionState = ConnectionState.Connected;
mContext.sendBroadcast(Utility.creatBroadCastReceiverIntent(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();
setIsRequrstingPermission(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)){
    mIsStopped=false;
openAccessory(accessory);
}
}
}
}else if (action.equalsIgnoreCase(UsbManager.ACTION_USB_ACCESSORY_DETACHED)) {
closeAccessory();
}
}
};
}
加载中
0
挨踢专业

我的为什么一直扫不出设备来啊博主。现在在做这个,求抱大腿啊,方便加qq交流一下 1322354549,谢谢了。

返回顶部
顶部