Android开发之USB数据通信

Android开发中USB串口通信开发主要涉及到以下几个类及相应的方法: 
1 ,UsbManager:负责管理USB设备的类,你可以在相应代码中通过以下方法获得

//获取UsbManager实例方法
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
 
 
  • 1
  • 2

该类提供的主要方法有: 
1) getDeviceList() 
获得设备列表,返回的是一个HashMap.; 
2) hasPermission(UsbDevice device) 
判断你的应用程序是否有接入此USB设备的权限,如果有则返回真,否则返回false. 
3) openDevice(UsbDevice device) 
打开USB设备,以便向此USB设备发送和接受数据,返回一个关于此USB设备的连接。 
4) requestPermission(UsbDevice device, PendingIntent pi) 
向USB设备请求临时的接入权限。

2,UsbDevice:一个USB设备对象,每个设备一般包括一个接口,也可能有多个,每个接口又包含节点用来与此设备传输数据。主要方法有: 
1) getDeviceClass() 
返回此USB设备的类别,用一个整型来表示。 
2) getDeviceId() 
返回唯一标识此设备的ID号,也用一个整型来表示。 
3) getDeviceName() 
返回此设备的名称,用一个字符串来表示。 
4) getDeviceProtocol() 
返回此设备的协议类别,用一个整型来表示。 
5) getDeviceSubclass() 
返回此设备的子类别,用一个整型来表示。 
6) getVendorId() 
返回生产商ID 
7) getProductId() 
返回产品ID 
8) getInterfaceCount() 
返回此设备的接口数量 
9) getInterface(int index) 
得到此设备的一个接口,返回一个UsbInterface。

3,UsbInterface:代表USB设备的一个接口(物理接口),UsbInterface本身是一个类,此类的主要方法有以下: 
1) getId() 
得到给接口的id号。 
2) getInterfaceClass() 
得到该接口的类别。 
3) getInterfaceSubclass() 
得到该接口的子类。 
4) getInterfaceProtocol() 
得到该接口的协议类别。 
5) getEndpointCount() 
获得关于此接口的节点数量。 
6) getEndpoint(int index) 
对于指定的index获得此接口的一个节点,返回一个UsbEndpoint. 
4, UsbEndpoint:代表一个接口的某个节点的类。该类主要方法: 
1) getAddress() 
获得此节点的地址 
2) getAttributes() 
获得此节点的属性 
3) getDirection() 
获得此节点的数据传输方向 
5 ,UsbDeviceConnection:代表USB连接的一个类。用此连接可以想USB设备发送和接收数据,主要方法有: 
1)bulkTransfer(UsbEndpoint endpoint, byte[] buffer, int length, int timeout) 
通过给定的endpoint来进行大量的数据传输,传输的方向取决于该节点的方向,buffer是要发送或接收的字节数组,length是该字节数组的长度。传输成功则返回所传输的字节数组的长度,失败则返回负数。 
2)controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout) 
该方法通过0节点向此设备传输数据,传输的方向取决于请求的类别,如果requestType为USB_DIR_OUT则为写数据,USB_DIR_IN, 则为读数据 
以上介绍资料主要来自博文: http://www.osedu.net/article/linux/2014-04-16/678.html

—-示例代码——

