android usb host

KingMing 发布于 2014/07/16 20:50
阅读 691
收藏 4

package com.ming.usb.host;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;

import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class UsbHostActivity extends Activity {
 private static final String TAG = "UsbHost";

 private Button btn = null;

 private UsbManager mUsbManager = null;
 private UsbDevice mUsbDevice = null;
 private UsbInterface mUsbInterface = null;
 private UsbDeviceConnection mUsbDeviceConnection = null;

 private byte[] sendBytes; // 发送信息字节
 private byte[] receiveBytes; // 接收信息字节

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  btn = (Button)findViewById(R.id.sendBtn);
  btn.setOnClickListener(new OnClickListener() {
   int ret = -100;
   public void onClick(View v) {
    // TODO Auto-generated method stub
    String testString = "010A";
    //String testString = "C783CC30";
    byte[] bt = HexString2Bytes(testString);
    sendBytes = Arrays.copyOf(bt, bt.length);

    // 1,发送准备命令
    ret = mUsbDeviceConnection.bulkTransfer(epOut, sendBytes,
      sendBytes.length, 5000);
    Log.i(TAG, "已经发送!");
    
    // 2,接收发送成功信息
             receiveBytes = new byte[32];
             ret = mUsbDeviceConnection.bulkTransfer(epIn, receiveBytes,
               receiveBytes.length, 10000);
             Log.i(TAG, "接收返回值:" + String.valueOf(ret));
             if (ret != 32) {
                 System.out.println("接收返回值" + String.valueOf(ret));
                 return;
             } else {
                 // 查看返回值
              System.out.println(Bytes2HexString(receiveBytes));
             }
   }
  });

  // 获取USB设备
  mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
  if (mUsbManager == null) {
   return;
  } else {
   Log.i(TAG, "usb设备:" + String.valueOf(mUsbManager.toString()));
  }

  HashMap<String,UsbDevice> deviceList = mUsbManager.getDeviceList();
  Log.i(TAG, "usb设备:" + String.valueOf(deviceList.size()));
  Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
  ArrayList<String> USBDeviceList = new ArrayList<String>(); // 存放USB设备的数量
  while (deviceIterator.hasNext()) {
   UsbDevice device = deviceIterator.next();

   USBDeviceList.add(String.valueOf(device.getVendorId()));
   USBDeviceList.add(String.valueOf(device.getProductId()));

   // 在这里添加处理设备的代码
   if (device.getVendorId() == 1234) {
    mUsbDevice = device;
    Log.i(TAG, "找到设备");
   }
  }
  findIntfAndEpt();
 }

 private void findIntfAndEpt(){
  if (mUsbDevice == null) {
   Log.i(TAG, "没有找到设备");
   return;
  }

  for (int i = 0; i < mUsbDevice.getInterfaceCount();) {
   // 获取设备接口,一般都是一个接口,你可以打印getInterfaceCount()方法查看接
   // 口的个数,在这个接口上有两个端点,OUT 和 IN
   UsbInterface intf = mUsbDevice.getInterface(i);
   Log.d(TAG, i + " " + intf);
   mUsbInterface = intf;
   break;
  }

  if (mUsbInterface != null) {
   UsbDeviceConnection connection = null;
   // 判断是否有权限
   if (mUsbManager.hasPermission(mUsbDevice)) {
    // 打开设备,获取 UsbDeviceConnection 对象,连接设备,用于后面的通讯
    connection = mUsbManager.openDevice(mUsbDevice);
    if (connection == null) {
     return;
    }
    if (connection.claimInterface(mUsbInterface, true)) {
     Log.i(TAG, "找到接口");
     mUsbDeviceConnection = connection;
     // 用UsbDeviceConnection 与 UsbInterface 进行端点设置和通讯
     getEndpoint(mUsbDeviceConnection, mUsbInterface);
    } else {
     connection.close();
    }
   } else {
    Log.i(TAG, "没有权限");
   }
  } else {
   Log.i(TAG, "没有找到接口");
  }
 }

 private UsbEndpoint epOut;
 private UsbEndpoint epIn;

 // 用UsbDeviceConnection 与 UsbInterface 进行端点设置和通讯
 private void getEndpoint(UsbDeviceConnection connection, UsbInterface intf) {
  if (intf.getEndpoint(1) != null) {
   epOut = intf.getEndpoint(1);
  }
  if (intf.getEndpoint(0) != null) {
   epIn = intf.getEndpoint(0);
  }
 }
 /**
  * 将两个ASCII字符合成一个字节;
  * 如:"EF"--> 0xEF
  * @param src0 byte
  * @param src1 byte
  * @return byte
  */ 
 public static byte uniteBytes(byte src0, byte src1) { 
  byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue(); 
  _b0 = (byte)(_b0 << 4); 
  byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue(); 
  byte ret = (byte)(_b0 ^ _b1); 
  return ret; 
 }

 /**
  * 将指定字符串src,以每两个字符分割转换为16进制形式
  * 如:"2B44EFD9" –> byte[]{0x2B, 0×44, 0xEF, 0xD9}
  * @param src String
  * @return byte[]
  */ 
 public static byte[] HexString2Bytes(String src){ 
  byte[] ret = new byte[src.length()/2]; 
  byte[] tmp = src.getBytes(); 
  for(int i=0; i< tmp.length/2; i++){ 
   ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]); 
  } 
  return ret; 
 } 

 /**
  *
  * @param b byte[]
  * @return String
  */ 
 public static String Bytes2HexString(byte[] b) { 
  String ret = ""; 
  for (int i = 0; i < b.length; i++) { 
   String hex = Integer.toHexString(b[i] & 0xFF); 
   if (hex.length() == 1) { 
    hex = '0' + hex; 
   } 
   ret += hex.toUpperCase(); 
  } 
  return ret; 
 } 

 /**
  * 将指定byte数组以16进制的形式打印到控制台
  * @param hint String
  * @param b byte[]
  * @return void
  */ 
 public static void printHexString(String hint, byte[] b) { 
  System.out.print(hint); 
  for (int i = 0; i < b.length; i++) { 
   String hex = Integer.toHexString(b[i] & 0xFF); 
   if (hex.length() == 1) { 
    hex = '0' + hex; 
   } 
   System.out.print(hex.toUpperCase() + " "); 
  } 
  System.out.println(""); 
 } 
}

加载中
返回顶部
顶部