Trouble sending Uint8List from Flutter to Android[Java] using method channels

517

before I start explaining what happened let me show you something in dart first

Uint8List li = Uint8List.fromList([-2, 100, 32]);
li.cast<int>();
print(li); //prints [254, 100, 32]

so why -2 changed to positive 254? short explaining would be that dart expect the bytes in Uint8List to be Unsigned values so it prints the positive value 254 but still they are just bytes,

on the contrary in java the default is Signed bytes, and it doesn't care how it prints bytes because they are still bytes so I can tell you happily that is nothing wrong with your code, the actual problem that you tried to see the bytes value through printing the byte list, another sources: https://stackoverflow.com/a/9609437/11252816 , https://stackoverflow.com/a/9609516/11252816

Share:
517
DrkStr
Author by

DrkStr

Jack of many trades.

Updated on December 27, 2022

Comments

  • DrkStr
    DrkStr over 1 year

    I have a method channel setup on Flutter to send Uint8List to Android[Java]. Android is receiving the data but it looks like the bytes are getting wrapped at 127.

    Ex: if I send [254, 100, 32] from flutter, it shows up as [-2, 100, 32] in Android.

    Basically, any value in the list over 127 is getting converted to a negative value.

    Here is how I have the method channel setup on the Fluter side:

    static const MethodChannel platform = MethodChannel(SEND_SERIAL_MESSAGE_TO_ANDROID);
    
    Future<void> sendMessageToAndroid(List<int> message) async {
    
      final bool result = await platform.invokeMethod('parseMessage', message);
    }
    

    And this is how I am receiving it on the Android side

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) -> {
                            if (call.method.equals("parseMessage")) {
                                byte[] message = call.arguments();
                                parseMessage(message);
                            } else {
                                result.notImplemented();
                            }
                        }
    
                );
    }
    
    private void parseMessage(byte[] message){
        Log.i(LOG_TAG, message.toString());
    }
    

    Question: how do I stop values over 127 in my Uint8List from getting converted to a negative value in Java?

    Let me know if you need to see any more of my code.