2
我嘗試發送命令到我的USB自定義設備。我認爲我將所有設置妥當 - 例如我可以獲取設備的ID,以便Android「看到」它。然而,當我嘗試發送它的命令時,我得到了一行空指針:USBConnection nullPointerException
connection.bulkTransfer(usbEndpointOut,send,send.length,SEND_TIMEOUT);
端點設置正確(我在日誌中檢查過它)。這是我的班級。請幫忙。
mTestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
UsbDevice device;
if (usbDevices != null) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
if (deviceVID != 0x1d6b || (devicePID != 0x0001 || devicePID != 0x0002 || devicePID != 0x0003)) {
Toast.makeText(MainActivity.this, "ID: " + device.getDeviceId()
, Toast.LENGTH_SHORT).show();
Log.e(TAG, "onCreate: " + device.getDeviceId());
UsbInterface usbInterface = null;
UsbEndpoint usbEndpointIn = null;
UsbEndpoint usbEndpointOut = null;
for (int i = 0; i < device.getInterfaceCount(); i++) {
usbInterface = device.getInterface(i);
//l("Interface[" + i + "] -> " + usbInterface);
if (usbInterface != null) {
for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
UsbEndpoint usbEndpoint = usbInterface.getEndpoint(j);
//l("Endpoint[" + j + "] -> " + usbEndpoint);
if (usbEndpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (usbEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
//l("Found input!");
usbEndpointIn = usbEndpoint;
} else {
//l("Found output!");
usbEndpointOut = usbEndpoint;
}
if (usbEndpointIn != null && usbEndpointOut != null) {
break;
}
}
}
if (usbEndpointIn != null && usbEndpointOut != null) {
break;
}
} else {
//l("Interface was null");
}
}
connection = usbManager.openDevice(device);
connection.bulkTransfer(usbEndpointOut, send, send.length, SEND_TIMEOUT);
keep = false;
} else {
{
connection = null;
device = null;
}
if (!keep)
break;
}
}
}
}
});
}
private static final byte[] send = new byte[]{
(byte) 0xDA, (byte) 0xAD, // const
(byte) 0x02, (byte) 0x74, (byte) 0x00, // com
(byte) 0xBF, (byte) 0xDB // last
};