Flutter开发之——Android通信-EventChannel

一 概述

  • 创建Flutter端EventChannel
  • 创建Android端EventChannel
  • 在合适的地方调用EventChannel

二 EventChannel通信示例

2.1 Flutter 端创建 EventChannel 通道

void main() => runApp(EventChannelDemo());

class EventChannelDemo extends StatefulWidget {
  @override
  _EventChannelDemoState createState() => _EventChannelDemoState();
}

class _EventChannelDemoState extends State<EventChannelDemo> {

  var _eventChannel = EventChannel('com.example.androidflutter.EventChannelDemo');
  var _data;
  @override
  void initState() {
    super.initState();
    _eventChannel.receiveBroadcastStream().listen(_onData);
  }

  _onData(event){
    setState(() {
      _data = event;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Flutter EventChannel")),
        body: Center(
          child: Text('$_data'),
        ),
      ),
    );
  }
}

2.2 Android端创建 EventChannel 通道

class EventChannelDemo(var activity: Activity, messenger: BinaryMessenger): EventChannel.StreamHandler {
    private var channel: EventChannel
    private var index = 0
    private var events: EventChannel.EventSink? = null
    init {
        channel = EventChannel(messenger, "com.example.androidflutter.EventChannelDemo")
        channel.setStreamHandler(this)
        startTimer()
    }
    fun startTimer() {
        var timer = Timer().schedule(timerTask {
            index++
            var map = mapOf("name" to "张三 ${index}",
                "age" to "${index}"
            )
            activity.runOnUiThread {
                events?.success(map)
            }

        }, 0, 1000)

    }
    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        this.events = events
    }

    override fun onCancel(arguments: Any?) {
        this.events = null
    }
}

2.3 调用处

class MainActivity : FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        EventChannelDemo(this,flutterEngine.dartExecutor.binaryMessenger)
    }
}

2.4 效果图

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值