关于android接口回调机制
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接口回调机制的更多相关文章
- 弄明白Android 接口回调机制
以前对于这个机制理解不够深刻,现在重新整理下思路. 一.建模 我理解的接口回调就是,我这个类实现了一个接口里的方法doSomething,然后注册到你这里,然后我就去做别的事情去了,你在某个触发的时机 ...
- Android接口回调机制
开发中,接口回调是我们经常用到的. 接口回调的意思即,注册之后并不立马执行,而在某个时机触发执行. 举个例子: A有一个问题不会,他去问B,B暂时解决不出来,B说,等我(B)解决了再告诉你(A)此时A ...
- (转)Android之接口回调机制
开发中,接口回调是我们经常用到的. 接口回调的意思即,注册之后并不立马执行,而在某个时机触发执行. 举个例子: A有一个问题不会,他去问B,B暂时解决不出来,B说,等我(B)解决了再告诉你(A)此时A ...
- Java接口回调机制
一.前言 最近在看android Fragment与Activity进行数据传递的部分,看到了接口回调的内容,今天来总结一下. 二.回调的含义和用途 1.什么是回调? 一般来说,模块之间都存在一定的调 ...
- JAVA和Android的回调机制
本文出自xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/17483273),请尊重他人的辛勤劳动成果,谢谢 以 前不理解什么叫回 ...
- Android接口回调的理解
1.各种理解 <1>说白了,就是拿到对象引用,调其方法 <2>实际上就是利用多态的方式调用而已 <3>其实很容易理解的,定义接口,然后提供一个外部的接口设置进去,然 ...
- 模拟DbUtils实现接口回调机制
想必大家都用过apache 的DbUtils吧,这个简单的对JDBC的封装小框架真的是非常非常的适合新手的学习呢.逻辑上也不是很复杂,难度刚刚好. 下面我就模仿它来实现一个字符串的处理小框架. 思路 ...
- Android实战之 万能的接口回调
转载请标明原地址:http://blog.csdn.net/gaolei1201/article/details/47084111 前言:本人也算是自学"成才",呵呵,大学时尽管学 ...
- Android 中的接口回调
http://blog.csdn.net/wangjinyu501/article/details/22052187 在Android中到处可见接口回调机制,尤其是UI事件处理方面.举一个最常见的 ...
随机推荐
- SQL server while语句、存储过程
1.循环语句 2.存储过程 存储过程(stored procedure)有时也称为sproc.存储过程存储于数据库中而不是在单独的文件中,有输入参数.输出参数以及返回值等. 3.四种存储过程类型(类似 ...
- JAVA6开发WebService (三)——几个概念
转载自http://wuhongyu.iteye.com/blog/808922 要了解WebService,光能写代码不行啊,这说说WebService最基本的概念. 首先WebService要知道 ...
- bzoj4457: 游戏任务--双层01背包
这题和NOIP的金明的预算方案(?)很像,只不过附件的数量增多了 如果对主件进行一次01背包,再套一层附件的01背包O(n4)肯定会爆.. 所以我们可以先预处理出,对于每个主件,花的时间为k的情况下, ...
- IOS第四天(1:图片的方法和缩小,遮罩层)
@interface HMViewController () @property (nonatomic, strong) UIButton *cover; //阴影 @end @implementat ...
- 【iCore3双核心板】【4.3寸液晶驱动板爆照!】
[源代码完全开源,过几天连同硬件一起发布] 花了好久的时间,我们的fpga工程师才完成这液晶模块的驱动代码,其核心价值如下: 1.完全基于fpga驱动,sdram当做缓存: 2.内建双缓冲机制:方便 ...
- IE6低版本jQuery里的show和hide方法BUG
公司内部一直在用的jQ的版本有些低,具体是哪个版本不太清楚,相关的东西都给删掉了,今天在做一个固定在页面右侧的导航的时候,IE6里出现了一个比较奇葩的问题.具体样子如下图: 收起是用定位left等于负 ...
- Objective-C 中类属性(修饰)
Objective-C 中类属性(修饰) (2013-07-13 14:38:35) 转载▼ 标签: it 分类: IOS笔记 nonatomic: 非原子性访问,对属性赋值的时候不加锁,多线程并发访 ...
- 正则基础之——捕获组(capture group)
1 概述 1.1 什么是捕获组 捕获组就是把正则表达式中子表达式匹配的内容,保存到内存中以数字编号或显式命名的组里,方便后面引用.当然,这种引用既可以是在正则表达式内部,也可以是 ...
- c#创建、安装、卸载、调试windows服务的简单事例
最近工作中用到了windows服务,对其有深刻理解和丰富经验谈不上,本篇文章只是简单陈诉用c#创建.安装.卸载.调试windows服务的步骤. 一.创建windows服务 1.用VS创建windows ...
- 菜菜CPP日记
分支预测建议: http://www.cppblog.com/mysileng/archive/2014/09/29/208454.html #ifndef likely #define likely ...