日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
一篇看懂Android與Flutter之間的通信

Flutter作為一種跨平臺(tái)解決方案,經(jīng)常會(huì)作為一個(gè)模塊嵌入到原生Android與iOS應(yīng)用中,F(xiàn)lutter與Android原生端的通信必不可少。所以本文就來(lái)講述一下Android如何與flutter進(jìn)行通信。

我們提供的服務(wù)有:成都做網(wǎng)站、成都網(wǎng)站建設(shè)、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、海興ssl等。為近千家企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的海興網(wǎng)站制作公司

1、架構(gòu)概述

消息通過(guò)平臺(tái)通道在native(host)與flutter(client)之間傳遞,如下圖所示:

為了確保用戶界面能夠正確響應(yīng),消息都是以異步的方式進(jìn)行傳遞。無(wú)論是native向flutter發(fā)送消息,還是flutter向native發(fā)送消息。

在flutter中,MethodChannel可以發(fā)送與方法調(diào)用相對(duì)應(yīng)的消息。在native平臺(tái)上,MethodChannel在Android可以接收方法調(diào)用并返回結(jié)果。這些類可以幫助我們用很少的代碼就能開(kāi)發(fā)平臺(tái)插件。

注意:本節(jié)內(nèi)容來(lái)自flutter官網(wǎng),讀者可自行查閱。

2、平臺(tái)通道數(shù)據(jù)類型支持和編解碼器

平臺(tái)通道可以使用提供的編解碼器對(duì)消息進(jìn)行編解碼,這些編解碼器支持簡(jiǎn)單類似JSON的值的高效二進(jìn)制序列化,例如布爾值,數(shù)字,字符串,字節(jié)緩沖區(qū)以及這些的列表和映射。當(dāng)你發(fā)送和接收值時(shí),會(huì)自動(dòng)對(duì)這些值進(jìn)行序列化和反序列化。

下表顯示了如何在平臺(tái)端接收Dart值,反之亦然:

關(guān)于編解碼器,Android端提供了以下幾種。

  1. BinaryCodec:是最簡(jiǎn)單的一種編解碼器,其返回值類型與入?yún)⒌念愋拖嗤?,均為二進(jìn)制格式(ByteBuffer)。由于BinaryCodec在編解碼過(guò)程中什么都沒(méi)做,只是原封不動(dòng)的將二進(jìn)制數(shù)據(jù)返回。所以傳遞的數(shù)據(jù)在編解碼時(shí)會(huì)免于拷貝,這種方式在傳遞的數(shù)據(jù)量比較大時(shí)很有用。比如從Android側(cè)傳入一張圖片到Flutter側(cè)顯示。
  2. StandardMessageCodec:是BasicMessageChannel的默認(rèn)編解碼器,支持基礎(chǔ)數(shù)據(jù)類型、列表及字典等。在編碼時(shí)會(huì)先將數(shù)據(jù)寫(xiě)入到ByteArrayOutputStream流中,然后再將該流中的數(shù)據(jù)寫(xiě)入到ByteBuffer中。在解碼時(shí),直接從ByteBuffer中讀取數(shù)據(jù)。
  3. StandardMethodCodec:是基于StandardMessageCodec的封裝。是MethodChannel與EventChannel的默認(rèn)編解碼器。
  4. StringCodec:是用于字符串與二進(jìn)制數(shù)據(jù)之間的編解碼,其編碼格式為UTF-8。在編碼時(shí)會(huì)將String轉(zhuǎn)成byte數(shù)組,然后再將該數(shù)組寫(xiě)入到ByteBuffer中。在解碼時(shí),直接從ByteBuffer中讀取數(shù)據(jù)
  5. JSONMessageCodec:內(nèi)部調(diào)用StringCodec來(lái)實(shí)現(xiàn)編解碼。
  6. JSONMethodCodec:基于JSONMessageCodec的封裝??梢栽贛ethodChannel與EventChannel中使用。

ByteBuffer是Nio中的一個(gè)類,顧名思義——就是一塊存儲(chǔ)字節(jié)的區(qū)域。它有兩個(gè)實(shí)現(xiàn)類——DirectByteBuffer與HeapByteBuffer,DirectByteBuffer是直接在內(nèi)存中開(kāi)辟了一塊區(qū)域來(lái)存儲(chǔ)數(shù)據(jù),而HeapByteBuffer是在JVM堆中開(kāi)辟一塊區(qū)域來(lái)存儲(chǔ)數(shù)據(jù),所以要想數(shù)據(jù)在DirectByteBuffer中與HeapByteBuffer互通,就需要進(jìn)行一次拷貝。

