1 /* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.volley.toolbox; 18 19 import android.content.Context; 20 import android.content.pm.PackageInfo; 21 import android.content.pm.PackageManager.NameNotFoundException; 22 import android.net.http.AndroidHttpClient; 23 import android.os.Build; 24 25 import com.android.volley.Network; 26 import com.android.volley.RequestQueue; 27 28 import java.io.File; 29 30 public class Volley { 31 32 /** Default on-disk cache directory. */ 33 private static final String DEFAULT_CACHE_DIR = "volley"; 34 35 /** 36 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. 37 * 38 * @param context A {@link Context} to use for creating the cache dir. 39 * @param stack An {@link HttpStack} to use for the network, or null for default. 40 * @return A started {@link RequestQueue} instance. 41 */ newRequestQueue(Context context, HttpStack stack)42 public static RequestQueue newRequestQueue(Context context, HttpStack stack) { 43 File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); 44 45 String userAgent = "volley/0"; 46 try { 47 String packageName = context.getPackageName(); 48 PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); 49 userAgent = packageName + "/" + info.versionCode; 50 } catch (NameNotFoundException e) { 51 } 52 53 if (stack == null) { 54 if (Build.VERSION.SDK_INT >= 9) { 55 stack = new HurlStack(); 56 } else { 57 // Prior to Gingerbread, HttpUrlConnection was unreliable. 58 // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html 59 stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); 60 } 61 } 62 63 Network network = new BasicNetwork(stack); 64 65 RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); 66 queue.start(); 67 68 return queue; 69 } 70 71 /** 72 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. 73 * 74 * @param context A {@link Context} to use for creating the cache dir. 75 * @return A started {@link RequestQueue} instance. 76 */ newRequestQueue(Context context)77 public static RequestQueue newRequestQueue(Context context) { 78 return newRequestQueue(context, null); 79 } 80 } 81