对此没有默认操作。
在您的自定义接收器中,获取端口并使用它。
这就是它喜欢的方式;
public class CustomBroadcastReceiver extends BroadcastReceiver {
public static final String BROADCAST = "arda.kaplan.android.action.broadcast";
@Override
public void onReceive(final Context context, Intent intent) {
findDevices(context);
}
private void findDevices(final Context context) {
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
final List<UsbSerialDriver> drivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
final List<UsbSerialPort> result = new ArrayList<>();
for (final UsbSerialDriver driver : drivers) {
final List<UsbSerialPort> ports = driver.getPorts();
result.addAll(ports);
}
if (result.size() > 0) {
UsbSerialPort usbSerialPort = result.get(0);
UsbSerialDriver driver = usbSerialPort.getDriver();
UsbDevice device = driver.getDevice();
UsbDeviceConnection usbConnection = usbManager.openDevice(usbSerialPort.getDriver().getDevice());
final UsbSerialDevice usbSerialDevice = UsbSerialDevice.createUsbSerialDevice(device, usbConnection);
usbSerialDevice.open();
usbSerialDevice.setBaudRate(9600);
usbSerialDevice.setDataBits(UsbSerialInterface.DATA_BITS_8);
usbSerialDevice.setStopBits(UsbSerialInterface.STOP_BITS_1);
usbSerialDevice.setParity(UsbSerialInterface.PARITY_NONE);
usbSerialDevice.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
usbSerialDevice.read(new UsbSerialInterface.UsbReadCallback() {
@Override
public void onReceivedData(final byte[] data) {
Intent startAppIntent = new Intent(context, ComingFromBroadcastReceiverActivity.class);
startAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startAppIntent.putExtra(ComingFromBroadcastReceiverActivity.KEY, new String(data));
context.startActivity(startAppIntent);
}
});
}
}
}
而这个注册自定义接收器的代码
Intent intent = new Intent(CustomBroadcastReceiver.BROADCAST);
Bundle extras = new Bundle();
sendBroadcast(intent);
这是明显的部分
<receiver android:name=".receivers.CustomBroadcastReceiver">
<intent-filter>
<action android:name="arda.kaplan.android.action.broadcast" />
</intent-filter>
</receiver>