最近搞的开发慢慢接近底层了,各种usb打印机,usb串口通信,蓝牙通信,搞得头挺晕,不过也学到了挺多,今天抽点时间总结下。

UsbAccessory 使用帮助类

//User must modify the below package with their package name
package com.UARTLoopback;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Toast;/******************************FT311 GPIO interface class******************************************/
public class FT311UARTInterface
{private static final String ACTION_USB_PERMISSION =    "com.UARTLoopback.USB_PERMISSION";public UsbManager usbmanager;public UsbAccessory usbaccessory;public PendingIntent mPermissionIntent;public ParcelFileDescriptor filedescriptor = null;public FileInputStream inputstream = null;public FileOutputStream outputstream = null;public boolean mPermissionRequestPending = false;public read_thread readThread;private byte [] usbdata; private byte []   writeusbdata;private byte  [] readBuffer; /*circular buffer*/private int readcount;private int totalBytes;private int writeIndex;private int readIndex;private byte status;final int  maxnumbytes = 65536;public boolean datareceived = false;public boolean READ_ENABLE = false;public boolean accessory_attached = false;public Context global_context;public static String ManufacturerString = "mManufacturer=FTDI";public static String ModelString1 = "mModel=FTDIUARTDemo";public static String ModelString2 = "mModel=Android Accessory FT312D";public static String VersionString = "mVersion=1.0";/*constructor*/public FT311UARTInterface(Context context){super();global_context = context;/*shall we start a thread here or what*/usbdata = new byte[1024]; writeusbdata = new byte[256];/*128(make it 256, but looks like bytes should be enough)*/readBuffer = new byte [maxnumbytes];readIndex = 0;writeIndex = 0;/***********************USB handling******************************************/usbmanager = (UsbManager) context.getSystemService(Context.USB_SERVICE);mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);context.registerReceiver(mUsbReceiver, filter);inputstream = null;outputstream = null;}public void SetConfig(int baud, byte dataBits, byte stopBits,byte parity, byte flowControl){/*prepare the baud rate buffer*/writeusbdata[0] = (byte)baud;writeusbdata[1] = (byte)(baud >> 8);writeusbdata[2] = (byte)(baud >> 16);writeusbdata[3] = (byte)(baud >> 24);/*data bits*/writeusbdata[4] = dataBits;/*stop bits*/writeusbdata[5] = stopBits;/*parity*/writeusbdata[6] = parity;/*flow control*/writeusbdata[7] = flowControl;/*send the UART configuration packet*/SendPacket((int)8);}/*write data*/public byte SendData(int numBytes, byte[] buffer) {status = 0x00; /*success by default*//** if num bytes are more than maximum limit*/if(numBytes < 1){/*return the status with the error in the command*/return status;}/*check for maximum limit*/if(numBytes > 256){numBytes = 256;}/*prepare the packet to be sent*/for(int count = 0;count<numBytes;count++){ writeusbdata[count] = buffer[count];}if(numBytes != 64){SendPacket(numBytes);}else{byte temp = writeusbdata[63];SendPacket(63);writeusbdata[0] = temp;SendPacket(1);}return status;}/*read data*/public byte ReadData(int numBytes,byte[] buffer, int [] actualNumBytes){status = 0x00; /*success by default*//*should be at least one byte to read*/if((numBytes < 1) || (totalBytes == 0)){actualNumBytes[0] = 0;status = 0x01;return status;}/*check for max limit*/if(numBytes > totalBytes)numBytes = totalBytes;/*update the number of bytes available*/totalBytes -= numBytes;actualNumBytes[0] = numBytes;    /*copy to the user buffer*/ for(int count = 0; count<numBytes;count++){buffer[count] = readBuffer[readIndex];readIndex++;/*shouldnt read more than what is there in the buffer,*   so no need to check the overflow*/readIndex %= maxnumbytes;}return status;}/*method to send on USB*/private void SendPacket(int numBytes){ try {if(outputstream != null){outputstream.write(writeusbdata, 0,numBytes);}} catch (IOException e) {e.printStackTrace();}}/*resume accessory*/public int ResumeAccessory(){// Intent intent = getIntent();if (inputstream != null && outputstream != null) {return 1;}//获取accessory列表UsbAccessory[] accessories = usbmanager.getAccessoryList();if(accessories != null){Toast.makeText(global_context, "Accessory Attached", Toast.LENGTH_SHORT).show();}else{accessory_attached = false;return 2;}//这里取第一个accessory,因为一般手机设备只能有一个.这里不考虑多个的情况,UsbAccessory accessory = (accessories == null ? null : accessories[0]);if (accessory != null) {Toast.makeText(global_context, "getDescription"+accessory, Toast.LENGTH_LONG).show();if( -1 == accessory.toString().indexOf(ManufacturerString)){Toast.makeText(global_context, "Manufacturer is not matched!", Toast.LENGTH_SHORT).show();return 1;}if( -1 == accessory.toString().indexOf(ModelString1) && -1 == accessory.toString().indexOf(ModelString2)){Toast.makeText(global_context, "Model is not matched!", Toast.LENGTH_SHORT).show();return 1;}if( -1 == accessory.toString().indexOf(VersionString)){Toast.makeText(global_context, "Version is not matched!", Toast.LENGTH_SHORT).show();return 1;}Toast.makeText(global_context, "Manufacturer, Model & Version are matched!", Toast.LENGTH_SHORT).show();accessory_attached = true;if (usbmanager.hasPermission(accessory)) {Toast.makeText(global_context, "usbmanager has permission", Toast.LENGTH_SHORT).show();OpenAccessory(accessory);} else{synchronized (mUsbReceiver) {if (!mPermissionRequestPending) {Toast.makeText(global_context, "Request USB Permission", Toast.LENGTH_SHORT).show();usbmanager.requestPermission(accessory,mPermissionIntent);mPermissionRequestPending = true;}}}} else {}return 0;}/*destroy accessory*/public void DestroyAccessory(boolean bConfiged){Toast.makeText(global_context, "DestroyAccessory"+bConfiged, Toast.LENGTH_SHORT).show();if(true == bConfiged){READ_ENABLE = false;  // set false condition for handler_thread to exit waiting data loopwriteusbdata[0] = 0;  // send dummy data for instream.read goingSendPacket(1);}else{SetConfig(9600,(byte)1,(byte)8,(byte)0,(byte)0);  // send default setting data for configtry{Thread.sleep(10);}catch(Exception e){}READ_ENABLE = false;  // set false condition for handler_thread to exit waiting data loopwriteusbdata[0] = 0;  // send dummy data for instream.read goingSendPacket(1);}try{Thread.sleep(10);}catch(Exception e){}           CloseAccessory();}/*********************helper routines*************************************************/       public void OpenAccessory(UsbAccessory accessory){filedescriptor = usbmanager.openAccessory(accessory);if(filedescriptor != null){Toast.makeText(global_context, "filedescriptior!=null", Toast.LENGTH_SHORT).show();usbaccessory = accessory;FileDescriptor fd = filedescriptor.getFileDescriptor();inputstream = new FileInputStream(fd);outputstream = new FileOutputStream(fd);/*check if any of them are null*/if(inputstream == null || outputstream==null){Toast.makeText(global_context, "connect fail", Toast.LENGTH_SHORT).show();return;}elseToast.makeText(global_context, "connect success", Toast.LENGTH_SHORT).show();if(READ_ENABLE == false){Toast.makeText(global_context, "READ_ENABLE==false", Toast.LENGTH_SHORT).show();READ_ENABLE = true;readThread = new read_thread(inputstream);readThread.start();}}elseToast.makeText(global_context, "filedescriptior====null", Toast.LENGTH_SHORT).show();}private void CloseAccessory(){try{if(filedescriptor != null)filedescriptor.close();}catch (IOException e){}try {if(inputstream != null)inputstream.close();} catch(IOException e){}try {if(outputstream != null)outputstream.close();}catch(IOException e){}/*FIXME, add the notfication also to close the application*/filedescriptor = null;inputstream = null;outputstream = null;global_context.unregisterReceiver(mUsbReceiver);System.exit(0);}/*** 监听usb插入拔出的广播* 以及请求获得usb权限的广播*/private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();//请求获得usb权限的广播if (ACTION_USB_PERMISSION.equals(action)) {synchronized (this){UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){OpenAccessory(accessory);} else {Toast.makeText(global_context, "Deny USB Permission", Toast.LENGTH_SHORT).show();Log.d("LED", "permission denied for accessory "+ accessory);}Toast.makeText(global_context, "BroadcastReceiver", Toast.LENGTH_SHORT).show();mPermissionRequestPending = false;}} //监听usb拔出的广播else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {DestroyAccessory(true);}}  };/*usb input data handler*/private class read_thread  extends Thread {FileInputStream instream;read_thread(FileInputStream stream ){instream = stream;this.setPriority(Thread.MAX_PRIORITY);}public void run(){       while(READ_ENABLE == true){while(totalBytes > (maxnumbytes - 1024)){try {Thread.sleep(50);}catch (InterruptedException e) {e.printStackTrace();}}try{if(instream != null){    readcount = instream.read(usbdata,0,1024);if(readcount > 0){for(int count = 0;count<readcount;count++){                                   readBuffer[writeIndex] = usbdata[count];writeIndex++;writeIndex %= maxnumbytes;}if(writeIndex >= readIndex)totalBytes = writeIndex-readIndex;elsetotalBytes = (maxnumbytes-readIndex)+writeIndex;//                              Log.e(">>@@","totalBytes:"+totalBytes);}}}catch (IOException e){e.printStackTrace();}}}}
}

