Android 下通過android.hardware.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);

        HashMap<String, UsbDevice> deviceHashMap = mUsbManager.getDeviceList();
        Iterator<UsbDevice> iterator = deviceHashMap.values().iterator();
        while (iterator.hasNext())
        {
            UsbDevice device = iterator.next();

            Log.i("-----device found:",device.toString());
            if (device.getProductId() == TargetProductId && device.getVendorId() == TargetVendorId)
            {
                onDeviceFound(device);
                break;
            }
        }

        if (mUsbDevice == null)
        {
            //Toast.makeText(context.getApplicationContext(), "未連接到設備", LENGTH_SHORT).show();
            Log.i("-----device not found:","not connect the device");
        }
    }

    private void registerReceiver()
    {
        IntentFilter usbFilter = new IntentFilter(ACTION_USB_PERMISSION);
        usbFilter.addAction(android.hardware.usb.UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbFilter.addAction(android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED);

        usbFilter.addAction(ACTION);
        Log.i("-----registerReceiver","");
        context.getApplicationContext().registerReceiver(mUsbReceiver, usbFilter);
    }

    public void stop()
    {
        Log.i("-----stop","");
        try
        {
            if (mUsbReceiver != null)
            {
               Log.i("---unregisterReceiver","");
                context.getApplicationContext().unregisterReceiver(mUsbReceiver);
            }

            if (usbThreadDataReceiver != null)
                usbThreadDataReceiver.stopThis();
            usbThreadDataReceiver = null;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            UsbDevice device = (UsbDevice) intent.getParcelableExtra(android.hardware.usb.UsbManager.EXTRA_DEVICE);

            if (android.hardware.usb.UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                Log.i("ACTION_USB_DEVICE_IN","");
                onDeviceFound(device);
            } else if (android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                onDeviceDelete(device);
            } else if (ACTION_USB_PERMISSION.equals(action)) {

                if (intent.getBooleanExtra(android.hardware.usb.UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (device != null) {
                        Log.i("ACTION_USB_PERMISSION","");
                        initCommunication(mUsbDevice);
                    }
                } else {
                    Log.i("permission denied for " , device.toString());
                }
            }
        }
    };

    private void initCommunication(UsbDevice device) {
        if (device != null && TargetVendorId == device.getVendorId() && TargetProductId == device.getProductId()) {
            int interfaceCount = device.getInterfaceCount();
            if (interfaceCount <= 0)
            {
                return;
            }

            mUsbDeviceConnection = mUsbManager.openDevice(device);

            for (int i = 0; i < interfaceCount; i++)
            {
                mUsbHIDInterface = device.getInterface(i);

                int endpointCount = mUsbHIDInterface.getEndpointCount();
                for (int j = 0; j < endpointCount; j++)
                {
                    if (UsbConstants.USB_DIR_IN == mUsbHIDInterface.getEndpoint(j).getDirection())
                    {
                        mUsbHIDEndpointIn = mUsbHIDInterface.getEndpoint(j);
                        mUsbHIDInMax = mUsbHIDEndpointIn.getMaxPacketSize();
                    }
                    if (UsbConstants.USB_DIR_OUT == mUsbHIDInterface.getEndpoint(j).getDirection())
                    {
                        mUsbHIDEndpointOut = mUsbHIDInterface.getEndpoint(j);
                        mUsbHIDOutMax = mUsbHIDEndpointOut.getMaxPacketSize();
                    }
                }

                if (mUsbDeviceConnection != null && mUsbHIDEndpointOut != null && mUsbHIDEndpointIn != null)
                {
                    break;
                }
            }

            if (null == mUsbDeviceConnection)
            {
            }
            else

                {
                if (mUsbHIDEndpointOut != null)
                    mUsbDeviceConnection.claimInterface(mUsbHIDInterface, true);
            }

            //Toast.makeText(context.getApplicationContext(), "連接到設備", LENGTH_SHORT).show();

            usbThreadDataReceiver = new USBThreadDataReceiver();
            usbThreadDataReceiver.start();
        }
    }

    private byte[] blockData = null;
    private int blockDataLen, LENTH = 1024;
    private int dataLen = 0;

    private int num = 0;


boolean bSend = false;
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEventMainThread(EventUtil eventUtil){

    }

    byte[] cmd = new byte[256];
    public boolean sendData(byte[] content)
    {
        //return formatCmd(string);
        if (mUsbDevice != null
                && mUsbHIDEndpointOut != null
                && mUsbManager.hasPermission(mUsbDevice))
        {
            //test
            Arrays.fill(cmd, (byte) 0x00);
            //System.arraycopy(content, 0, cmd, 0, content.length);
            cmd[0]= (byte) 0x01;
            for (int i=1;i<=content.length;i++)
            {
                cmd[i]=content[i-1];
            }
           int ret = mUsbDeviceConnection.bulkTransfer(mUsbHIDEndpointOut, cmd, cmd.length, 100);
            //Log.i("Test send ",+ ret +"---"+ Commom_Function.byte2hex(cmd));
            return  ret > 0;
        }
        return  false;
    }

    byte[] recBuffer = new byte[256];
    EventUtil sentEvent = new EventUtil("Buffer",recBuffer);
    private class USBThreadDataReceiver extends Thread {

        private volatile boolean isStopped;

        public USBThreadDataReceiver() {
        }
        @Override
        public void run()
        {
            try {
                if (mUsbDeviceConnection != null && (mUsbHIDEndpointIn != null)) {
                    while (!isStopped)
                    {
                        if (mUsbHIDEndpointIn != null) {

                            int status = mUsbDeviceConnection.bulkTransfer(mUsbHIDEndpointIn, recBuffer, 256, 100);
                            //int status = mUsbDeviceConnection.controlTransfer(0xA1,0x01,0x301,0,recBuffer,256,1000);

                            if (status > 0)
                            {
                                //String string = Commom_Function.byte2hex(recBuffer);
                                //Log.i("Test received :" ,status +" length , data is " + string);
                                sentEvent.setParam(recBuffer);
                                EventBus.getDefault().post(sentEvent);
                               // MessageUtils.doCallBackMethod(recBuffer);
                            }
                        }
                        Thread.sleep(3);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Error in receive thread", e.getMessage());
            }
        }

        public void stopThis() {
            isStopped = true;
        }
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章