对于我的应用程序,我需要与连接的Arduino设备建立连接,这是代码:
public String openConnection(UsbManager manager, Context context) {
// getting the driver with an external library...
UsbSerialDriver driver = availableDrivers.get(0);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
manager.requestPermission(driver.getDevice(), pi);
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
if (connection == null) {
return "Found a device, but cannot connect";
}
// otherwise, continue and do stuff
}
问题在于,当连接了设备时,第一次打开应用程序时,它会显示警告,要求获得许可,但是如果单击“确定”,则连接为空,因此连接会提前返回。但是,第二次它不要求任何许可,而是打开了连接并且一切正常。
为什么会这样?
我知道这不是打开USB连接的最正确方法,但是我还有其他并非该问题固有的问题,因此我很想了解为什么会发生 比我应该做什么
我正在Android 8.1.0上对此进行测试
答案 0 :(得分:1)
尝试先前请求许可,并从侦听所授予的USB许可的广播接收器中启动其余代码。 这显示在Google的文档中:
private static final String ACTION_USB_PERMISSION =
"com.android.example.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
//call method to set up device communication
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
这是您注册广播接收器的方法:
UsbManager mUsbManager = (UsbManager)
getSystemService(Context.USB_SERVICE);
private static final String ACTION_USB_PERMISSION =
"com.android.example.USB_PERMISSION";
...
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new
Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
然后从以下所有内容开始:
UsbDevice device;
...
mUsbManager.requestPermission(device, mPermissionIntent);
通过这种方式,设备甚至会在授予许可之前尝试连接到USB,因此它将失败。