android - 多次调用 USB 广播接收器
问题描述
我正在创建一个通过 USB 连接到 Arduino 的应用程序。连接工作正常,我可以正确传输和接收数据。我的问题是连接和断开 USB 时。
出于某种原因,每次我通过 USB 连接或断开 Arduino 时,BroadcastReceives
都会调用 2 到 4 次,有时 Arduino 甚至根本没有连接。
我的BroadcastReceiver
实现:
public static class ArduinoConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
switch(intent.getAction()) {
case ArduinoConfigurations.ACTION_USB_PERMISSION:
if (intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED)) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
serialPort.setBaudRate(115200);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(new ArduinoCallback());
Log.d("ARDUINO", "Arduino connected!");
((MainActivity)context).enableButtons(true);
} else
Log.e("ARDUINO", "Port not open, not possible to connect.");
} else
Log.e("ARDUINO", "Port is null, not possible to connect.");
} else
Log.e("ARDUINO", "Permission not granted, not possible to connect.");
break;
case UsbManager.ACTION_USB_DEVICE_ATTACHED:
openConnection((MainActivity)context);
break;
case UsbManager.ACTION_USB_DEVICE_DETACHED:
default:
closeConnection((MainActivity)context);
break;
}
...
有时它也会抛出:
exception in UsbManager.openDevice
java.lang.IllegalArgumentException: device /dev/bus/usb/003/012 does not exist or is restricted
at android.os.Parcel.readException(Parcel.java:1688)
at android.os.Parcel.readException(Parcel.java:1637)
at android.hardware.usb.IUsbManager$Stub$Proxy.openDevice(IUsbManager.java:411)
at android.hardware.usb.UsbManager.openDevice(UsbManager.java:330)
...
和
Error on connecting Arduino: Attempt to invoke virtual method 'boolean android.hardware.usb.UsbDeviceConnection.claimInterface(android.hardware.usb.UsbInterface, boolean)' on a null object reference
我读过USB连接器有时真的很不稳定。但仅此而已吗?我可以解决这个问题,以便 Arduino 只连接和断开一次吗?
解决方案
推荐阅读
- reactjs - react-pose:如何在 react-pose 中定义道具的类型?(道具隐含任何类型)
- rss - Automatic mediawiki article generation with a script?
- amazon-s3 - Prevent httpclient from adding server url when calling presigned url
- javascript - Getting ↵ in my array while Getting data from td cells
- python - 假设我有一个清单。lst[0] 和 [lst[0]] 有什么区别?
- oracle - 查找日期相互重叠的记录
- apache-kafka - 使用 Kafka-MongoDB-Connect 将数据插入 MongoDB
- jquery - 在滚动条上隐藏 div
- chart.js - 如何减少任何图表中的边框宽度?
- reactjs - Is OnChange required for react forms anymore?