smartinvoke入门系列六——让Flex实现事件回调与多线程
本质上来说事件回调也是属于Java调用Flex。前面的Java调用Flex部分已经实现了该功能。但前面介绍的方式有些弊端:
1. 导致Java逻辑代码与Flex接口部分代码结合的比较紧密,降低了代码的可维护性。
2. 程序调用的smartinvoke API比较多,代码的可移植性不高。
在这里我们介绍smartinvoke的事件回调机制,可以解决上面遇到的两个问题。
首先修改First项目中的cn.first.ServiceTest类,让其继承
cn.smartinvoke.gui.module.CObservable类,CObservable类封装了事件回调的实现细节。增加callbackTest方法模拟后台长时间任务,修改后内容如下:
package cn.first;
import cn.smartinvoke.gui.module.CObservable;
import cn.smartinvoke.ide.declare.AServiceType;
@AServiceType
public class ServiceTest extends CObservable {
public ServiceTest() {
//smarinvoke will call this default constructure.
}
public String hello(String info){
System.out.println(info);
return "hello Flex I'm java";
}
public void beanTest(BeanTest bean){
System.out.println(bean);
}
public void callbackTest(){
//创建并启动一个新线程模拟后台任务
Thread thread=new Thread(){
public void run(){
for(int i=0;i<10;i++){
System.out.println(i);
try {
Thread.sleep(800);
} catch (InterruptedException e) {
}
}
//当任务执行完毕后调用flex显示对应信息
ServiceTest.this.fireEvent("Task Finish");
}
};
thread.start();
}
public void gc(){
//when this service object not be used smartinvoke call this method free memory.
}
}
保存编译后你会发现First_项目中的ServiceTest.as文件也做了相应的修改,内容如下:
package cn.first{
import cn.smartinvoke.gui.module.CObservable;
import cn.first.BeanTest;
import cn.smartinvoke.RemoteObject;
[RemoteClass(alias="cn.first.ServiceTest")]
public class ServiceTest extends CObservable{
public static function CreateInstance0():ServiceTest{
var instance:ServiceTest=new ServiceTest();
instance.createRemoteObject(arguments);
return instance;
}
public function hello(info:String):String{
var ret:Object=this.call('hello',arguments);
return ret as String;
}
public function beanTest(bean:BeanTest):void{
this.call('beanTest',arguments);
}
public function callbackTest():void{
this.call('callbackTest',arguments);
}
}
}
Flex中通过以下代码就可以看到效果了。
//创建ServiceTest服务对象
var serv:ServiceTest=ServiceTest.CreateInstance0();
//添加事件监听器
serv.addListener(function(res:Object):void{
Alert.show(res+"");
},this);
//调用任务方法,启动后台线程
serv.callbackTest();