android网络下载图片并缓存

来源:互联网 发布:开通淘宝直播 编辑:程序博客网 时间:2024/05/17 06:38

功能:

实现网络下载图片,并缓存。缓存之后,即使断网,也能从缓存中读取已有的数据。(当缓存中有数据时,则不会启动异步任务)

--------------------------------------------MainActivity.java------------------------------------------------------------------------------

package com.example.downloadpicturetest;

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

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class MainActivity extends Activity {


private ImageView imageView;
private String url = "http://img0.bdstatic.com/img/image/shouye/mxym-9447375568.jpg";
private String imagesDocument = null; 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到存储图片文件的文件夹路径
imagesDocument = getApplication().getCacheDir().getAbsolutePath()+File.separator+"images";

imageView = (ImageView) findViewById(R.id.imageViewId);
//创建图片文件路径所指向文件的文件对象
File imageFile = new File(imagesDocument,ImageCacheUtils.getFileName(url));
if(imageFile.exists()){//如果图片文件存在
//从缓存中取出图片文件
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
//在imageView上显示图片
imageView.setImageBitmap(bitmap);

}else{//如果文件不存在
//创建异步任务对象,并启动异步任务(下载并缓存图片)
MyTask myTask = new MyTask();
myTask.execute(url);
}

}
/**
* 异步任务   下载图片
*/
class MyTask extends AsyncTask<String,Void, Bitmap>{

//创建一个虚拟的路径 指向 缓存目录下的 images文件夹
String imagesDocument = getApplication().getCacheDir().getAbsolutePath()+File.separator+"images"; 

@Override
protected Bitmap doInBackground(String... params) {
try{
HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet(params[0]);
HttpResponse response=client.execute(get);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//将请求响应的数据转成字节数组
byte[] bytes=EntityUtils.toByteArray(response.getEntity()); //开始从网络下载数据
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}


}catch(Exception e){
e.printStackTrace();
}


return null;
}




@Override
protected void onPostExecute(Bitmap result) {
if(result!=null){
File fileDir = new File(imagesDocument);//创建路径为imagesDir的文件夹对象
if(!fileDir.exists()){//如果文件夹对象不存在
fileDir.mkdir();//创建该文件夹
}
File imageFile = new File(fileDir,ImageCacheUtils.getFileName(url));//创建路径为fileDir+File.separator+getFileName()的文件对象
if(!imageFile.exists()){//如果文件不存在
try {
//将图片保存在该路径下(此处的result表示已经下载好的图片数据  bitmap )
result.compress(CompressFormat.JPEG, 100, new FileOutputStream(imageFile));

} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
imageView.setImageBitmap(result);
}
}

}
}

----------------------------------------------imageCacheUtils.java(工具类)-----------------------------------------------------------------------

package com.example.downloadpicturetest;


import java.io.File;


public class ImageCacheUtils {

/**
* 从Url中截取图片的名称
* 例如:
* url:"http://img0.bdstatic.com/img/image/shouye/mxym-9447375568.jpg"
* 截取出来的结果:mxym-9447375568.jpg
*/
public static String getFileName(String url){
return url.substring(url.lastIndexOf("/")+1);
}
}

-----------------------------------------------------------------------------------------------------------------------------------------------------

总结:

核心代码

1、//将图片写入缓存
      result.compress(CompressFormat.JPEG, 100, new FileOutputStream(imageFile));

2、//从缓存中取出图片文件
      Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
































0 0