问题
I have a device which I need to connect via usb to my android phone. I simply want to read some data this device is sending and present it on my app screen. I've tried some API's such https://github.com/felHR85/UsbSerial and https://github.com/mik3y/usb-serial-for-android where I found the code below
public class MainActivity extends AppCompatActivity {
private TextView data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = findViewById(R.id.data);
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
if (availableDrivers.isEmpty()) {
return;
}
// Open a connection to the first available driver.
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
if (connection == null) {
// You probably need to call UsbManager.requestPermission(driver.getDevice(), ..)
return;
}
// Read some data! Most have just one port (port 0).
UsbSerialPort port = driver.getPorts().get(0);
try {
port.open(connection);
port.setParameters(57600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
byte buffer[] = new byte[8];
int numBytesRead = port.read(buffer, 1000);
//Log.d(TAG, "Read " + numBytesRead + " bytes.");
data.setText(numBytesRead);
} catch (IOException e) {
// Deal with error.
} finally {
try {
port.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
It simply does not read anything at all, is there a simpler way to do that?
The device I'm trying to read from is an oximeter (Ut-100). I only need some data to show up on the screen, is there a simple way to simple return an array of bytes and handle it by myself? Thanks for any help
回答1:
You can start with Android Developer documentation USB HOST MODE to understand how to communicate over USB.
You should start with the section USB host overview.
回答2:
Typically the UsbManager.requestPermission(...) handling is missing.
Please look at the recently enhanced examples @ https://github.com/mik3y/usb-serial-for-android
来源:https://stackoverflow.com/questions/56798092/how-to-read-data-from-usb-device-on-android