Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android volley封裝及源碼解析

android volley封裝及源碼解析

編輯:關於Android編程

1.簡單使用volley

Volley.newRequestQueue(this).add(new StringRequest(Request.Method.GET, "http://api.wumeijie.net/list", new Response.Listener() {
    @Override
    public void onResponse(String response) {
        //TODO 處理響應數據
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        //TODO 處理請求失敗情況
    }
}));

2.封裝VolleyManager

完整代碼:https://github.com/snailycy/volley_manager

注意,volley裡面的請求隊列建議使用單例,因為每次實例化ReqeustQueue並start()時,會創建1個緩存線程和4個網絡請求線程,多次調用start()會創建多余的被interrupt的線程,造成資源浪費

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class VolleyManager {
    private static RequestQueue requestQueue;
    //超時時間 30s
    private final static int TIME_OUT = 30000;

    private static RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            synchronized (VolleyManager.class) {
                if (requestQueue == null) {
                    //使用全局context對象
                    requestQueue = Volley.newRequestQueue(MyApplication.getContext());
                }
            }
        }
        return requestQueue;
    }

    private static  void addRequest(RequestQueue requestQueue, Request request) {
        request.setShouldCache(true);
        request.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);
    }

    public static void sendJsonObjectRequest(int method, String url,
                                             JSONObject params,
                                             final Response.Listener listener,
                                             final Response.ErrorListener errorListener) {
        try {
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(method,
                    url, params, listener, errorListener) {
                @Override
                public Map getHeaders() throws AuthFailureError {
                    Map headers = new HashMap<>();
                    headers.put("accept-encoding", "utf-8");
                    return headers;
                }
            };
            addRequest(getRequestQueue(), jsonObjectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendStringRequest(int method, String url,
                                         final Map params,
                                         final Response.Listener listener,
                                         final Response.ErrorListener errorListener) {
        try {
            StringRequest stringRequest = new StringRequest(method, url, listener, errorListener) {
                @Override
                protected Map getParams() throws AuthFailureError {
                    return params;
                }
            };
            addRequest(getRequestQueue(), stringRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

封裝完了,使用起來也非常簡單

//使用StringRequest
HashMap params = new HashMap<>();
params.put("params1", "xixi");
VolleyManager.sendStringRequest(Request.Method.GET,
        "http://api.wumeijie.net/list", params,
        new Response.Listener() {
            @Override
            public void onResponse(String response) {
                //TODO 處理響應數據
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //TODO 處理請求失敗情況
            }
        });

或者

//使用JsonObjectRequest
JSONObject params = new JSONObject();
try {
    params.put("params1", "xixi");
} catch (JSONException e) {
    e.printStackTrace();
}
VolleyManager.sendJsonObjectRequest(Request.Method.GET,
        "http://api.wumeijie.net/list", params,
        new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                //TODO 處理響應數據
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //TODO 處理請求失敗情況
            }
        });

3.源碼分析

3.1 Volley在創建RequestQueue時,會先創建一個HttpStack對象,該對象在系統版本<=9時,是由實現類HurlStack創建,具體是用HttpURLConnection來實現網絡請求,在系統版本>9時,是由實現類HttpClientStack創建,使用的是HttpClient來實現網絡請求
源碼如下:(Volley類中newRequestQueue方法)

    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

        String userAgent = "volley/0";
        try {
            String packageName = context.getPackageName();
            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
            userAgent = packageName + "/" + info.versionCode;
        } catch (NameNotFoundException e) {
        }

        if (stack == null) {
            if (Build.VERSION.SDK_INT >= 9) {
                stack = new HurlStack();
            } else {
                // Prior to Gingerbread, HttpUrlConnection was unreliable.
                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }

        Network network = new BasicNetwork(stack);

        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        queue.start();

        return queue;
    }

3.2 創建RequestQueue,主要是創建了1個緩存線程和4個網絡請求線程,這5個線程共用1個請求隊列,共用1個緩存對象,共用1個ResponseDelivery
源碼如下:(請求隊列RequestQueue類中start方法)

public void start() {
    stop();  // Make sure any currently running dispatchers are stopped.
    // Create the cache dispatcher and start it.
    mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
    mCacheDispatcher.start();

    // Create network dispatchers (and corresponding threads) up to the pool size.
    for (int i = 0; i < mDispatchers.length; i++) {
        NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                mCache, mDelivery);
        mDispatchers[i] = networkDispatcher;
        networkDispatcher.start();
    }
}

3.3 緩存線程run方法中,主要是一個死循環,不斷的從緩存隊列中取出請求對象,如果該請求對象緩存丟失或者不需要緩存或者需要刷新緩存數據,則加入到請求隊列中,否則,直接解析緩存後通過ResponseDelivery對象中的handler post到主線程中執行響應回調接口
源碼如下:(緩存線程CacheDispatcher類中run方法)

@Override
public void run() {
    if (DEBUG) VolleyLog.v("start new dispatcher");
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    // Make a blocking call to initialize the cache.
    mCache.initialize();

    while (true) {
        try {
            // Get a request from the cache triage queue, blocking until
            // at least one is available.
            final Request request = mCacheQueue.take();
            request.addMarker("cache-queue-take");

            // If the request has been canceled, don't bother dispatching it.
            if (request.isCanceled()) {
                request.finish("cache-discard-canceled");
                continue;
            }

            // Attempt to retrieve this item from cache.
            Cache.Entry entry = mCache.get(request.getCacheKey());
            if (entry == null) {
                request.addMarker("cache-miss");
                // Cache miss; send off to the network dispatcher.
                mNetworkQueue.put(request);
                continue;
            }

            // If it is completely expired, just send it to the network.
            if (entry.isExpired()) {
                request.addMarker("cache-hit-expired");
                request.setCacheEntry(entry);
                mNetworkQueue.put(request);
                continue;
            }

            // We have a cache hit; parse its data for delivery back to the request.
            request.addMarker("cache-hit");
            Response response = request.parseNetworkResponse(
                    new NetworkResponse(entry.data, entry.responseHeaders));
            request.addMarker("cache-hit-parsed");

            if (!entry.refreshNeeded()) {
                // Completely unexpired cache hit. Just deliver the response.
                mDelivery.postResponse(request, response);
            } else {
                // Soft-expired cache hit. We can deliver the cached response,
                // but we need to also send the request to the network for
                // refreshing.
                request.addMarker("cache-hit-refresh-needed");
                request.setCacheEntry(entry);

                // Mark the response as intermediate.
                response.intermediate = true;

                // Post the intermediate response back to the user and have
                // the delivery then forward the request along to the network.
                mDelivery.postResponse(request, response, new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mNetworkQueue.put(request);
                        } catch (InterruptedException e) {
                            // Not much we can do about this.
                        }
                    }
                });
            }

        } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
            if (mQuit) {
                return;
            }
            continue;
        }
    }
}

