egret 发布android原生项目(三)JS与原生通讯
Java注册接收消息的方法:
nativeAndroid.setExternalInterface("sendToNative",newINativePlayer.INativeInterface(){@Overridepublicvoidcallback(Stringmessage){Stringstr="Nativegetmessage:";str+=message;Log.d(TAG,str);}});
JS发送消息:
egret.ExternalInterface.call("sendToNative","messagefromJS");Java向JS发送消息
JS注册接收消息的方法:
egret.ExternalInterface.addCallback("sendToJS",function(msg){console.log(msg);});
Java发送消息:
nativeAndroid.callExternalInterface("sendToJS","messagefromJava");注意
需要先注册接收消息的方法,才能接收到另一端发送的消息。
在应用刚启动时,JS可能没有加载完,这是向JS发送消息是不能接收到的。可以在游戏代码中先向Java发送消息通知Java端接收方法已经注册完成,再向JS发送消息。
------------------------------------------
具体实现步骤
1、在Demo项目Main.ts文件createGameScene方法最后添加注册消息的方法
如果接收到java发送过来的消息,将colorLabel文本由Hello Egret修改为java端发送过来的字符串
并在按钮事件发送消息
2、回到android studio,MainActivity.java已经实现了消息的注册,并发送消息到js
3、编译项目
4、在android手机上运行项目,查看结果,可以观察到点击Click2!之后,将colorLabel文本由Hello Egret修改为
Nativegetmessage:messagefromJS
,说明整个流程是通的
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。