Skip to content

Commit

Permalink
add new default Request , and update progress
Browse files Browse the repository at this point in the history
- ByteRequest added
- FileRequest added
- Add Update Progress
- Add VolleyBitmapLruCache Helper for Android 3.0 or above
  • Loading branch information
Alan committed Nov 21, 2013
1 parent 5ae5662 commit 3eac4f1
Show file tree
Hide file tree
Showing 11 changed files with 325 additions and 25 deletions.
5 changes: 3 additions & 2 deletions .classpath
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ gen
build
target
.gradle

.DS_Store
11 changes: 11 additions & 0 deletions src/com/android/volley/Request.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.android.volley;

import android.R.integer;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Handler;
Expand Down Expand Up @@ -497,6 +498,16 @@ protected VolleyError parseNetworkError(VolleyError volleyError) {
return volleyError;
}


/**
* Return the progress of the download
* @param response
* @return long[] , long[0] = size of file downloaded , int[1] = file size
*/
public long[] progressResponse(long[] response){
return response;
}

/**
* Subclasses must implement this to perform delivery of the parsed
* response to their listeners. The given response is guaranteed to
Expand Down
42 changes: 24 additions & 18 deletions src/com/android/volley/toolbox/BasicNetwork.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,22 @@

package com.android.volley.toolbox;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.cookie.DateUtils;

import android.os.SystemClock;

import com.android.volley.AuthFailureError;
Expand All @@ -31,22 +47,6 @@
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.cookie.DateUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* A network performing Volley requests over an {@link HttpStack}.
*/
Expand Down Expand Up @@ -103,7 +103,8 @@ public NetworkResponse performRequest(Request<?> request) throws VolleyError {

// Some responses such as 204s do not have content. We must check.
if (httpResponse.getEntity() != null) {
responseContents = entityToBytes(httpResponse.getEntity());
// add request to entityToBytes for notify the download process
responseContents = entityToBytes(request , httpResponse.getEntity());
} else {
// Add 0 byte response as a way of honestly representing a
// no-content request.
Expand Down Expand Up @@ -206,10 +207,12 @@ protected void logError(String what, String url, long start) {
}

/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
private byte[] entityToBytes(Request<?> request,HttpEntity entity) throws IOException, ServerError {
PoolingByteArrayOutputStream bytes =
new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
byte[] buffer = null;
long[] progress = new long[2];
progress[1] = (int) entity.getContentLength();
try {
InputStream in = entity.getContent();
if (in == null) {
Expand All @@ -219,6 +222,9 @@ private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError
int count;
while ((count = in.read(buffer)) != -1) {
bytes.write(buffer, 0, count);
progress[0] = bytes.size();
// Update the progress , may use for main view 's progress bar
request.progressResponse(progress);
}
return bytes.toByteArray();
} finally {
Expand Down
52 changes: 52 additions & 0 deletions src/com/android/volley/toolbox/ByteRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.android.volley.toolbox;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;


/**
* A canned request for retrieving the response body at a given URL as a byte[].
*/
public class ByteRequest extends Request<byte[]> {
private final Listener<byte[]> mListener;


/**
* Creates a new request with the given method.
*
* @param method the request {@link Method} to use
* @param url URL to fetch the string at
* @param listener Listener to receive the String response
* @param errorListener Error listener, or null to ignore errors
*/
public ByteRequest(int method, String url, Listener<byte[]> listener,
ErrorListener errorListener) {
super(method, url, errorListener);
mListener = listener;
}

/**
* Creates a new GET request.
*
* @param url URL to fetch the string at
* @param listener Listener to receive the String response
* @param errorListener Error listener, or null to ignore errors
*/
public ByteRequest(String url, Listener<byte[]> listener, ErrorListener errorListener) {
this(Method.GET, url, listener, errorListener);
}

@Override
protected void deliverResponse(byte[] response) {
mListener.onResponse(response);
}

@Override
protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
return Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
}
}
131 changes: 131 additions & 0 deletions src/com/android/volley/toolbox/FileRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.android.volley.toolbox;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.provider.MediaStore.Files;

/**
* A canned request for getting an file at a given URL and calling
* back with a File.
*
* like BitmapDowlload one
*
* @author extralam@github
*/
public class FileRequest extends Request<File> {

/** Socket timeout in milliseconds for image requests */
private static final int FILE_TIMEOUT_MS = 6000;
/** Default number of retries for image requests */
private static final int FILE_MAX_RETRIES = 3;
/** Default backoff multiplier for image requests */
private static final float FILE_BACKOFF_MULT = 2f;

private final Response.Listener<File> mListener;

/** Decoding lock so that we don't decode more than one image at a time (to avoid OOM's) */
private static final Object sDecodeLock = new Object();

private File mFile = null;

/**
*
* @param url
* @param file provide a File in main Activity
* @param listener
* @param errorListener
*/
public FileRequest(int method ,String url, File file, Response.Listener<File> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
setRetryPolicy(
new DefaultRetryPolicy(FILE_TIMEOUT_MS, FILE_MAX_RETRIES, FILE_BACKOFF_MULT));
mListener = listener;
mFile = file;
}

public FileRequest(String url, File file, Response.Listener<File> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
setRetryPolicy(
new DefaultRetryPolicy(FILE_TIMEOUT_MS, FILE_MAX_RETRIES, FILE_BACKOFF_MULT));
mListener = listener;
mFile = file;
}

@Override
public Priority getPriority() {
return Priority.LOW;
}

@Override
protected Response<File> parseNetworkResponse(NetworkResponse response) {
// Serialize all decode on a global lock to reduce concurrent heap usage.
synchronized (sDecodeLock) {
try {
return doParse(response);
} catch (OutOfMemoryError e) {
VolleyLog.e("Caught OOM for %d byte image, url=%s", response.data.length, getUrl());
return Response.error(new ParseError(e));
}
}
}

/**
* The real guts of parseNetworkResponse. Broken out for readability.
*/
private Response<File> doParse(NetworkResponse response) {
byte[] bytes = response.data;
//convert array of bytes into file
FileOutputStream stream;
try {
stream = new FileOutputStream(mFile);
stream.write(bytes);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

if (mFile == null) {
return Response.error(new ParseError(response));
} else {
return Response.success(mFile, HttpHeaderParser.parseCacheHeaders(response));
}
}

@Override
protected void deliverResponse(File response) {
mListener.onResponse(response);
}

}
36 changes: 36 additions & 0 deletions src/com/android/volley/toolbox/Volley.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,42 @@ public class Volley {
/** Default on-disk cache directory. */
private static final String DEFAULT_CACHE_DIR = "volley";

/**
*
* @param context A {@link Context} to use for creating the cache dir.
* @param stack An {@link HttpStack} to use for the network, or null for default.
* @param maxCacheSizeInBytes {@link Integer} size of the cache in bytes.
* @return A started {@link RequestQueue} instance.
*/
public static RequestQueue newRequestQueue(Context context, HttpStack stack ,int maxCacheSizeInBytes) {
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;
}

/**
* Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
*
Expand Down
Loading

0 comments on commit 3eac4f1

Please sign in to comment.