3.4 網絡線程run方法中,主要是一個死循環,不斷的從請求隊列中取出請求對象,然後根據系統版本使用HttpStack對象來進行網絡請求(包括設置請求參數,請求頭,請求方法等信息),最終返回一個HttpResponse對象,接著就是解析響應數據,處理緩存情況,最後通過ResponseDelivery對象中的handler post到主線程中執行響應回調接口
源碼如下:(網絡請求線程NetWorkDispatcher類中run方法)

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    while (true) {
        long startTimeMs = SystemClock.elapsedRealtime();
        Request request;
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
            if (mQuit) {
                return;
            }
            continue;
        }

        try {
            request.addMarker("network-queue-take");

            // If the request was cancelled already, do not perform the
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }

            addTrafficStatsTag(request);

            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");

            // If the server returned 304 AND we delivered a response already,
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }

            // Parse the response here on the worker thread.
            Response response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");

            // Write to cache if applicable.
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }

            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            VolleyError volleyError = new VolleyError(e);
            volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
            mDelivery.postError(request, volleyError);
        }
    }
}

3.5 當步驟3.4中執行

NetworkResponse networkResponse = mNetwork.performRequest(request);

時,會將請求分發給不同版本的網絡請求實現類,這裡以HurlStack為例,請求最終分發到HurlStack中的performRequest方法執行
源碼如下:(HurlStack類中performRequest方法)

@Override
public HttpResponse performRequest(Request request, Map additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap map = new HashMap();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion,
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

3.6 執行完步驟3.5後,拿到一個響應對象HttpResponse,接著步驟3.4解析響應對象:

Response response = request.parseNetworkResponse(networkResponse);

,執行響應回調:

mDelivery.postResponse(request, response);

這個mDelivery(ExecutorDelivery類型)就是在創建RequestQueue時創建的ResponseDelivery對象,主要負責回調響應接口
注:ExecutorDelivery implements ResponseDelivery
源碼如下:(ExecutorDelivery類中postResponse方法)

@Override
public void postResponse(Request request, Response response, Runnable runnable) {
    request.markDelivered();
    request.addMarker("post-response");
    mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
}

ExecutorDelivery屬性mResponsePoster具體實現有兩種方式,這裡使用的是handler實現
源碼如下:(ExecutorDelivery類的構造方法)

public ExecutorDelivery(final Handler handler) {
    // Make an Executor that just wraps the handler.
    mResponsePoster = new Executor() {
        @Override
        public void execute(Runnable command) {
            handler.post(command);
        }
    };
}

注:這個構造方法傳進來的Handler對象拿的是主線程中的Looper對象

volley源碼:https://android.googlesource.com/platform/frameworks/volley

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved