【发布时间】:2016-05-24 07:08:52
【问题描述】:
我尝试连接我的自定义 USB 设备。我已经使用 android doc 一步一步地完成了所有工作,但我仍然在连接对象处得到空指针。这是我的活动:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(usbReceiver, filter);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceIterator.next();
if (device.getVendorId() == 1659 && device.getProductId() == 8963) {
this.device = device;
usbManager.requestPermission(device, mPermissionIntent);
Toast.makeText(MainActivity.this, "vendor: " + device.getVendorId() + "ID " + device.getProductId() , Toast.LENGTH_SHORT).show();
break;
}
}
这就是我尝试连接 USB 设备的方式:
mTestButton = (Button) findViewById(R.id.button);
mTestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
usbInterface = device.getInterface(0);
if (connection != null) {
connection = usbManager.openDevice(device);
connection.claimInterface(usbInterface, false);
for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
UsbEndpoint end = usbInterface.getEndpoint(i);
if (end.getDirection() == UsbConstants.USB_DIR_IN) {
usbEndpointIn = end;
} else {
usbEndpointOut = end;
}
}
//SEND START COMMAND TO THE USB DEVICE;
int result = connection.bulkTransfer(usbEndpointOut, "START".getBytes(), "START".getBytes().length, 1000);
Log.e("SEND RESULT", result + "");
//START READING in run method
readThread = new Thread((Runnable) MainActivity.this);
readThread.start();
} else {
Toast.makeText(MainActivity.this, "Connection is null", Toast.LENGTH_SHORT).show();
}
但是连接仍然是空的:/请帮助。
【问题讨论】:
-
您是否在 androidManifest.xml 中添加了 usb 权限?
-
获取usbReceiver中的连接对象。在接收器中: boolean grant = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED); if (granted) { connection = usbManager.openDevice(device); }
标签: java android usb usb-drive