使用

<span style="white-space:pre">  </span>uartInterface.ResumeAccessory();uartInterface.SetConfig(baudRate, dataBit, stopBit, parity, flowControl);

记得加上权限

    <uses-feature android:name="android.hardware.usb.accessory"/>

UsbAccessory相关推荐

  1. Android中的USB中的UsbAccessory和UsbDevice的区别

    Android中的USB中的UsbAccessory和UsbDevice的区别 [背景] 之前折腾android中的USB相关的东西. 遇到两个东西: UsbAccessory和UsbDevice 但 ...

  2. UsbAccessory和UsbDevice的区别

    UsbAccessory和UsbDevice的区别 UsbDevice:正常的,USB的Host和USB的Device架构中的USB的Device 所以,此时:Android设备是USB的Host,外 ...

  3. Android UsbAccessory中你需要小心的坑及解决方案

    本文旨在解决Usb连接过程中的问题而不注重具体实现过程,如果有对Usb连接过程感兴趣的朋友可以查看Android官方文档 目录 目录 现实背景 存在问题 问题原因 解决方案 小结 现实背景 现在智能硬 ...

  4. 基于AOA协议的android USB通信

    摘 要:AOA协议是Google公司推出的用于实现Android设备与外围设备之间USB通信的协议.该协议拓展了Android设备USB接口的功能,为基于Android系统的智能设备应用于数据采集和设 ...

  5. USB Host Device And OTG

    USB是一种数据通信方式,也是一种数据总线,而且是最复杂的总线之一.  硬件上,它是用插头连接.一边是公头(plug),一边是母头(receptacle).例如,PC上的插座就是母头,USB设备使用公 ...

  6. android USB

    google 在推出API 3.0后 就增加啦USB通讯这块 同时为API  2.3提供啦一个USB通讯吧,这样也让2.3有啦USB通讯功能  不过只支持USBAccessory模式 USB通讯分为两 ...

  7. 轻松搭建Google ADK开发环境

    相信很多网友一直有自己DIY机器人的想法,但苦于要使用的各种控制模块品种繁多.成本高昂.且开发难度较高.但是随着Google发布了任何人均可自由开发Android终端外设的协议"Open A ...

  8. 安卓USB开发教程 三 USB Accessory

    USB Accessory(配件模式) USB 配件模式允许用户连接专为 Android 设备设计的 USB 主机硬件.配件必须遵守 Android Accessory Development Kit ...

  9. 【Android】完善Android学习(二:API 2.3.4)

    备注:之前Android入门学习的书籍使用的是杨丰盛的<Android应用开发揭秘>,这本书是基于Android 2.2API的,目前Android已经到4.4了,更新了很多的API,也增 ...

