最近搞的开发慢慢接近底层了,各种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. CentOS7.0下编译安装Nginx 1.10.0
  2. python下载图片、已知url_python实现通过URL下载图片到本地服务器
  3. java maven -DskipTests 和 -Dmaven.test.skip=true 区别
  4. rtti是什么java_RTTI
  5. [云炬创业学笔记]第一章创业是什么测试15
  6. 对Coverage进行编辑
  7. 如何给开源项目提过 PR 呢?其实很简单
  8. 1000道Python题库系列分享六(40道)
  9. CEF与JavaScript交互读取电脑信息
  10. 使用Adorner显示WPF控件的边界点
  11. 2021软件评测师考试大纲(清华出版社2021.7第1次印刷)
  12. JDK8绿色安装详细步骤
  13. nRF 主机扫描过滤器
  14. java转行失败_转行学JAVA,成功和失败的原因
  15. 佐治亚理工计算机考研,[转载]佐治亚理工学院硕士研究生怎么样?申请难度
  16. 2018-08-08 Mac使用中的一些实用设置
  17. 企业如何解决供应商管理难题?
  18. mt7688 OpenWrt 编译
  19. Relief特征选择算法
  20. 横扫天下mysql首充修改_横扫天下完整修复商业端(邮件发送+充值后台+物品ID+教程)...

热门文章

  1. POJ 1568 四子棋 搜索剪枝
  2. 莽荒纪计算机游戏,莽荒纪电脑版
  3. 用Keras搞一个阅读理解机器人
  4. 单链表——单链表的定义及基本操作(初始化、头插法尾插法建表、查找、插入、删除、判空等)
  5. _get_sysconfigdata_name() missing 1 required positional argument: ‘check_exists‘
  6. Java Calendar set()方法与示例
  7. 人工智能交互革命:探索ChatGPT的无限可能 第5章 ChatGPT-语音助手
  8. LightDB中的存储过程(七)—— 子程序
  9. 全国计算机等级考试南京点一年考几次,2018年上半年江苏省南京市计算机等级考试考务通知...
  10. Unity3D中的(Camera组件、AudioSource 组件、AudioListener 组件)