我正在使用GitHub上的库与USB设备进行串行通信。 https://github.com/felHR85/SerialPortExample
我的要求是将USB连接到android设备时从USB读取数据。因此,我创建了一个广播来调用readUsb()操作。但是问题是UsbSerialInterface.UsbReadCallback在我从android设备上删除USB之前不会返回任何值。但是,如果我在按钮单击上调用readUsb()操作,则可以正常运行。
当USB服务返回USB可以进行通信时,创建了两个不同的广播,试图调用readUsb()。
主要活动
/*
* Notifications from UsbService will be received here.
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action) || UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)) {
readUsb();
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action) || UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
}
}
}
}
};
/*
* This handler will be passed to UsbService. Data received from the serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
mActivity.get().display.append("Handle:");
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
// Do operations with data over here.
break;
}
}
}
我希望能够通过连接的USB呼叫usbRead,并需要断开USB才能获得USB响应。
答案 0 :(得分:0)
在清单中添加此代码
<receiver
android:name=".MainActivity$BootUpReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
然后在MainActivity中运行广播接收器
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(bootupreceiver);
}
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("USB", "Decive Connected -> " + action);
if (action.equalsIgnoreCase(ACTION_USB_ATTACHED)) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
tv_otg.setText("External OTG storage device connected !");
Log.e("true", "true");
}
} else if (action.equalsIgnoreCase(ACTION_USB_DETACHED)) {
tv_otg.setText("External OTG storage device disconnected !");
Log.e("false", "false");
}
}
}
还添加oncreate()进行注册。必须在onDestroy()方法中注销。
bootupreceiver = new BootUpReceiver();
IntentFilter filter = new IntentFilter(ACTION_USB_ATTACHED);
filter.addAction(ACTION_USB_DETACHED);
filter.setPriority(100);
registerReceiver(bootupreceiver, filter);