android volley,asynctask,finalhttp 请求对比volley 内存泄漏漏

Java Code Example com.android.volley.toolbox.HttpStack
Java Code Examples for com.android.volley.toolbox.HttpStack
The following are top voted examples for showing how to use
com.android.volley.toolbox.HttpStack. These examples are extracted from open source projects.
You can vote up the examples you like and your votes will be used in our system to product
more good examples.
+ Save this class to your library
public static RequestQueue newImageRequestQueue(Context context, HttpStack stack) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
String userAgent = &volley/0&;
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + &/& + info.versionC
} catch (PackageManager.NameNotFoundException e) {
if (stack == null) {
if (Build.VERSION.SDK_INT &= 9) {
stack = new HurlStack();
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new ImageDiskBasedCache(cacheDir), network);
queue.start();
* Creates a default instance of the worker pool and calls
RequestQueue#start()} on it.
* @param context A
Context} to use for creating the cache dir.
* @return A started
RequestQueue} instance.
public static RequestQueue newRequestQueue(Context context) {
if (Build.VERSION.SDK_INT &= 9) {
stack = new HurlStack();
stack = new HttpClientStack(AndroidHttpClient.newInstance(&volley&));
return newRequestQueue(context, stack);
* Creates a default instance of the worker pool and calls
RequestQueue#start()} on it. You may set a maximum size of the
* disk cache in bytes.
* @param context
Context} to use for creating the cache dir.
* @param stack
HttpStack} to use for the network, or null for
* @param maxDiskCacheBytes
the maximum size of the disk cache, in bytes. Use -1 for
default size.
* @return A started
RequestQueue} instance.
public static RequestQueue newRequestQueue(Context context,
HttpStack stack, int maxDiskCacheBytes) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
String userAgent = &volleyplus/0&;
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(
packageName, 0);
userAgent = packageName + &/& + info.versionC
} catch (NameNotFoundException e) {
if (stack == null) {
if (Build.VERSION.SDK_INT &= 9) {
//in order to support https
stack = new LarkHurlStack();
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// http://android-/2011/09/androids-http-clients.html
stack = new HttpClientStack(
AndroidHttpClient.newInstance(userAgent));
Network network = new BasicNetwork(stack);
if (maxDiskCacheBytes &= -1) {
// No maximum size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
// Disk cache size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir,
maxDiskCacheBytes), network);
queue.start();
public void shouldReturnMultipartHttpStackWrapper() {
HttpStack httpStack = HttpStackFactory.createDefaultHttpStack();
assertThat(httpStack, is(instanceOf(MultipartHttpStackWrapper.class)));
* Creates a default instance of the worker pool and calls
RequestQueue#start()} on it.
* @param stack
HttpStack} to use for the network, or null for
* @return A started
RequestQueue} instance.
public static RequestQueue newRequestQueue(HttpStack stack) {
File cacheDir = AcApp.isExternalStorageAvailable() ? AcApp
.getExternalCacheDir(DEFAULT_CACHE_DIR) : new File(AcApp
.context().getCacheDir(), DEFAULT_CACHE_DIR);
if (stack == null) {
if (Build.VERSION.SDK_INT &= 9) {
stack = new HurlStack();
// FIXME: dead code
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// http://android-/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(UA));
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir),
queue.start();
* @param httpStack
HTTP stack to be used
public QMusicNetwork(HttpStack httpStack) {
// If a pool isn't passed in, then build a small default pool that will
// give us a lot of
// benefit and not use too much memory.
this(httpStack, new ByteArrayPool(DEFAULT_POOL_SIZE));
* Creates a default instance of the worker pool and calls
RequestQueue#start()} on it.
* @param context A
Context} to use for creating the cache dir.
* @param stack
com.android.volley.toolbox.HttpStack} to use for the network, or null for default.
* @return A started
RequestQueue} instance.
private static RequestQueue newRequestQueue(Context context, HttpStack stack) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
String userAgent = &volley/0&;
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + &/& + info.versionC
} catch (PackageManager.NameNotFoundException e) {
if (stack == null) {
if (Build.VERSION.SDK_INT &= 9) {
stack = new HurlStack();
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir, CACHE_SIZE_DISK), network);
queue.start();
public void testWaspHttpStackCustom() throws Exception {
class MyHttpStack implements WaspHttpStack {
public HttpStack getHttpStack() {
return new OkHttpStack(new OkHttpClient());
public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
public void setCookieHandler(CookieHandler cookieHandler) {
Wasp.Builder builder = new Wasp.Builder(context)
.setWaspHttpStack(new MyHttpStack())
.setEndpoint(&http&);
builder.build();
//default should be NONE
assertThat(builder.getWaspHttpStack()).isInstanceOf(MyHttpStack.class);
private RequestQueue newRequestQueue(Context context) {
// define cache folder
File rootCache = context.getExternalCacheDir();
if (rootCache == null) {
rootCache = context.getCacheDir();
File cacheDir = new File(rootCache, DEFAULT_CACHE_DIR);
cacheDir.mkdirs();
HttpStack stack = new HurlStack();
Network network = new BasicNetwork(stack);
DiskBasedCache diskBasedCache = new DiskBasedCache(cacheDir, DEFAULT_DISK_USAGE_BYTES);
RequestQueue queue = new RequestQueue(diskBasedCache, network);
queue.start();
Example 10
private void tryRelogin(AuthFailureError ex, Request&?& request, AuthStrategy authStrategy, HttpStack httpStack, Converter converter) throws VolleyError {
if (authStrategy != null && authStrategy.authenticate(httpStack, converter, mNetworkHelper)) {
attemptRetryOnException(&auth&, request, ex);
Example 11
public static HttpStack createStack() {
if(hasOkHttp()) {
OkHttpClient okHttpClient = new OkHttpClient();
VolleyLog.d(&OkHttp found, using okhttp for http stack&);
return new OkHttpStack(okHttpClient);
else if (useHttpClient()){
VolleyLog.d(&Android version is older than Gingerbread (API 9), using HttpClient&);
return new HttpClientStack(AndroidHttpClient.newInstance(USER_AGENT));
VolleyLog.d(&Using Default HttpUrlConnection&);
return new HurlStack();
Example 12
* Creates a default instance of the worker pool and calls
com.android.volley.RequestQueue#start()} on it.
* @param context A
android.content.Context} to use for creating the cache dir.
* @param stack An
com.android.volley.toolbox.HttpStack} to use for the network, or null for default.
* @return A started
com.android.volley.RequestQueue} instance.
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
String userAgent = &volley/0&;
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + &/& + info.versionC
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
if (stack == null) {
if (Build.VERSION.SDK_INT &= 9) {
stack = new HurlStack();
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
Network network = new BasicNetwork(stack);
SmartRequestQueue queue = new SmartRequestQueue(new DiskBasedCache(cacheDir), network);
//SmartRequestQueue queue = new SmartRequestQueue(new BitmapLruImageCache(100), network);
queue.start();
Example 13
* Creates a default instance of the worker pool and calls
RequestQueue#start()} on it.
* @param stack
HttpStack} to use for the network, or null for
* @return A started
RequestQueue} instance.
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
File cacheDir = CommonUtil.isExternalStorageAvailable() ? CommonUtil.getExternalCacheDir(
context, DEFAULT_CACHE_DIR) : new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
Log.i(DEFAULT_CACHE_DIR, cacheDir.getAbsolutePath());
if (stack == null)
stack = new HurlStack();
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();
Example 14
public static RequestQueue getRequestQueue(Context context, Cache diskCache) {
String userAgent = &volley/0&;
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + &/& + info.versionC
} catch (NameNotFoundException e) {
final HttpS
if (Build.VERSION.SDK_INT &= 9) {
stack = new HurlStack();
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(diskCache, network);
queue.start();
Example 15
public static RequestQueue getRequestQueue(Context context, Cache diskCache) {
String userAgent = &volley/0&;
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + &/& + info.versionC
} catch (NameNotFoundException e) {
final HttpS
if (Build.VERSION.SDK_INT &= 9) {
stack = new HurlStack();
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(diskCache, network);
queue.start();
Example 16
public static RequestQueue newRequestQueue(Context context, int threadPoolSize) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
String userAgent = &volley/0&;
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + &/& + info.versionC
} catch (PackageManager.NameNotFoundException e) {
if (Build.VERSION.SDK_INT &= 9) {
stack = new HurlStack();
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
Network network = new BasicNetwork(stack);
ResponseDelivery delivery = new ExecutorDelivery(Executors.newFixedThreadPool(threadPoolSize));
// pass ResponseDelivery object as a 4th parameter for RequestQueue constructor
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network, threadPoolSize, delivery);
queue.start();
Example 17
public static HttpStack getHTTPClientStack(final Context ctx, final Blog currentBlog) {
SSLSocketFactory mSslSocketFactory =
TrustManager[] trustAllowedCerts = new TrustManager[]{ new BWTrustManager(SelfSignedSSLCertsManager.getInstance(ctx).getLocalKeyStore()) };
SSLContext context = SSLContext.getInstance(&SSL&);
context.init(null, trustAllowedCerts, new SecureRandom());
mSslSocketFactory = context.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
AppLog.e(AppLog.T.API, e);
} catch (KeyManagementException e) {
AppLog.e(AppLog.T.API, e);
} catch (GeneralSecurityException e) {
AppLog.e(AppLog.T.API, e);
} catch (IOException e) {
AppLog.e(AppLog.T.API, e);
HurlStack stack = new HurlStack(null, mSslSocketFactory) {
public HttpResponse performRequest(Request&?& request, Map&String, String& headers)
throws IOException, AuthFailureError {
if (request.getUrl() != null) {
if (!StringUtils.getHost(request.getUrl()).endsWith(&&) && currentBlog != null && currentBlog.hasValidHTTPAuthCredentials()) {
HashMap&String, String& authParams = new HashMap&String, String&();
String creds = String.format(&%s:%s&, currentBlog.getHttpuser(), currentBlog.getHttppassword());
String auth = &Basic & + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
authParams.put(&Authorization&, auth);
headers.putAll(authParams);
if (StringUtils.getHost(request.getUrl()).endsWith(&&) && ctx != null && BioWiki.getWPComAuthToken(ctx) != null) {
// Add the auth header to access
HashMap&String, String& authParams = new HashMap&String, String&();
authParams.put(&Authorization&, &Bearer & + BioWiki.getWPComAuthToken(ctx));
headers.putAll(authParams);
HashMap&String, String& defaultHeaders = new HashMap&String, String&();
defaultHeaders.put(&User-Agent&, BioWiki.getUserAgent());
headers.putAll(defaultHeaders);
return super.performRequest(request, headers);
return new HurlStack(null);
Example 18
@SuppressLint(&NewApi&)
public void onCreate() {
TIDSSTEMPEL_VED_OPSTART = System.currentTimeMillis();
netvaerk = new Netvaerksstatus();
EMULATOR = Build.PRODUCT.contains(&sdk&) || Build.MODEL.contains(&Emulator&);
if (!EMULATOR)
BugSenseHandler.initAndStartSession(this, getString(PRODUKTION ? R.string.bugsense_n?gle : R.string.bugsense_testn?gle));
super.onCreate();
forgrundstr?d = new Handler();
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
audioManager = (AudioManager) App.instans.getSystemService(Context.AUDIO_SERVICE);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
fejls?gning = prefs.getBoolean(&fejls?gning&, false);
res = App.instans.getResources();
App.color = new DRFarver();
// HTTP-forbindelser havde en fejl prae froyo, men jeg har ogs? set problemet p? Xperia Play, der er 2.3.4 (!)
if (Build.VERSION.SDK_INT & Build.VERSION_CODES.HONEYCOMB) {
System.setProperty(&http.keepAlive&, &false&);
String packageName = getPackageName();
if (AEGTE_DR) if (&dk.dr.radio&.equals(packageName)) {
if (!PRODUKTION) App.langToast(&Saet PRODUKTIONs-flaget&);
if (PRODUKTION) App.langToast(&Testudgave - fjern PRODUKTIONs-flaget&);
//noinspection ConstantConditions
PackageInfo pi = getPackageManager().getPackageInfo(packageName, 0);
App.versionsnavn = packageName + &/& + pi.versionN
if (EMULATOR) App.versionsnavn += & EMU&;
Log.d(&App.versionsnavn=& + App.versionsnavn);
App.erInstalleretP?SDKort = 0!=(pi.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE);
/* check for API level 7 - check files dir
String filesDir = context.getFilesDir().getAbsolutePath();
if (filesDir.startsWith(&/data/&)) {
} else if (filesDir.contains(&/mnt/&) || filesDir.contains(&/sdcard/&)) {
} catch (Throwable e) {
if (!App.erInstalleretP?SDKort) prefs.edit().remove(N?GLE_advaretOmInstalleretP?SDKort).commit();
Class.forName(&android.os.AsyncTask&); // Fix for /p/android/issues/detail?id=20915
} catch (Exception e) {
Log.rapporterFejl(e);
accessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
if (!AEGTE_DR) FilCache.init(new File(getCacheDir(), &FilCache&));
// Initialisering af Volley
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-/2011/09/androids-http-clients.html
HttpStack stack =
Build.VERSION.SDK_INT &= 9 ? new HurlStack()
: Build.VERSION.SDK_INT &= 8 ? new HttpClientStack(AndroidHttpClient.newInstance(App.versionsnavn))
: new HttpClientStack(new DefaultHttpClient()); // Android 2.1 -
: new HurlStack(); // Android 2.1
// HTTP connection reuse was buggy pre-froyo
if (Build.VERSION.SDK_INT & Build.VERSION_CODES.FROYO) {
System.setProperty(&http.keepAlive&, &false&);
// Vi bruger vores eget Netvaerkslag, da DRs Varnish-servere ofte svarer med HTTP-kode 500,
// som skal h?ndteres som et timeout og at der skal pr?ves igen
Network network = new DrBasicNetwork(stack);
// Vi bruger vores egen DrDiskBasedCache, da den indbyggede i Volley
// har en opstartstid p? flere sekunder
// Mappe aendret fra standardmappen &volley& til &dr_volley& 19. nov 2014.
// Det skyldtes at et hukommelsesdump viste, at Volley indekserede alle filerne i standardmappen,
// uden om vores implementation, hvilket gav et un?dvendigt overhead p? ~ 1MB
File cacheDir = new File(getCacheDir(), &dr_volley&);
volleyCache = new DrDiskBasedCache(cacheDir);
volleyRequestQueue = new RequestQueue(volleyCache, network);
volleyRequestQueue.start();
// P4 stedplacering skal ske s? tidligt som muligt - ellers
// n?r P4-valgskaermbilledet at blive instantieret med ukendt placering og foresl?r derfor K?benhavn
// Sl?et fra, da stedplaceringen ikke virker
// if (prefs.getString(P4_FORETRUKKEN_GAET_FRA_STEDPLACERING, null) == null) startP4stedplacering();
DRData.instans = new DRData();
DRData.instans.grunddata = new Grunddata();
// Indlaesning af grunddata/stamdata.
// F?rst tjekkes om vi har en udgave i prefs, og ellers bruges den i raw-mappen
// P? et senere tidspunkt henter vi nye grunddata
grunddata_prefs = App.instans.getSharedPreferences(&grunddata&, 0);
String grunddata = grunddata_prefs.getString(DRData.GRUNDDATA_URL, null);
if (grunddata == null) {
grunddata = App.prefs.getString(DRData.GRUNDDATA_URL, null);
if (grunddata!=null) { // 28 nov 2014 - flyt data fra faelles prefs til separat fil - kan fjernes ultimo 2015
App.prefs.edit().remove(DRData.GRUNDDATA_URL).commit();
grunddata_prefs.edit().putString(DRData.GRUNDDATA_URL, grunddata).commit();
if (!AEGTE_DR) App.prefs.edit().putBoolean(&vispager_title_strip&, true).commit();
if (App.prefs.contains(&stamdata23&) || App.prefs.contains(&stamdata24&)) {
// 24 feb 2015 - fjern gamle stamdata fra prefs - kan fjernes primo 2016
App.prefs.edit().remove(&stamdata22&).remove(&stamdata23&).remove(&stamdata24&).commit();
if (grunddata == null)
grunddata = Diverse.laesStreng(res.openRawResource(App.PRODUKTION ? R.raw.grunddata : R.raw.grunddata_udvikling));
DRData.instans.grunddata.parseFaellesGrunddata(grunddata);
if (App.fejls?gning && DRData.instans.grunddata.udelukHLS) App.kortToast(&HLS er udelukket&);
String pn = App.instans.getPackageName();
for (final Kanal k : DRData.instans.grunddata.kanaler) {
k.kanallogo_resid = res.getIdentifier(&kanalappendix_& + k.kode.toLowerCase().replace('?', 'o').replace('?', 'a'), &drawable&, pn);
String kanalkode = prefs.getString(FORETRUKKEN_KANAL, null);
// Hvis brugeren foretraekker P4 er vi n?dt til at finde underkanalen
kanalkode = tjekP4OgVaelgUnderkanal(kanalkode);
Kanal aktuelKanal = DRData.instans.grunddata.kanalFraKode.get(kanalkode);
if (aktuelKanal == null || aktuelKanal == Grunddata.ukendtKanal) {
aktuelKanal = DRData.instans.grunddata.forvalgtK
Log.d(&forvalgtKanal=& + aktuelKanal);
if (!aktuelKanal.harStreams()) { // ikke && App.erOnline(), det kan vaere vi har en cachet udgave
final Kanal kanal = aktuelK
Request&?& req = new DrVolleyStringRequest(aktuelKanal.getStreamsUrl(), new DrVolleyResonseListener() {
public void fikSvar(String json, boolean fraCache, boolean uaendret) throws Exception {
if (uaendret) // ingen grund til at parse det igen
kanal.setStreams(json);
Log.d(&hentStreams akt fraCache=& + fraCache + & =& & + kanal);
public Priority getPriority() {
return Priority.HIGH;
App.volleyRequestQueue.add(req);
DRData.instans.afspiller = new Afspiller();
DRData.instans.afspiller.setLydkilde(aktuelKanal);
registerReceiver(netvaerk, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
netvaerk.onReceive(this, null); // F? opdateret netvaerksstatus
fjernbetjening = new Fjernbetjening();
// udest?endeInitialisering kaldes n?r aktivitet bliver synlig f?rste gang
// - muligvis aldrig hvis app'en kun betjenes via levende ikon
} catch (Exception ex) {
// Burde der vaere popop-advarsel til bruger om intern fejl og rapporter til udvikler-dialog ?
Log.rapporterFejl(ex);
try { // DRs skrifttyper er ikke offentliggjort i SVN, derfor kan f?lgende fejle:
skrift_gibson = Typeface.createFromAsset(getAssets(), &Gibson-Regular.otf&);
skrift_gibson_fed = Typeface.createFromAsset(getAssets(), &Gibson-SemiBold.otf&);
skrift_georgia = Typeface.createFromAsset(getAssets(), &Georgia.ttf&);
} catch (Exception e) {
if (AEGTE_DR) Log.e(&DRs skrifttyper er ikke tilgaengelige&, e);
skrift_gibson = Typeface.DEFAULT;
skrift_gibson_fed = Typeface.DEFAULT_BOLD;
skrift_georgia = Typeface.SERIF;
skrift_gibson_fed_span = new EgenTypefaceSpan(&Gibson fed&, App.skrift_gibson_fed);
Log.d(&onCreate tog & + (System.currentTimeMillis() - TIDSSTEMPEL_VED_OPSTART) + & ms&);

我要回帖

更多关于 asynctask volley 的文章

 

随机推荐