Is possible to have an app written in flutter that send data to another app in android? through EventChannels

1.2k views Asked by At

Can you explain how to communicate from an application A written in flutter to an application written in Android B. Is possible use EventChannels for this purpose? If it is possible this communication is bidirectional?

An example is here (FLUTTER APP A):

import 'dart:async';

import 'package:flutter/services.dart';

class MyEventChannel {
  static const MethodChannel _channel =
      const MethodChannel('my_event_channel');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Stream<String> get messageStream {
    return _channel.receiveBroadcastStream('message');
  }
}

void _sendMessage(String message) {
MyEventChannel.platformVersion.then((version) {
  if (version == 'Android') {
    MyEventChannel._channel.invokeMethod('sendMessage', message);
  }
});


}

Android APP B:

import android.content.Context;

import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

public class MyEventChannel implements MethodCallHandler {
  private final Context context;

  private MyEventChannel(Context context) {
    this.context = context;
  }

  public static void registerWith(Registrar registrar) {
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "my_event_channel");
    channel.setMethodCallHandler(new MyEventChannel(registrar.context()));

    final EventChannel eventChannel = new EventChannel(registrar.messenger(), "message");
    eventChannel.setStreamHandler(new EventChannel.StreamHandler() {
      @Override
      public void onListen(Object args, EventChannel.EventSink events) {
        // Handle messages received from Flutter
      }

      @Override
      public void onCancel(Object args) {
        // Handle cancel event
      }
    });
  }

  @Override
  public void onMethodCall(MethodCall call, Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android");
    } else if (call.method.equals("sendMessage")) {
      // Handle send message event
    } else {
      result.notImplemented();
    }
  }
}

We can have A send some message to B, and in other cases b send something to A? How it works this mechanism. There is poor documentation about this mechanism.

1

There are 1 answers

0
Maleesha97 On

It is possible to do this. However, you need to first pass the data that you need to send, Within the Flutter application from Flutter code to the Android native code. I will be addressing flutter app as App 1 and Android app App 2 in this example. And I will be sending a simple String in this app.

App 1 Flutter -

static const AndroidComChannel = MethodChannel('message_channel'); //provide a channel name

Future<Null> sendDataToAndroid(String message) async{
//Passing the message to Native code
try{

  final String returnResult = await AndroidComChannel.invokeMethod('setMessage',{"Message_tag":message});
  print("$returnResult");

}on PlatformException catch (e){
  print(e);
   }
}

App 1 Android Native Code-

private static final String CHANNEL = "message_channel";

//Put this method inside onCreate() in MainActivity.
 @Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
    super.configureFlutterEngine(flutterEngine);

    BinaryMessenger messenger = flutterEngine.getDartExecutor().getBinaryMessenger();

    new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
            .setMethodCallHandler(
                    (call, result) -> {
                     onMethodCall(call,result);
                    }
            );
}


private void onMethodCall(MethodCall call, MethodChannel.Result result){
    if(call.method.equals("setMessage")){
        String messageText = call.argument("Message_tag");
        //To do Implement here
        result.success("Message Received");
    }
    else{
        result.notImplemented();
    }
}

Then you can send data from App 1 to App 2 using a broadcast receiver in Native code like this

And in a case where you receive something from App 2 to App 1, You can capture data using a Broadcastreceiver as you did in App 2 above. To send the data from Native code to Flutter, Refer this video. It demonstrates of using EventChannels, MethodsChannels to call a Flutter method from Android Native code.