Skip to content

Instantly share code, notes, and snippets.

@ShenXuGongZi
Created November 8, 2013 23:25
Show Gist options
  • Save ShenXuGongZi/7379281 to your computer and use it in GitHub Desktop.
Save ShenXuGongZi/7379281 to your computer and use it in GitHub Desktop.
安卓获取远程图片
/**
* 异步下载图片
*/
class ImageDownloaderTask extendsAsyncTask<String, Void, Bitmap> {
private static final int IO_BUFFER_SIZE= 4 * 1024;
private String url;
private finalWeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageViewimageView) {
imageViewReference = newWeakReference<ImageView>(imageView);
}
@Override
protected BitmapdoInBackground(String... params) {
final AndroidHttpClient client =AndroidHttpClient.newInstance("Android");
url = params[0];
final HttpGet getRequest = newHttpGet(url);
try {
HttpResponse response =client.execute(getRequest);
final int statusCode =response.getStatusLine().getStatusCode();
if (statusCode !=HttpStatus.SC_OK) {
Log.w(TAG, "从" +url + "中下载图片时出错!,错误码:" + statusCode);
return null;
}
final HttpEntity entity =response.getEntity();
if (entity != null) {
InputStream inputStream =null;
OutputStream outputStream =null;
try {
inputStream =entity.getContent();
finalByteArrayOutputStream dataStream = new ByteArrayOutputStream();
outputStream = newBufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(inputStream,outputStream);
outputStream.flush();
final byte[] data =dataStream.toByteArray();
final Bitmap bitmap =BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;
} finally {
if (inputStream !=null) {
inputStream.close();
}
if (outputStream !=null) {
outputStream.close();
}
entity.consumeContent();
}
}
} catch (IOException e) {
getRequest.abort();
Log.w(TAG, "I/O errorwhile retrieving bitmap from " + url, e);
} catch (IllegalStateException e) {
getRequest.abort();
Log.w(TAG, "Incorrect URL:" + url);
} catch (Exception e) {
getRequest.abort();
Log.w(TAG, "Error whileretrieving bitmap from " + url, e);
} finally {
if (client != null) {
client.close();
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment