How to pend flutter method channel callback (android native java code) for an android listener

Viewed 65

I have a flutter app that run a java code in some situations. I wrote java code in method call handler in MethodCahnnel. In this callback I call another method that is communicate with a serial port using usb-serial-for-android and wait for data in onNewData listener. I want to send back this data to flutter. and I am using a class variable for it and fill it in onNewData method. and use result.success conditionaly when the variable is not empty! but result.success never called and if I delete the if statement, result.success called when the variable is empty.

Here is the section of my code:

public class MainActivity extends FlutterActivity implements SerialInputOutputManager.Listener {

    private static final String CHANNEL = "channel";

    private UsbSerialPort connectionPort;
    private String response = "";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) -> {
                                    select();
                                    if (!response.isEmpty()) result.success(response);
                        }
                );
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (intent.getAction().equals("android.hardware.usb.action.USB_DEVICE_ATTACHED")) {
            Toast.makeText(this, "new usb device detected!", Toast.LENGTH_SHORT).show();
        }
        super.onNewIntent(intent);
    }

    private void select() {
        connectionPort.write(...);
    }

    @Override
    public void onNewData(byte[] data) {
        response = Utils.byteArrayToHexString(data);
    }

    @Override
    public void onRunError(Exception e) {
        status("error onRunError" + e.getMessage());
    }
}
0 Answers
Related