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.

最新文章

  1. 《Ansible权威指南》笔记(2)——Inventory配置
  2. iOS开发之如何跳到系统设置里的各种设置界面
  3. js限制文本框只能输入整数或者带小数点[转]
  4. 【JVM】2、关于jdk7的MethodHandle类
  5. iOS -- 给model赋值时走了[self setValuesForKeysWithDictionary:dic]不走setvalue: forked:
  6. VS2012外接程序VMDebugger未能加载或导致了异常
  7. hdu 1848 Fibonacci again and again (初写SG函数,详解)
  8. 如何取消Linux下,vi中显示的^M符号
  9. [转] json in javascript
  10. 【MVC4 之 ViewData ViewBag TempData】
  11. Openstack_O版(otaka)部署_准备环境和依赖软件
  12. Netty源码—五、内存分配概述
  13. bash-4.2$ bash: /home/test/.bashrc: 权限不够
  14. 执行力:Just Do It
  15. JDOM生成XML文档的一般方法
  16. [100]linux输入输出重定向
  17. VM虚拟机,Linux系统安装tools过程遇到 what is the location of the “ifconfig” program
  18. Redis主从配置及通过Keepalived实现Redis自动切换高可用
  19. Python程序调试-TabError: inconsistent use of tabs and spaces in indentation
  20. 开源IMS平台中间件Mobicents

热门文章

  1. DataTable to byte[]、DataTable to XML(string)
  2. Windows Server 2003修改远程桌面最大连接数的方法
  3. eclipse汉化过程
  4. Spinner的深入学习
  5. [转]从网页Web上调用本地应用程序(.jar、.exe)的主流处理方法
  6. ExtJS笔记 Reader
  7. 控制Wordpress对搜索引擎的可见性
  8. 《Linux内核分析》第三周 构建一个简单的Linux系统MenuOS
  9. Oracle的Connect By理解
  10. 转载 Servlet3.0中使用注解配置Servle