东西很简单,模拟的是在UI线程调用网络对象进行下载,当下载完成以后将数据传递给UI线程进行显示。就不多解释了,直接上代码。
/**
* @Title: CallbackDemo.java
* @Package
* @Description:
* @author Mr.Simple bboyfeiyu@gmail.com
* @date Apr 5, 2013 1:50:44 PM
* @version V1.0
*/
public class CallbackDemo {
// 回调函数的接口类型
private NetworkCallback mCallback = null ;
public CallbackDemo() {
}
public CallbackDemo(NetworkCallback callback) {
mCallback = callback;
}
/**
*
* @Title: DownloadCompleted
* @Description:
* @param url
* @param callback
* @return void
* @throws
*/
public void DownloadCompleted(String url,final NetworkCallback callback) {
System.out.println("你的地址是: " + url) ;
try {
System.out.println("正在下载中...") ;
Thread.sleep(3000) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("下载完成!!! ") ;
// 回调函数触发
callback.DownloadCompleted("这里是你下载到的结果") ;
}
public static void main(String[] args) {
CallbackDemo demo = new CallbackDemo();
demo.DownloadCompleted("www.hao123.com", new DownloadCompletedDone()) ;
}
/**
*
* @ClassName: DownloadCompletedDone
* @Description: 自定义的回调类型
* @author Mr.Simple
* @date Apr 5, 2013 1:59:16 PM
*
*/
static class DownloadCompletedDone implements NetworkCallback{
@Override
public void DownloadCompleted(Object result) {
System.out.println("UI接到的结果为: " + result.toString()) ;
}
}
}
回调的接口类型:
/**
* @Title: NetworkCallback.java
* @Package
* @Description: 回调接口类型
* @author Mr.Simple bboyfeiyu@gmail.com
* @date Apr 5, 2013 1:51:40 PM
* @version V1.0
*/
//定义回调接口
public interface NetworkCallback {
// 回调函数
void DownloadCompleted(Object result);
}
例子下载 : http://download.csdn.net/detail/bboyfeiyu/5222943