4

我用串口通讯系统做了一个应用程序。但我需要这个。当接收到串行数据时,应用程序触发并打开屏幕。

我已经使用了 USB_DEVICE_ATTACHED,但我需要类似“USB_DATA_RECEIVED”的操作。可能吗?

XXX是我需要的动作。

<receiver
        android:name=".receivers.SerialDataReceiver"
        android:enabled="true">

        <intent-filter>
            <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            <action android:name="android.hardware.usb.action.XXX" />
        </intent-filter>
</receiver>
4

1 回答 1

1

对此没有默认操作。

在您的自定义接收器中,获取端口并使用它。

这就是它喜欢的方式;

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>
于 2016-10-14T12:01:34.270 回答