3、通信方式

前面講了Android與flutter通信的一些基礎(chǔ)知識(shí),下面就進(jìn)入正題,來(lái)看Android如何與flutter進(jìn)行通信。

Android與Flutter之間的通信共有四種實(shí)現(xiàn)方式。

  1. 由于在初始化flutter頁(yè)面時(shí)會(huì)傳遞一個(gè)字符串——route,因此我們就可以拿route來(lái)做文章,傳遞自己想要傳遞的數(shù)據(jù)。該種方式僅支持單向數(shù)據(jù)傳遞且數(shù)據(jù)類型只能為字符串,無(wú)返回值。
  2. 通過(guò)EventChannel來(lái)實(shí)現(xiàn),EventChannel僅支持?jǐn)?shù)據(jù)單向傳遞,無(wú)返回值。
  3. 通過(guò)MethodChannel來(lái)實(shí)現(xiàn),MethodChannel支持?jǐn)?shù)據(jù)雙向傳遞,有返回值。
  4. 通過(guò)BasicMessageChannel來(lái)實(shí)現(xiàn),BasicMessageChannel支持?jǐn)?shù)據(jù)雙向傳遞,有返回值。

下面就來(lái)看一下這幾種方式的使用。

3.1、初始化時(shí)傳值

主要是利用了創(chuàng)建flutter頁(yè)面?zhèn)鬟f的route來(lái)做文章,筆者認(rèn)為該種方式屬于取巧,但還是可以用來(lái)傳遞數(shù)據(jù)。它的使用很簡(jiǎn)單,代碼如下。

首先來(lái)看Android代碼。

 
 
 
 
  1. //第三個(gè)參數(shù)可以換成我們想要字符串。 
  2. FlutterView flutterView = Flutter.createView(this, getLifecycle(), "route"); 

