http://www.cnblogs.com/JohnTsai/p/3975022.html

http://www.zhihu.com/question/19801131

In my previous post I showed how to perform asynchronous web API calls in native Android code, after showing how to do it in native iOS a few days before. My Android post was glaringly missing support for callback functions however, so today I'll show how to add that functionality in the Java world.

First we'll need to add some code to the class from where ApiCall is called. This will be what represents our reference to the callback function that we can call from an ApiCall (thanks to this Stack Overflow post for how to do this).

public interface OnTaskCompleted{
void onTaskCompleted(JSONObject result);
}
public class Callback implements OnTaskCompleted{
@Override
public void onTaskCompleted(JSONObject result) {
// do something with result here!
}
}

Now let's modify ApiCall itself to accept the callback as a parameter.

public class ApiCall extends AsyncTask {
private OnTaskCompleted listener;
private String result;
public ApiCall(OnTaskCompleted listener){
this.listener=listener;
}
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < count; i++) {
try {
// Read all the text returned by the server
InputStreamReader reader = new InputStreamReader(urls[i].openStream());
BufferedReader in = new BufferedReader(reader);
String resultPiece;
while ((resultPiece = in.readLine()) != null) {
resultBuilder.append(resultPiece);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// if cancel() is called, leave the loop early
if (isCancelled()) {
break;
}
}
// save the result
this.result = resultBuilder.toString();
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
// update progress here
}
// called after doInBackground finishes
protected void onPostExecute(Long result) {
Log.v("result, yay!", this.result);
// put result into a json object
try {
JSONObject jsonObject = new JSONObject(this.result);
// call callback
listener.onTaskCompleted(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Just a few small changes from the original callback-less class. Up top we added a new private variable of typeOnTaskCompleted, which we just defined. This object "listens" for us to send it a signal from this class, and then it executes the necessary action. Kind of like a callback!

We also defined a constructor just below this, which now accepts an OnTaskCompleted object as a paramter. So now you can pass in your callback when you create a new ApiCall. Down near the bottom, after receiving the response and putting our results nicely into a JSON object, we call this callback with listener.onTaskCompleted(jsonObject); just as expected.

Finally, here is how you would call this new version of ApiCall from the other class where Callback is defined:

URL url = null;
try {
url = new URL("http://search.twitter.com/search.json?q=@justinjmcc");
} catch (MalformedURLException e) {
e.printStackTrace();
}
new ApiCall(new Callback()).execute(url);

And that is all you need to implement a callback in this asynchronous web API call. By defining and passing a different callback when you create an ApiCall object, you can effectively have ApiCall call whatever function you want after receiving the results of the call.

Not as bad as I was expecting, but still a bit different from iOS and completely different from javascript. While coding moves more and more onto the web where slow calls over the internet are common, it's hard not to see languages like javascript taking over... But then again that's coming from an HTML5 fanboy playing around in native code.

关于android接口回调机制的更多相关文章

  1. 弄明白Android 接口回调机制

    以前对于这个机制理解不够深刻,现在重新整理下思路. 一.建模 我理解的接口回调就是,我这个类实现了一个接口里的方法doSomething,然后注册到你这里,然后我就去做别的事情去了,你在某个触发的时机 ...

  2. Android接口回调机制

    开发中,接口回调是我们经常用到的. 接口回调的意思即,注册之后并不立马执行,而在某个时机触发执行. 举个例子: A有一个问题不会,他去问B,B暂时解决不出来,B说,等我(B)解决了再告诉你(A)此时A ...

  3. (转)Android之接口回调机制

    开发中,接口回调是我们经常用到的. 接口回调的意思即,注册之后并不立马执行,而在某个时机触发执行. 举个例子: A有一个问题不会,他去问B,B暂时解决不出来,B说,等我(B)解决了再告诉你(A)此时A ...

  4. Java接口回调机制

    一.前言 最近在看android Fragment与Activity进行数据传递的部分,看到了接口回调的内容,今天来总结一下. 二.回调的含义和用途 1.什么是回调? 一般来说,模块之间都存在一定的调 ...

  5. JAVA和Android的回调机制

    本文出自xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/17483273),请尊重他人的辛勤劳动成果,谢谢 以 前不理解什么叫回 ...

  6. Android接口回调的理解

    1.各种理解 <1>说白了,就是拿到对象引用,调其方法 <2>实际上就是利用多态的方式调用而已 <3>其实很容易理解的,定义接口,然后提供一个外部的接口设置进去,然 ...

  7. 模拟DbUtils实现接口回调机制

    想必大家都用过apache 的DbUtils吧,这个简单的对JDBC的封装小框架真的是非常非常的适合新手的学习呢.逻辑上也不是很复杂,难度刚刚好. 下面我就模仿它来实现一个字符串的处理小框架. 思路 ...

  8. Android实战之 万能的接口回调

    转载请标明原地址:http://blog.csdn.net/gaolei1201/article/details/47084111 前言:本人也算是自学"成才",呵呵,大学时尽管学 ...

  9. Android 中的接口回调

    http://blog.csdn.net/wangjinyu501/article/details/22052187   在Android中到处可见接口回调机制,尤其是UI事件处理方面.举一个最常见的 ...

随机推荐

  1. 【HDU4630 No Pain No Game】 dp思想+线段树的离线操作

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4630 题意:给你n个数据范围在[1,n]中的数,m个操作,每个操作一个询问[L,R],让你求区间[L, ...

  2. Eclipse 官方简体中文语言包下载地址及安装方法

    Eclipse 官方简体中文语言包下载地址及安装方法 打开Eclipse Babel Project 主页: http://www.eclipse.org/babel/downloads.php 根据 ...

  3. XPath提取xml文档数据

    package itcast.dom4j; import java.io.File; import org.dom4j.Document; import org.dom4j.DocumentExcep ...

  4. 解决thrift: ···No such file or directory问题

    感谢Anker分享:error while loading shared libraries: xxx.so.x" 错误的原因和解决办法 今天在装thrift的时候遇到一个这样的问题: ro ...

  5. python - ConfigParser

    ConfigParse 作用是解析配置文件. 配置文件格式如下 [test1]num1: 10[test2]num1: 35 配置文件两个概念section和option, 在这个例子中第一个sect ...

  6. Oracle-01033错误处理

    今天电脑非常卡,强制重启后,发现oracle 11g启动不了了,提示错误: ERROR - ORA-01033 oracle initialization or shutdown in progres ...

  7. ssm maven项目启动 报SYSTEM_PROPERTIES_MODE_ENVIRONMENT

    1.jar包冲突,查看项目中的jar和pom.xml中配置的jar包 版本,把没用的jar包删掉

  8. css3超过指定宽度文字,显示省略号

    text-overflow:ellipsis; overflow:hidden; white-space:nowrap; width:200px;

  9. 遍历echsop的region表形成缓存的程序

    header("Content-type: text/html; charset=utf-8"); $con = mysql_connect("localhost&quo ...

  10. Wordpress本地伪静态设置

    遇到的问题: 在主题的目录页,用wordpress默认链接方式是的,但是改了固定链接结构为:/%post_id%.html后,就访问不了了,开始以为是我主题的问题,然后切换为官方主题也是访问不了,而神 ...