最新文章

  1. 格式化输出--对齐及补全
  2. 数据结构与算法 / 概念
  3. zz -- QQ圈子感想
  4. oracle客户端ora 12541,Oracle 11g 64bit下程序报ORA-12541: TNS: 无监听程序解决办法
  5. 区域医疗移动医疗影像解决方案1-基于HTML5的PACS
  6. 语音识别模型_语音 识别_语音识别 - 云+社区 - 腾讯云
  7. 设计模式 (十一) 外观模式
  8. html简单网页设计实验实践结论,网页设计社会实践报告
  9. 3DGIS合伙人招募
  10. 文件夹批量重命名的方法
  11. Request processing failed; nested exception is com.alibaba.dubbo.rpc.RpcException问题 学习记录
  12. 十个你必须知道的ps技巧
  13. 作恶可以,但请有底线!
  14. R 一行代码出Cox回归模型的表格
  15. 改进后的速算小游戏(2011211909 苟玲、2011211933 郝怡然)
  16. 令人躁动一时且令人不安的TCP BBR算法
  17. GitLab 服务搭建
  18. 【关于NI CAN USB-8473在实际应用中的案例分析】
  19. android EditText 属性
  20. PMP考试计算专题——网络图

热门文章

  1. 华为新机搭载鸿蒙系统,华为又一款新机入网!搭载麒麟9000芯片,预装鸿蒙系统...
  2. 汇丰银行java框架_汇丰银行面试经历(IT类).doc
  3. 央企和国企什么级别可以转为公务员?
  4. Android手机音量设置相关
  5. c++bind函数使用
  6. Vue2.5开发去哪网App项目实战记录(根据慕课网课程编写)
  7. 关于PS批处理存储JPG时总是要选JPG质量的问题,如何解决
  8. Tesseract编译
  9. autodesk公司送来的小音箱
  10. 平移不变性和Siam目标跟踪