Android 下通过android.hardware.usb实现usb监听接收数据发送数据源码

本文详细介绍了使用Android系统下的USB接口进行数据收发的具体实现方式。通过创建线程接收数据,利用bulkTransfer发送数据,并借助EventBus在主线程中接收消息。文章提供了完整的源码示例,展示了如何初始化USB设备,打开设备连接,获取输入输出端点,以及如何在接收到USB设备时启动通信。

用bulkTransfer发送数据

用一个线程接收数据

用EventBus传递消息

下面是usb接收发送源码

 private android.hardware.usb.UsbManager mUsbManager;
    private UsbDevice mUsbDevice;

    private UsbEndpoint mUsbHIDEndpointIn, mUsbHIDEndpointOut;
    private int mUsbHIDInMax, mUsbHIDOutMax;
    private UsbInterface mUsbHIDInterface;
    private UsbDeviceConnection mUsbDeviceConnection;
    private USBThreadDataReceiver usbThreadDataReceiver;
    private static UsbManager hidManager;
    private Context context;

    private int receivedMode = 0;
    private int TIME_OUT_TIME = 100;
    private int TIME_OUT = 0;

    //MessageUtils oneMsgUtils = new MessageUtils();

    public static UsbManager newInstance(Context context) {
        if (hidManager == null) {
            hidManager = new UsbManager(context);
            EventBus.getDefault().register(hidManager);
        }
        return hidManager;
    }

    public static String getVersion() {
        return "1.1";
    }

    private UsbManager(Context context) {
        this.context = context;

    }

    public void start()
    {
        mUsbDevice = null;
        registerReceiver();
        startDevice();
    }

    private void onDeviceFound(UsbDevice device) {
        if (device != null && device.getProductId() == TargetProductId && device.getVendorId() == TargetVendorId) {
            mUsbDevice = device;
            if (mUsbManager.hasPermission(device))
            {
                initCommunication(mUsbDevice);
            }
            else {
                mUsbManager.requestPermission(device, mPermissionIntent);
            }
        }
    }

    private void onDeviceDelete(UsbDevice device) {
        if (device != null && device.getProductId() == TargetProductId && device.getVendorId() == TargetVendorId)
        {
        }
    }

    private void startDevice() {
        mUsbManager = (android.hardware.usb.UsbManager) context.getSystemService(Context.USB_SERVICE);
        if (mUsbManager == null)
        {

            return;
        }

        mPermissionIntent = PendingIntent.getBroadcast(context, 0,
                new Intent(ACTION_USB_PERMISSION), 0);</

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值