学以致用--链式结构处理android耗时请求
1:背景
今天遇到了一个情况(首先需要去http请求获取服务器数据,然后将数据存库,其次再将数据的一部分放入share文件,最后更新内存数据.....)
哎,最后一步更新内存还行,非常速度的,前面散步基本是基本包括了android中耗时操作的三个大类吧,哎---是在不想一步一步整
2:知识前提
大概了解程序的设计模式(本文采用责任链模式),有一点点开发经验就ok了哈
3:程序基本模型
一个请求类 Responser, 一个请求执行类ResponserChain,一个
HttpUtils工具类,一个数据库工具类databaseutils,一个share文件工具类shareutils
Responser代码如下:
public abstract class Responser<T> {
public final int CONS_TIME_OUT_ONE_SECOND = 1000;
private final int CONS_TIME_OUT_SIXTEEN_SECOND = 60 * CONS_TIME_OUT_ONE_SECOND; // 10秒
public Responser(int weight) {
this.thisWeight = weight;
this.ResponserKey = String.valueOf(hashCode());
}
public String ResponserKey;<span style="white-space:pre"> </span>//唯一标识一个任务
public int thisWeight = Integer.MAX_VALUE; //该请求的权重
protected T t;
public int timeOut() {
return CONS_TIME_OUT_SIXTEEN_SECOND;
}
/**
* 依次执行任务的时候,如果下一个任务需要上一次执行的返回结果,在这里设置
*
* @param ob
*/
public void doNext(JSONObject ob) {
}
/**
* 依次执行任务的时候,如果下一个任务需要上一次执行的返回结果,在这里获取
*
* @param ob
*/
public T onNext() {
return t;
}
/**
* 执行任务
*
* @return
*/
public abstract String excute();
/**
* 任務類型
*
* @return
*/
public abstract EResponseType resType();
public enum EResponseType {
DATABASE, HTTP, SHARE
}
}
注意以上的一个excute的方法,每个请求类均有该方法执行
下面举例说明以上遇到的情况,先http请求,再入库,然后再share文件,然后内存
<pre name="code" class="java">final Responser<String> http= new Responser<String>(0) {
@Override
public String excute() {
return HttpUtils.get(......);//省略号是请求地址
}
};
<pre name="code" class="java">final Responser<String> db= new Responser<String>(1) {
@Override
public String excute() {
return databaseutils.insert(......);//省略号是插入数据库代码
}
};
<pre name="code" class="java">final Responser<String> unbind = new <span style="font-family: Arial, Helvetica, sans-serif;">Responser</span><span style="font-family: Arial, Helvetica, sans-serif;"><String>(2) {</span>
@Override
public String excute() {
return shareutils.commit(......);//省略号是提交share文件
}
};
然后是执行请求的类ResponserChain:
代码如下
public class ResponserChain {
private Vector<Responser<?>> allResponse = new Vector<Responser<?>>();
private boolean currentChainIsAlive = false;
private responserChainListener _ResChainListener;
private Responser<?> _Responser;
/**
* Constructor one responseChain
*/
public ResponserChain(responserChainListener excuteListener, Responser<?>... responsers) {
if (responsers.length <= 0) {
return;
}
for (Responser<?> responser : responsers) {
allResponse.add(responser);
}
currentChainIsAlive = true;
_ResChainListener = excuteListener;
}
/**
* ready
*/
public boolean ready() {
synchronized (allResponse) {
if (allResponse.isEmpty()) {
return false;
}
for (Responser<?> responser : allResponse) {
if (_Responser == null || responser.thisWeight < _Responser.thisWeight) {
_Responser = responser;
}
}
if (_Responser == null) {
return false;
}
for (Responser<?> responser : allResponse) {
if (responser.ResponserKey.equals(_Responser.ResponserKey)) {
allResponse.remove(responser);
break;
}
}
return _Responser.thisWeight != Integer.MAX_VALUE;
}
}
/**
* go,
*/
public void go() {
HTTPThreadPool.getInstance().submit(new Runnable() {
@Override
public void run() {
/**
* 必须保证以下代码执行的每一句的顺序
*/
final String _task = _Responser.ResponserKey;
final int _timeout = _Responser.timeOut();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = _timeout; i > 0; i -= _Responser.CONS_TIME_OUT_ONE_SECOND) {
// 如果在计算超时的时候,改任务已经执行结束,则結束超時
if (!currentChainIsAlive || !_Responser.ResponserKey.equals(_task)) {
return;
}
try {
Thread.sleep(1050); // 为什么是1050呢--猜
}
catch (Exception e) {
}
}
if (currentChainIsAlive && _Responser.ResponserKey.equals(_task)) {
if (_ResChainListener != null) {
_ResChainListener.onExcuteChainCallBack(HttpConstans.HTTP_TIMEOUT, _Responser, null);
}
release();
}
}
}).start();
String result = _Responser.excute();
// 执行完成,但是职责链已经不存在
if (!currentChainIsAlive) {
return;
}
JSONObject json = null;
try {
if (!TextUtils.isEmpty(result)) {
json = new JSONObject(result);
}
}
catch (JSONException e) {
json = null;
}
if (json == null) {
if (_ResChainListener != null) {
_ResChainListener.onExcuteChainCallBack(HttpConstans.HTTP_FAILED, _Responser, null);
}
release();
return;
}
final int code = json.optInt("code");
if (_ResChainListener != null) {
_ResChainListener.onExcuteChainCallBack(code, _Responser, json);
}
_Responser.thisWeight = Integer.MAX_VALUE;
boolean hasNext = ready();
if (hasNext) {
_Responser.doNext(json);
}
if (code == 0 && hasNext) {
go();
return;
}
release();
}
});
}
/**
* cut current chain
*/
public void cut() {
release();
}
/**
* current chain is alive
*/
public boolean isAlive() {
return currentChainIsAlive;
}
/**
* dynamic add one response, but this response is excute lase
*/
public boolean addResponseToLase(Responser<?>... responsers) {
/** current chain is over, may be this object is destory */
if (!currentChainIsAlive) {
return false;
}
synchronized (allResponse) {
for (Responser<?> responser : responsers) {
allResponse.add(responser);
}
}
return true;
}
/**
* release
*/
public void release() {
currentChainIsAlive = false;
_ResChainListener = null;
allResponse.clear();
}
/**
* one chain excute result
*/
public interface responserChainListener {
public void onExcuteChainCallBack(int result, Responser<?> responser, JSONObject json);
}
}
ResponserChain c = new ResponserChain(new responserChainListener() {
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public void onExcuteChainCallBack(final int result, final Responser<?> responser, final JSONObject json) {
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>postUI(new Runnable() {
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public void run() {
<span style="white-space:pre"> </span>//根据返回的请求的类型,各种结果就出来了,而且是你制定的顺序 http第一执行,db第二执行,share第三执行,
<span style="white-space:pre"> </span>}, http,db,share);
if (c.ready()) {
<span style="white-space:pre"> </span>c.go();
<span style="white-space:pre"> </span>return;
}