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. 34款Firefox渗透测试插件工具

    工欲善必先利其器,firefox一直是各位渗透师必备的利器,小编这里推荐34款firefox渗透测试辅助插件,其中包含渗透测试.信息收集.代理.加密解密等功能. 1:Firebug Firefox的 ...

  2. mongodb备忘

    1.远程拷贝数据库 db.copyDatabase(fromdb, todb, fromhost, [dbuser, dbpassword]) 2.数据库备份/恢复(导出/导入) mongoexpor ...

  3. U3D--常用属性(不完整,待加)

    1. AddComponentMenu 描述:这个属性可以在Component这个菜单栏下加自己定义的子菜单,这样可以快速添加常用的脚本.该属性要用在类上. using UnityEngine; us ...

  4. jquery动态刷新select的值,后台传过来List<T>,前台解析后填充到select的option中

    jquery动态刷新select的值:将后台传来的List<T>赋值到select下的option. 第一个select选择后出发该方法refreshMerchant(params),传递 ...

  5. Android WebApp开发使用Genymotion连接Fiddler2/Charles代理调试

    1.       目的 在模拟器的浏览器或app hybrid开发中遇到chrome调试代码为线上代码或者混淆代码时,可以利用fiddler/charles为genymotion配置代理, 可以方便的 ...

  6. VBS练习题

    练习题: 1.输入3个数,输出其中最大的那个值. Option Explicit Dim intA,intB,intC intA=CInt(InputBox("请输入a:")) i ...

  7. DBXJSON和ADO的效率真的好低....

    项目需要写了一个JSON和DataSet互转的单元.....支持了Delphi自带的几种DataSet, 结果发现DBXJSON和ADO的效率真的是好低啊........-_-.... 开发环境是XE ...

  8. TF-IDF 文本相似度分析

    前阵子做了一些IT opreation analysis的research,从产线上取了一些J2EE server运行状态的数据(CPU,Menory...),打算通过训练JVM的数据来建立分类模型, ...

  9. 向ES6看齐,用更好的JavaScript(三)

    本文是ES6系列的第三篇,主要介绍ES6新增的数据类型.数据结构,先上传送门: 1 变量部分 2 现有对象拓展 3 新增数据类型/数据结构 4 新的异步编程模式 5 类和模块 1 第七种数据类型Sym ...

  10. sdutoj 2623 The number of steps

    http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2623 The number of steps ...