smartinvoke入门系列5——实现Java调用Flex
前面讲的都是Flex调用Java的情况,但是在某些时候需要Java调用Flex,比如,当Java某个后台任务执行完毕后应该调用Flex以便界面得到响应。
?
首先我们在Flex项目First_中新建一服务类cn.first.FlexService供Java调用,内容如下:
package cn.first
{
??? import cn.smartinvoke.ServerObject;
???
??? import mx.controls.Alert;
?
??? public class FlexService extends ServerObject
??? {
??????? public function FlexService()
??????? {
???????????
??????? }
??????? /**
??????? ?*Java调用该方法在界面显示输入信息
??????? ?*/
??????? public function showInfo(msg:String):void{
??????????? Alert.show(msg);
??????? }
??? }
}
?
在FirstWin.mxml中添加对FlexService类的变量申明,以便将FlexService类编译进FirstWin.swf文件中,供Java调用。
在Java项目First中新建FlexService.as类的对应代理类型FlexService.java,内容如下:
package cn.first;
?import cn.smartinvoke.FlashContainer;
?import cn.smartinvoke.RemoteObject;
?public class FlexService extends RemoteObject {
?public FlexService(FlashContainer flashContainer) {
??????? super(flashContainer);
??????? //调用flex插件cn.first.FlexService类型服务对象,并将该对象与当前对象关联
??????? this.nativeCreateObject("cn.first.FlexService");
?}
?/**
? * 调用FlexService.as的showInfo方法
? * @param msg
? */
?public void showInfo(String msg){
??? ?this.call("showInfo",new Object[]{msg});
?}
}
?
这里的FlashContainer对象负责加载当前需要访问的swf.
修改First项目中的FirstWin.java文件,在shell.open();代码的后面加入如下代码:
?
final FlashContainer? container=shell.getFlashViewer().getFlashContainer();
??????? container.addListener(new ILoadCompleteListener(){
??????????? //当flex加载完毕后会自动调用这里的方法.
??????????? @Override
??????????? public void run() {
??????????????? FlexService service=new FlexService(container);
??????????????? service.showInfo("Hello Flex");
??????????? }
???????????
??????? });
这段代码的作用是在FirstWin.swf文件加载完毕后自动调用run方法,我们在run方法中实现了Java调用Flex的功能。