felHR85 / UsbSerial

Usb serial controller for Android
MIT License
1.81k stars 589 forks source link

null port error #295

Open teambrainoidtech opened 4 years ago

teambrainoidtech commented 4 years ago

In broadcast receiver i am getting null port. even after connecting the device. please help me out on this. i am trying to connect to ch340 device.

here is small code snippet

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
            boolean granted =
                    intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
            if (granted) {
                usbConnection = usbManager.openDevice(device);
                serialPort = UsbSerialDevice.createUsbSerialDevice(device, usbConnection);
                if (serialPort != null) {
                    if (serialPort.open()) { //Set Serial Connection Parameters.
                       // setUiEnabled(true); //Enable Buttons in UI
                        serialPort.setBaudRate(9600);
                        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(mCallback); //
                        tvAppend(textView, "Serial Connection Opened!\n");

                    } else {
                        Log.d("SERIAL", "PORT NOT OPEN");
                    }
                } else {
                    Log.d("SERIAL", "PORT IS NULL");
                }
            } else {
                Log.d("SERIAL", "PERM NOT GRANTED");
            }
        } else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
            onClickStart();
        } else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
            closeCon();
        }
    }

};
ge0rg commented 6 months ago

Looks like I'm also encountering an NPE, specifically in the intent.getExtras() call. The UsbManager permissions intent doesn't have any extras on some devices (on Android 8 only?), leading to a crash. Have you found a solution / workaround for your case?