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. Joomla 3.2.0 - 3.4.4 无限制SQL注入漏洞

    http://www.sebug.net/vuldb/ssvid-89680#0-tsina-1-18081-397232819ff9a47a7b7e80a40613cfe1 http://10.21 ...

  2. Hibernate查询 Query Language

    1,Native SQL ->HQL->EJBQL->QBC(Query By Cretira)->QBE(Query By Example) 此排列是根据可实现功能大小排序.

  3. 获取Java系统相关信息

    package com.test; import java.util.Properties; import java.util.Map.Entry; import org.junit.Test; pu ...

  4. Android课程---qq登陆页面(练习)

    AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xm ...

  5. Windows 10输入法已禁用IME无法输入中文怎么办

    Windows 10输入法已禁用IME无法输入中文怎么办 | 浏览:10453 | 更新:2015-03-01 14:46 | 标签:windows 1 2 3 4 5 分步阅读 Windows10系 ...

  6. Jquery--防止冒泡

    e.stopPropagation();//阻止冒泡

  7. 用GSON解析Json格式数据

    GSON是谷歌提供的开源库,用来解析Json格式的数据,非常好用.如果要使用GSON的话,则要先下载gson-2.2.4.jar这个文件,如果是在Android项目中使用,则在Android项目的li ...

  8. .Net using,string.Empty初探

    前两天够哦年公司培训,讲了编码优化.现在初步总结下:(有些不大确定的就不讲了) 多次字符串拼接(特别是循环内),宜用stringBuilder.Append()方法,少用字符串+,至于string.F ...

  9. 使用windows资源管理器的排序规则

    对于windows资源管理器 abc_1_def是要排到abc_10_def前面的 而一般的排序规则, 都会吧_10_排到前面 所以为了使用习惯, 最好用资源管理器的排序规则, windows有个AP ...

  10. 解决pip国外安装源慢的问题

    用默认的pip安装源pypi.python.org由于在国外经常会出现超时的问题,而且安装速度极其的慢,如下图中的超时问题=>