How to read and write data to COM/Serial ports in Android?

▼魔方 西西 提交于 2019-11-28 20:50:53

Your problem is one with operating systems. Android runs Linux under the hood, and Linux treats serial ports differently than Windows does. javax.comm also contains win32com.dll, a driver file, which you won't be able to install on an Android device. If you do find a way to achieve what you're trying to do, you can't actually look for a "COM" port in a Linux environment. The serial ports will go by different names.

 Windows Com Port   Linux equivalent  
      COM 1           /dev/ttyS0  
      COM 2           /dev/ttyS1
      COM 3           /dev/ttyS2 

So, hypothetically, if your idea were to work, you have to look for these names.

Luckily for you, Android does have provisions for interfacing with USB devices (Which I assume you want to connect to, as opposed to parallel or RS-232 ports). To do this, you will set up your device as a USB Host. Here's what you'll want to do:

  1. Get a USBManager.
  2. Find your device.
  3. Get the USBInterface and USBEndpoint.
  4. Open a connection.
  5. Transfer data.

Here's my rough estimate of how you'll do it. Your code will, of course, have a more mature way of doing things.

String YOUR_DEVICE_NAME;
byte[] DATA;
int TIMEOUT;

USBManager manager = getApplicationContext().getSystemService(Context.USB_SERVICE);
Map<String, USBDevice> devices = manager.getDeviceList();
USBDevice mDevice = devices.get(YOUR_DEVICE_NAME);
USBDeviceConnection connection = manager.openDevice(mDevice);
USBEndpoint endpoint = device.getInterface(0).getEndpoint(0);

connection.claimInterface(device.getInterface(0), true);
connection.bulkTransfer(endpoint, DATA, DATA.length, TIMEOUT);

Extra material for your reading pleasure: http://developer.android.com/guide/topics/connectivity/usb/host.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!