Flutter develops EventChannel for Android communication

  • Android sends messages
  • Note the following when sending messages on Android:
  • Android gets the current phone battery
  • The Flutter end receives messages

That calm, not indifferent, the inevitable fight, let nature take its course. Life is unpleasant nine out of ten things, things do not have to be too serious, do not be too demanding. Everything is fate, let nature take its course. Life sometimes must have, life without time don’t force. Indeed, this is a treacherous, competitive society, survival of the fittest, the unfit out.

Preface: In the previous chapter, we introduced BasicMessageChannel bidirectional communication, one of the hybrid Flutter development communications. In this chapter, we introduce the Event that Android sends messages to Flutter independently and continuously. The Flutter cannot send messages to Android and has no return value Channel

Let’s take a look at today’s results.

Rendering (1.1) :



Analysis:

The Android side:

  • A Button, a Text()
  • Text Displays the current power using the broadcast receiver

The Flutter end:

  • Receive data from Android and display it

Android sends messages

Step 1: Create EventChannel

 private final EventChannel eventChannelPlugin;

 eventChannelPlugin = new EventChannel(messenger, "demo.ht.com.androidproject/EventChannelPlugin");
Copy the code
  • Parameter 1 :BinaryMessenger Messenger tool for sending messages
  • Parameter 2 :String name Channel name Unique identifier (andRendering (1.2)Corresponding)

Rendering (1.2)

Second, send the message via setStreamHandler()

public class EventChannelPlugin implements EventChannel.StreamHandler {
	eventChannelPlugin.setStreamHandler(this);

	 @Override
    public void onListen(Object args, EventChannel.EventSink eventSink) {
        // To send a message
        eventSink.success(ElectricityQuantity);
    }

    @Override
    public void onCancel(Object o) {}}Copy the code

The message is sent by overriding the eventSink parameter in the onListen() method

Call eventsink.success (” Message to send, current is power “);

Complete code for EventChannelPlugin:

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;
/ * * * SZJ 2020/11/26 * CSDN blog: https://blog.csdn.net/weixin_44819566/ * WeChat public: code on rich * EventChannelPlugin * change for data flow (the event * For example: mobile phone battery change, network connection change, gyroscope, sensor, etc.; * /
public class EventChannelPlugin implements EventChannel.StreamHandler {
    private final String ElectricityQuantity;

    / * * * *@paramMessenger A tool for sending messages@paramElectricityQuantity Current quantity */
    public static void registerWith(BinaryMessenger messenger, String ElectricityQuantity) {
        new EventChannelPlugin(messenger, ElectricityQuantity);
    }

    private EventChannelPlugin(BinaryMessenger messenger,String ElectricityQuantity) {
        this.ElectricityQuantity = ElectricityQuantity;

        EventChannel eventChannelPlugin = new EventChannel(messenger, "demo.ht.com.androidproject/EventChannelPlugin");

        eventChannelPlugin.setStreamHandler(this);
    }
    @Override
    public void onListen(Object args, EventChannel.EventSink eventSink) {
        // To send a message
        eventSink.success(ElectricityQuantity);
    }

    @Override
    public void onCancel(Object o) {}}Copy the code

Note the following when sending messages on Android:

The getCachedEngineId() method needs to be commented out in The FlutterAppActivity. This method cannot be called with EventChannel, otherwise the second step, sending a message via setStreamHandler(), will not be performed. FlutterAppActivity can view Flutter mixed development to transfer initialization data to Android(4.2)

At this point,Android is done sending a message

Android gets the current phone battery

I pasted the code from the Internet and shared it with you

IntentFilter = new IntentFilter(IntentFilter.ACTION_BATTERY_CHANGED); * receiver = new BatteryReceiver(textView); * registerReceiver(receiver, filter); * /
public class BatteryReceiver extends BroadcastReceiver {
    private TextView pow;

    public BatteryReceiver(TextView pow) {
        this.pow = pow;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int current = intent.getExtras().getInt("level");// Get the current power
        int total = intent.getExtras().getInt("scale");// Get the total power
        int percent = current * 100 / total;
        pow.setText(percent + "%"); }}Copy the code

Use: Just pass the textView object in.

 IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
 receiver = new BatteryReceiver(textView);
 registerReceiver(receiver, filter);
Copy the code

The Flutter end receives messages

Step 1: /// EventChannel receives the battery sent by Android

  /// EventChannel receives the power sent by Android
  EventChannel _eventChannelPlugin = EventChannel("demo.ht.com.androidproject/EventChannelPlugin");
Copy the code

Corresponding to the effect drawing (1.3)

Rendering (1.3):

The second step:

	String _eventMessage; // To receive EventMes charge

	// Use Event to receive power messages
    _eventChannelPlugin.receiveBroadcastStream().listen((event) {
      setState(() {
	        _eventMessage = event;
      });
    });
Copy the code

The event here is the message sent by Android

Take a look at the effect:

The complete code

What do you like?

Android jump page, FLutter engine, etc. (4.1)

Pass initialization data to Android for Flutter hybrid development (4.2)

BasicMessageChannel and native android communication (4.3)

MethodChannel of Flutter hybrid development one-way message passing (4.5)

How to convert a Flutter project into a Module into an Android project (4.6)

Original is not easy, your thumbs up is my biggest support, leave your thumbs up ~