Volley 源码解析 StringRequest解析

Android Vollety是一个很有用的框架,所以想借鉴前人思想,分析这个源代码。
参考: http://blog.csdn.net/crazy__chen/article/details/46486123
public class StringRequest extends Request<String> {
private final Listener<String> mListener;

public StringRequest(int method, String url, Listener<String> listener, ErrorListener errorListener) {
    super(method, url, errorListener);
    this.mListener = listener;
}

public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) {
    this(0, url, listener, errorListener);
}

protected void deliverResponse(String response) {
    this.mListener.onResponse(response);
}

protected Response<String> parseNetworkResponse(NetworkResponse response) {
    String parsed;
    try {
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException var4) {
        parsed = new String(response.data);
    }

    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
}

这就是StringRequest源码,其实比较短,关键还是 继承了Request
现在着重介绍Request;
分开介绍:

/**
 *默认编码格式
 */
private static final String DEFAULT_PARAMS_ENCODING = "UTF-8";
private final MarkerLog mEventLog;
private final int mMethod;//请求方式,常见的get,post
private final String mUrl;//请求地址
private final int mDefaultTrafficStatsTag;// 流量统计标签
private final ErrorListener mErrorListener;
private Integer mSequence;//请求序号,用于fifo算法
private RequestQueue mRequestQueue;//请求所在的请求队列 ,这也是一个重点,有时间再写一篇
private boolean mShouldCache;//是否使用缓存响应请求
private boolean mCanceled;//该请求是否被取消
private boolean mResponseDelivered;
private long mRequestBirthTime;//请求产生时间
private static final long SLOW_REQUEST_THRESHOLD_MS = 3000L;
private RetryPolicy mRetryPolicy;//请求重试策略
private Entry mCacheEntry;
private Object mTag;


 /** @deprecated */
public Request(String url, ErrorListener listener) {
    this(-1, url, listener);
}

构造函数:

/**
 * 构造函数:请求方式,创建新的请求(需要地址,错误监听器等参数)
 * @param method
 * @param url
 * @param listener
 */
public Request(int method, String url, ErrorListener listener) {
    this.mEventLog = MarkerLog.ENABLED?new MarkerLog():null;
    this.mShouldCache = true;
    this.mCanceled = false;
    this.mResponseDelivered = false;
    this.mRequestBirthTime = 0L;
    this.mCacheEntry = null;
    this.mMethod = method;
    this.mUrl = url;
    this.mErrorListener = listener;
    this.setRetryPolicy(new DefaultRetryPolicy());
    this.mDefaultTrafficStatsTag = TextUtils.isEmpty(url)?0:Uri.parse(url).getHost().hashCode();
}

/**
* 比较重要的function
* @param tag
*/

void finish(final String tag) {
    if(this.mRequestQueue != null) {
        this.mRequestQueue.finish(this);//请求完成
    }

    final long requestTime;
    if(MarkerLog.ENABLED) {//如果开启了调试
        requestTime = Thread.currentThread().getId();
        if(Looper.myLooper() != Looper.getMainLooper()) {
            //如果请求不是主线程
            Handler mainThread = new Handler(Looper.getMainLooper());
            mainThread.post(new Runnable() {
                //在主线程中记录Log
                public void run() {
                    Request.this.mEventLog.add(tag, requestTime);
                    Request.this.mEventLog.finish(this.toString());
                }
            });
            return;
        }

        this.mEventLog.add(tag, requestTime);
        this.mEventLog.finish(this.toString());
    } else {//否则不开启调试
        requestTime = SystemClock.elapsedRealtime() - this.mRequestBirthTime;
        if(requestTime >= 3000L) {
            VolleyLog.d("%d ms: %s", new Object[]{Long.valueOf(requestTime), this.toString()});
        }
    }

}


/**
 * 请求优先级,比较定义,
 * @param other
 * @return
 */
public int compareTo(Request<T> other) {
    Request.Priority left = this.getPriority();
    Request.Priority right = other.getPriority();
    return left == right?this.mSequence.intValue() - other.mSequence.intValue():right.ordinal() - left.ordinal();
}

这里面发现开始定义的几个函数都比较简单,所有源代码并不是我们所说的那么难看懂.

Request 不是很难理解,主演是一些基本属性的设置,比如重试策略,重向标记,自定义标记,还有错误信息,当然还有编码问题

posted on 2016-06-05 23:58  forgot93  阅读(440)  评论(0编辑  收藏  举报

导航