public class UsbTestActivity extends Activity implements View.OnClickListener {
   //设备列表
    private HashMap<String, UsbDevice> deviceList;
    //从设备读数据
    private Button read_btn;
    //给设备写数据(发指令)
    private Button write_btn;
    //USB管理器:负责管理USB设备的类
    private UsbManager manager;
    //找到的USB设备
    private UsbDevice mUsbDevice;
    //代表USB设备的一个接口
    private UsbInterface mInterface;
    private UsbDeviceConnection mDeviceConnection;
    //代表一个接口的某个节点的类:写数据节点
    private UsbEndpoint usbEpOut;
    //代表一个接口的某个节点的类:读数据节点
    private UsbEndpoint usbEpIn;
    //要发送信息字节
    private byte[] sendbytes;
    //接收到的信息字节
    private byte[] receiveytes;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usb);
        initUsbData();
        initViews();
    }

    private void initUsbData() {

        // 获取USB设备
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
         //获取到设备列表
        deviceList = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            Log.e("ldm", "vid=" + usb.getVendorId() + "---pid=" + usb.getProductId());
            //if (mVendorID == usb.getVendorId() && mProductID == usb.getProductId()) {//找到指定设备
             mUsbDevice = deviceIterator.next();
            }
            // }
        }
        //获取设备接口
        for (int i = 0; i < mUsbDevice.getInterfaceCount(); ) {
            // 一般来说一个设备都是一个接口,你可以通过getInterfaceCount()查看接口的个数
            // 这个接口上有两个端点,分别对应OUT 和 IN
            UsbInterface usbInterface = mUsbDevice.getInterface(i);
            mInterface = usbInterface;
            break;
        }
        //用UsbDeviceConnection 与 UsbInterface 进行端点设置和通讯
        if (mInterface.getEndpoint(1) != null) {
            usbEpOut = mInterface.getEndpoint(1);
        }
        if (mInterface.getEndpoint(0) != null) {
            usbEpIn = mInterface.getEndpoint(0);
        }
        if (mInterface != null) {
            // 判断是否有权限
            if (manager.hasPermission(mUsbDevice)) {
                // 打开设备,获取 UsbDeviceConnection 对象,连接设备,用于后面的通讯
                mDeviceConnection = manager.openDevice(mUsbDevice);
                if (mDeviceConnection == null) {
                    return;
                }
                if (mDeviceConnection.claimInterface(mInterface, true)) {
                    showTmsg("找到设备接口");
                } else {
                    mDeviceConnection.close();
                }
            } else {
                showTmsg("没有权限");
            }
        } else {
            showTmsg("没有找到设备接口!");
        }
    }

    private void initViews() {
        this.read_btn = (Button) findViewById(R.id.read_btn);
        this.write_btn = (Button) findViewById(R.id.write_btn);
        this.read_btn.setOnClickListener(this);
        this.write_btn.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.write_btn:
                sendToUsb("按照规则给设备发指令!");
                break;
            case R.id.read_btn:
                readFromUsb();
                break;
        }
    }

    private void sendToUsb(String content) {
        sendbytes = content.getBytes();
        int ret = -1;
        // 发送准备命令
        ret = mDeviceConnection.bulkTransfer(usbEpOut, sendbytes, sendbytes.length, 5000);
        showTmsg("指令已经发送!");
        // 接收发送成功信息(相当于读取设备数据)
        receiveytes = new byte[128];   //根据设备实际情况写数据大小
        ret = mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 10000);
//        result_tv.setText(String.valueOf(ret));
        Toast.makeText(this, String.valueOf(ret), Toast.LENGTH_SHORT).show();
    }

    private void readFromUsb() {
        //读取数据2
        int outMax = usbEpOut.getMaxPacketSize();
        int inMax = usbEpIn.getMaxPacketSize();
        ByteBuffer byteBuffer = ByteBuffer.allocate(inMax);
        UsbRequest usbRequest = new UsbRequest();
        usbRequest.initialize(mDeviceConnection, usbEpIn);
        usbRequest.queue(byteBuffer, inMax);
        if (mDeviceConnection.requestWait() == usbRequest) {
            byte[] retData = byteBuffer.array();
            try {
                showTmsg("收到数据:" + new String(retData, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    //文字提示方法
    private void showTmsg(String msg) {
        Toast.makeText(UsbTestActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}


 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140

另外要与USB通信,在开发项目的配置上还需要注意: 
1,添加相应权限:

 <uses-permission android:name="android.permission.HARDWARE_TEST" />
 
 
  • 1

2,AndroidManifest.xml中添加uses-feature过滤所有你设备不支持的应用:

 <uses-feature android:name="android.hardware.usb.host" android:required="true"/>
 
 
  • 1

3, SDK必须是12以上的,因为从 Android3.1开始,才正式支持USB Host相应开发。 
4,在AndroidManifext.xml中对操作USB对应的Activity配置做修改,添加USB_DEVICE_ATTACHED与:

<activity android:name=".UsbTestActivity">
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>
 <!-- 以下这个meta-data是要手工增加上,他是用来过滤你的具体USB设备的,其中的device_filter是个xml文件 -->
            <meta-data
    android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/device_filter" />
        </activity>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

—–@xml/device_filter—–

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 以下内容的 vendor-id、product-id就是USB的vid和pid了,填写自己设备对应的数据->
    <usb-device vendor-id="1155" product-id="22352"/>
</resources>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5

参考博客:http://www.xuebuyuan.com/702736.html

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值