转载来自于Egret社区
基于有较多的开发者问这个问题,我请大家和我一起完成一个demo的制作,这样大家能很清楚这个应该怎么写了。我没有给出源代码而是截图,是因为让大伙自己码一下,理解会更深刻一点。本文分三部分,命令,egret 项目和android项目
1. 命令,
- egret info 查看当前的egret engine的版本
- egret create hello #创建一个名为hello的egret h5 项目
- egret create_app HelloAndroid -f hello -t ~/work/egret/runtime/support/android #创建egret android的项目,这个项目是基于hello的egret h5 项目,模版的位置在“~/work/egret/runtime/support/android”,
- cd hello #进入到egret h5项目hello目录中
- egret build --runtime native # 每次修改h5项目之后,使用该命令更新egret android项目HelloAndroid
2. 实现egret 上面的通讯接口
我们选择在main.ts中添加通讯的实现
- 我们在155行添加 this.setEgretRuntimePipe()
- 158-165行,我们实现了该方法
- 159-162行,提供了一个Egret端的接口给Runtime调用,egret.ExternalInterface.addCallback,我们的接口名叫“EgretInterfaceA”,当Runtime端给“EgretInterfaceA”,发送消息时,会执行后面的function(message:string)方法,这里打印一行,并调用Runtime端的名为“RuntimeInterfaceA”的接口,传递的消息是“message C from Egret Interface A”
- 163行和164行分别给Runtime端的“RuntimeInterfaceA”和“RuntimeInterfaceB”发送消息
- 使用egret build --runtime native 将变动更新到Android项目
3. 实现Android上面的Egret 通讯
- 我们在40行添加通讯用的方法 setEgretRuntimePipe()
- 47-76行,我们实现了该方法,
- 要使用通讯,我们首先要打开该模块,见49行打开通讯模块 enableEgretRuntimeInterface()
- 75行,我们提供了Runtime端的通讯接口,使用setRuntimeInterfaceSet(HashMap)设置所有的接口集
- 51-53行,我们声明并初始化了HashMap,用于保存Runtime的接口集
- 54-62行,我们实现了一个名为“RuntimeInterfaceA”的Runtime端的接口,当Egret端向这个就扣发送消息的时候,他将在57行中的callBack(String)方法中执行
- 同样的,63-74行,我们实现了一个名为“RuntimeInterfaceB”的Runtime端的接口,但是不同的是,我们可以看到70行,当Egret端祥这个接口发送消息,我们执行了一个callEgretInterface(String, String)的方法来向Egret端发送消息。
自此我们就完成了编码部分,我们根据代码部分的来走一遍 :
- Runtime 端的setEgretRuntimePipe被执行,只是设置接口,没有输出,设备准备完毕后,
- Egret 端main.ts开始执行, setEgretRuntimePipe,设置一个接口,
- 调用发送接口给Runtime端的RuntimeInterfaceA接口,发送消息“message A from Egret”, Runtime端的“RuntimeInterfaceA”执行了Log,
- Egret 端继续执行,发送消息给Runtime端的RuntimeInterfaceB接口,内容为“message B from Egret”, Runtime端的“RuntimeInterfaceB”执行了Log输出后;
- 再执行了向Egret端的“EgretInterfaceA”发送消息“A message from runtime”, Egret端接收执行了console.log输出了消息,并发送消息给Runtime端的“RuntimeInterfaceB”接口,内容为“message C from Egret Interface A”,
- Runtime端的“RuntimeInterfaceA”,输了该消息
那我们的输出的应该是这样的:
- message A from Egret
- message B from Egret
- [JS] ... A message from runtime
- message C from Egret Interface A
这样就正好和我们在上图中给出的logcat符合。
完毕