Home » Android » Usb data cable communication in Android

Usb data cable communication in Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I want to communicate with my android application from my computer with the usb data cable. What listener should I implement?

I think a TCP connection will suit my needs but connecting with it over the adb driver seems akward.

How can I communicate from windows to android using a data cable?

How to&Answers:

I found a nice post about this subject here. You basically need adb in order to do the port forwarding between the Android device and the PC. As an example:

C:\android-sdk-windows\tools\adb.exe forward tcp:38300 tcp:38300

Then you can use standard socket programming, both in the Android device and in the PC.

Answer:

Android supports a variety of USB peripherals and Android USB accessories (hardware that implements the Android accessory protocol) through two modes: USB accessory and USB host. In USB accessory mode, the external USB hardware act as the USB hosts.

for more info see: USB Host and Accessory and example click here

Answer:

You need to have an USB data transfer cable (also called USB data link cable) which
support API or SDK, then use the following code:

void usb2usbComm() 
{
BYTE        buf[65530];
LPU2URET    pU2uRet;
BOOL        bRet;
int         ret;
CString     msgstr;

ret = u2u_open();
if (ret == -1){
    AfxMessageBox("Open U2U device Success.");
}else{
    msgstr.Format("Open U2U device fail,return:%d", ret);
    AfxMessageBox(msgstr);
    return;
}

//send data
bRet = u2u_SendData(buf, 65530, ret);
if(!bRet)
{
    msgstr.Format("Send data error,return:%d", ret);
    AfxMessageBox(msgstr);
    return;
}

//receive data
while (1){
    bRet = u2u_RecvData(recvData, dataLen, ret);
    if( !bRet )
    {
        msgstr.Format("Receive data error,return:%d", ret);
        AfxMessageBox(msgstr);
        u2u_close();
        return;
    }else{
        break;
    }
}
u2u_close();


}

See:
Reference1, Reference2

Answer:

If data volume is low you might just copy files back and forth by using MTP protocol. Readily available on most devices and does not require enabling USB debugging or using USB accessory mode.