在flutter中,我們只需要通過(guò)下面代碼來(lái)獲取值即可。

 
 
 
 
  1. void main() => runApp(MyApp( 
  2.  initParams: window.defaultRouteName, 
  3.  )); 
  4. class MyApp extends StatelessWidget { 
  5.  final String initParams;//既是前面?zhèn)鬟f的值——route 
  6.  MyApp({Key key, @required this.initParams}) : super(key: key); 
  7.  @override 
  8.  Widget build(BuildContext context) {...} 

通過(guò)該種方式就可以在初始化flutter時(shí),Android給flutter傳遞數(shù)據(jù)。由于runApp僅會(huì)調(diào)用一次,所以該種方式只能傳遞一次數(shù)據(jù)且數(shù)據(jù)只能是字符串。

  • 使用window的相關(guān)API需要導(dǎo)入包dart:ui

3.2、EventChannel

EventChannel是一種native向flutter發(fā)送數(shù)據(jù)的單向通信方式,flutter無(wú)法返回任何數(shù)據(jù)給native。主要用于native向flutter發(fā)送手機(jī)電量變化、網(wǎng)絡(luò)連接變化、陀螺儀、傳感器等。它的使用方式如下。

首先來(lái)看Android代碼。

 
 
 
 
  1. public class EventChannelPlugin implements EventChannel.StreamHandler { 
  2.  private static final String TAG = EventChannelPlugin.class.getSimpleName(); 
  3.  private EventChannel.EventSink eventSink; 
  4.  private Activity activity; 
  5.  static EventChannelPlugin registerWith(FlutterView flutterView) { 
  6.  EventChannelPlugin plugin = new EventChannelPlugin(flutterView); 
  7.  new EventChannel(flutterView, "EventChannelPlugin").setStreamHandler(plugin); 
  8.  return plugin; 
  9.  } 
  10.  private EventChannelPlugin(FlutterView flutterView) { 
  11.  this.activity = (Activity) flutterView.getContext(); 
  12.  } 
  13.  void send(Object params) { 
  14.  if (eventSink != null) { 
  15.  eventSink.success(params); 
  16.  } 
  17.  } 
  18.  void sendError(String str1, String str2, Object params) { 
  19.  if (eventSink != null) { 
  20.  eventSink.error(str1, str2, params); 
  21.  } 
  22.  } 
  23.  void cancel() { 
  24.  if (eventSink != null) { 
  25.  eventSink.endOfStream(); 
  26.  } 
  27.  } 
  28.  //第一個(gè)參數(shù)為flutter初始化EventChannel時(shí)返回的值,僅此一次 
  29.  @Override 
  30.  public void onListen(Object o, EventChannel.EventSink eventSink) { 
  31.  this.eventSink = eventSink; 
  32.  Log.i(TAG, "eventSink:" + eventSink); 
  33.  Log.i(TAG, "Object:" + o.toString()); 
  34.  Toast.makeText(activity, "onListen——obj:" + o, Toast.LENGTH_SHORT).show(); 
  35.  } 
  36.  @Override 
  37.  public void onCancel(Object o) { 
  38.  Log.i(TAG, "onCancel:" + o.toString()); 
  39.  Toast.makeText(activity, "onCancel——obj:" + o, Toast.LENGTH_SHORT).show(); 
  40.  this.eventSink = null; 
  41.  } 

筆者對(duì)Android端代碼做了一個(gè)簡(jiǎn)單的封裝,還是很好理解的。下面就來(lái)看flutter代碼實(shí)現(xiàn)。

 
 
 
 
  1. class _MyHomePageState extends State { 
  2.  EventChannel _eventChannelPlugin = EventChannel("EventChannelPlugin"); 
  3.  StreamSubscription _streamSubscription; 
  4.  @override 
  5.  void initState() { 
  6.  _streamSubscription = _eventChannelPlugin 
  7.  //["abc", 123, "你好"]對(duì)應(yīng)著Android端onListen方法的第一個(gè)參數(shù),可不傳值 
  8.  .receiveBroadcastStream(["abc", 123, "你好"]) 
  9.  .listen(_onToDart, onError: _onToDartError, onDone: _onDone); 
  10.  super.initState(); 
  11.  } 
  12.  @override 
  13.  void dispose() { 
  14.  if (_streamSubscription != null) { 
  15.  _streamSubscription.cancel(); 
  16.  _streamSubscription = null; 
  17.  } 
  18.  super.dispose(); 
  19.  } 
  20.  //native端發(fā)送正常數(shù)據(jù) 
  21.  void _onToDart(message) { 
  22.  print(message); 
  23.  } 
  24.  //當(dāng)native出錯(cuò)時(shí),發(fā)送的數(shù)據(jù) 
  25.  void _onToDartError(error) { 
  26.  print(error); 
  27.  } 
  28.  //當(dāng)native發(fā)送數(shù)據(jù)完成時(shí)調(diào)用的方法,每一次發(fā)送完成就會(huì)調(diào)用 
  29.  void _onDone() { 
  30.  print("消息傳遞完畢"); 
  31.  } 
  32.  @override 
  33.  Widget build(BuildContext context) {...} 

上面就是通過(guò)EventChannel來(lái)進(jìn)行通信的代碼實(shí)現(xiàn),調(diào)用EventChannelPlugin的send方法就能給flutter發(fā)送數(shù)據(jù)。

3.3、MethodChannel

MethodChannel是一種native與flutter之間互相發(fā)送數(shù)據(jù)的通信方式,顧名思義,通過(guò)MethodChannel就能調(diào)用native與flutter中相對(duì)應(yīng)的方法,該種方式有返回值。它的使用方式如下。

首先來(lái)看Android端的代碼實(shí)現(xiàn)。

 
 
 
 
  1. public class MethodChannelPlugin implements MethodChannel.MethodCallHandler { 
  2.  private Activity activity; 
  3.  private MethodChannel channel; 
  4.  public static MethodChannelPlugin registerWith(FlutterView flutterView) { 
  5.  MethodChannel channel = new MethodChannel(flutterView, "MethodChannelPlugin"); 
  6.  MethodChannelPlugin methodChannelPlugin = new MethodChannelPlugin((Activity) flutterView.getContext(), channel); 
  7.  channel.setMethodCallHandler(methodChannelPlugin); 
  8.  return methodChannelPlugin; 
  9.  } 
  10.  private MethodChannelPlugin(Activity activity, MethodChannel channel) { 
  11.  this.activity = activity; 
  12.  this.channel = channel; 
  13.  } 
  14.  //調(diào)用flutter端方法,無(wú)返回值 
  15.  public void invokeMethod(String method, Object o) { 
  16.  channel.invokeMethod(method, o); 
  17.  } 
  18.  //調(diào)用flutter端方法,有返回值 
  19.  public void invokeMethod(String method, Object o, MethodChannel.Result result) { 
  20.  channel.invokeMethod(method, o, result); 
  21.  } 
  22.  @Override 
  23.  public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) { 
  24.  switch (methodCall.method) { 
  25.  case "send"://返回的方法名 
  26.  //給flutter端的返回值 
  27.  result.success("MethodChannelPlugin收到:" + methodCall.arguments); 
  28.  Toast.makeText(activity, methodCall.arguments + "", Toast.LENGTH_SHORT).show(); 
  29.  if (activity instanceof FlutterAppActivity) { 
  30.  ((FlutterAppActivity) activity).showContent(methodCall.arguments); 
  31.  } 
  32.  break; 
  33.  default: 
  34.  result.notImplemented(); 
  35.  break; 
  36.  } 
  37.  } 

筆者對(duì)Android端代碼做了一個(gè)簡(jiǎn)單的封裝,還是很好理解的。下面就來(lái)看flutter代碼實(shí)現(xiàn)。

 
 
 
 
  1. class _MyHomePageState extends State { 
  2.  MethodChannel _methodChannel = MethodChannel("MethodChannelPlugin"); 
  3.  @override 
  4.  void initState() { 
  5.  _methodChannel.setMethodCallHandler((handler) => Future(() { 
  6.  print("_methodChannel:${handler}"); 
  7.  //監(jiān)聽(tīng)native發(fā)送的方法名及參數(shù) 
  8.  switch (handler.method) { 
  9.  case "send": 
  10.  _send(handler.arguments);//handler.arguments表示native傳遞的方法參數(shù) 
  11.  break; 
  12.  } 
  13.  })); 
  14.  super.initState(); 
  15.  } 
  16.  //native調(diào)用的flutter方法 
  17.  void _send(arg) { 
  18.  setState(() { 
  19.  _content = arg; 
  20.  }); 
  21.  } 
  22.  String _resultContent = ""; 
  23.  //flutter調(diào)用native的相應(yīng)方法 
  24.  void _sendToNative() { 
  25.  Future future = 
  26.  _methodChannel.invokeMethod("send", _controller.text); 
  27.  future.then((message) { 
  28.  setState(() { 
  29.  //message是native返回的數(shù)據(jù) 
  30.  _resultContent = "返回值:" + message; 
  31.  }); 
  32.  }); 
  33.  } 
  34.  @override 
  35.  Widget build(BuildContext context) {...} 

上面就是通過(guò)MethodChannel來(lái)進(jìn)行通信的代碼實(shí)現(xiàn)。還是比較簡(jiǎn)單的。在Android端使用只需要調(diào)用MethodChannelPlugin的invokeMethod方法即可。在flutter端使用只需要參考_sendToNative方法的實(shí)現(xiàn)即可。

3.4、BasicMessageChannel

BasicMessageChannel是一種能夠在native與flutter之間互相發(fā)送消息的通信方式,它支持?jǐn)?shù)據(jù)類型最多,使用范圍最廣。EventChannel與MethodChannel的應(yīng)用場(chǎng)景可以使用BasicMessageChannel來(lái)實(shí)現(xiàn),但BasicMessageChannel的應(yīng)用場(chǎng)景就不一定能夠使用EventChannel與MethodChannel來(lái)實(shí)現(xiàn)。該方式有返回值。它的使用方式如下。

首先來(lái)看Android代碼的實(shí)現(xiàn)。

 
 
 
 
  1. //這里支持的數(shù)據(jù)類型為String。 
  2. public class BasicMessageChannelPlugin implements BasicMessageChannel.MessageHandler { 
  3.  private Activity activity; 
  4.  private BasicMessageChannel messageChannel; 
  5.  static BasicMessageChannelPlugin registerWith(FlutterView flutterView) { 
  6.  return new BasicMessageChannelPlugin(flutterView); 
  7.  } 
  8.  private BasicMessageChannelPlugin(FlutterView flutterView) { 
  9.  this.activity = (Activity) flutterView.getContext(); 
  10.  this.messageChannel = new BasicMessageChannel(flutterView, "BasicMessageChannelPlugin", StringCodec.INSTANCE); 
  11.  messageChannel.setMessageHandler(this); 
  12.  } 
  13.  @Override 
  14.  public void onMessage(String s, BasicMessageChannel.Reply reply) { 
  15.  reply.reply("BasicMessageChannelPlugin收到:" + s); 
  16.  if (activity instanceof FlutterAppActivity) { 
  17.  ((FlutterAppActivity) activity).showContent(s); 
  18.  } 
  19.  } 
  20.  void send(String str, BasicMessageChannel.Reply reply) { 
  21.  messageChannel.send(str, reply); 
  22.  } 

筆者對(duì)Android端代碼做了一個(gè)簡(jiǎn)單的封裝,還是很好理解的。下面就來(lái)看flutter代碼實(shí)現(xiàn)。

 
 
 
 
  1. class _MyHomePageState extends State { 
  2.  //StringCodec()為編碼格式 
  3.  BasicMessageChannel _basicMessageChannel = 
  4.  BasicMessageChannel("BasicMessageChannelPlugin", StringCodec()); 
  5.  @override 
  6.  void initState() { 
  7.  _basicMessageChannel.setMessageHandler((message) => Future(() { 
  8.  print(message); 
  9.  //message為native傳遞的數(shù)據(jù) 
  10.  setState(() { 
  11.  _content = message; 
  12.  }); 
  13.  //給Android端的返回值 
  14.  return "收到Native消息:" + message; 
  15.  })); 
  16.  _controller = TextEditingController(); 
  17.  super.initState(); 
  18.  } 
  19.  //向native發(fā)送消息 
  20.  void _sendToNative() { 
  21.  Future future = _basicMessageChannel.send(_controller.text); 
  22.  future.then((message) { 
  23.  _resultContent = "返回值:" + message; 
  24.  }); 
  25.  } 
  26.  @override 
  27.  Widget build(BuildContext context) {...} 

上面就是通過(guò)BasicMessageChannel來(lái)進(jìn)行通信的代碼實(shí)現(xiàn)。在Android端只需要調(diào)用BasicMessageChannelPlugin的send方法就可以向flutter發(fā)送數(shù)據(jù),BasicMessageChannel.Reply是返回值的回調(diào)方法。在flutter端使用只需要參考_sendToNative方法的實(shí)現(xiàn)即可。

4、通信原理

從分析Android與Flutter通信的源碼來(lái)看,實(shí)現(xiàn)還是比較簡(jiǎn)單的,都是以ByteBuffer為數(shù)據(jù)載體,然后通過(guò)BinaryMessenger來(lái)發(fā)送與接收數(shù)據(jù)。整體設(shè)計(jì)如下。

從圖中可以看出,Android側(cè)與flutter側(cè)采用了相同的設(shè)計(jì)。前面說(shuō)過(guò)通信時(shí)是異步進(jìn)行的,那么線程切換在哪?其實(shí)是在系統(tǒng)底層實(shí)現(xiàn)的。在Android與Flutter通信中,系統(tǒng)底層屏蔽了線程切換、數(shù)據(jù)拷貝等大量復(fù)雜操作。使得Android側(cè)與flutter側(cè)能方便的來(lái)進(jìn)行通信。

在Android側(cè),BinaryMessenger是一個(gè)接口,在FlutterView中實(shí)現(xiàn)了該接口,在BinaryMessenger的方法中通過(guò)JNI來(lái)與系統(tǒng)底層溝通。在Flutter側(cè),BinaryMessenger是一個(gè)類,該類的作用就是與類window溝通,而類window才真正與系統(tǒng)底層溝通。

5、總結(jié)

在Android與Flutter混合開(kāi)發(fā)模式下,相互之間通信的場(chǎng)景肯定不會(huì)少。了解Android與Flutter之間通信的各種方式及使用,有助于選用合理的方式來(lái)實(shí)現(xiàn)。

最后

如果你看到了這里,覺(jué)得文章寫(xiě)得不錯(cuò)就給個(gè)贊唄?如果你覺(jué)得那里值得改進(jìn)的,請(qǐng)給我留言。一定會(huì)認(rèn)真查詢,修正不足。謝謝。


文章標(biāo)題:一篇看懂Android與Flutter之間的通信
當(dāng)前網(wǎng)址:http://www.5511xx.com/article/cceipop.html