这是一个简单的 AsyncTask,用于从 Web 下载和缓存图像:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;
/**
* Downloads an image from a URL and saves it to disk, to be referenced if the
* same URL is requested again
*/
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private static final String LOG = DownloadImageTask.class.getSimpleName();
ImageView mImageView;
public static final String IMAGE_CACHE_DIRECTORY = YourApplication
.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
.getAbsolutePath();
public DownloadImageTask(ImageView bmImage) {
this.mImageView = bmImage;
// TODO set to default "loading" drawable
mImageView.setImageBitmap(null);
}
@Override
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Log.v(LOG, "url: " + url);
String filename = url.substring(url.lastIndexOf("/") + 1, url.length());
Log.v(LOG, "filename: " + filename);
Bitmap bmp = getBitmapFromDisk(filename);
if (bmp == null) {
try {
InputStream in = new java.net.URL(url).openStream();
bmp = BitmapFactory.decodeStream(in);
writeBitmapToDisk(filename, bmp);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return bmp;
}
@Override
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
public boolean writeBitmapToDisk(String imageid, Bitmap bmp) {
boolean saved = false;
File path = new File(IMAGE_CACHE_DIRECTORY);
path.mkdirs();
File imageFile = new File(path, imageid);
FileOutputStream imageOS = null;
try {
imageOS = new FileOutputStream(imageFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
saved = bmp.compress(Bitmap.CompressFormat.JPEG, 95, imageOS);
return saved;
}
public Bitmap getBitmapFromDisk(String imageid) {
Bitmap bmp = BitmapFactory.decodeFile(IMAGE_CACHE_DIRECTORY + "/"
+ imageid);
return bmp;
}
}
这是这样实现的:
new DownloadImageTask(mImageView).execute("https://www.google.com/images/srpr/logo3w.png");