在android的网络应用中,下载图片和显示图片需要消耗大量的时间,通过应用缓存机制可以提高用户体验,下面就给出一个简单的实例。
代码思路:
1.首先获取SDcard路径,在SDcard中新建文件夹作为图片缓存的地址,,利用hashmap保存url和对应的文件地址
2.进行判断图片是否已经下载过,如果下载过则从缓存中获取并且显示在页面上,如果没有则执行下载
下面是代码,代码里面有详细的说明:
1.异步类
public class DownloadTask extends AsyncTask<String,Integer,Integer> {
private String cachepath,urlString;
private File file;
private ImageView imageView;
private Map<String,String> cacheMap;
public DownloadTask(String cachepath,File file,ImageView imageView,Map<String,String> cacheMap,String urlString) {
this.cachepath = cachepath;
this.urlString=urlString;
this.file=file;
this.imageView=imageView;
this.cacheMap=cacheMap;
}
private URL url=null;
@Override
protected Integer doInBackground(String... params) {
//获取url
String urlString=params[0];
try {
url=new URL(urlString);
//打开网络连接
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
//获取文件名称
String filename=urlString.substring(urlString.lastIndexOf("/")+1);
//实例化新的文件目录
File dir=new File(cachepath);
//判断文件目录是否存在
if (!dir.exists()){
//创建新目录
dir.mkdir();
}
//创建新文件
file=new File(cachepath+filename);
file.createNewFile();
OutputStream outputStream=new FileOutputStream(file);
byte[] bytes=new byte[1024*4];
//写文件
while (inputStream.read(bytes)!=-1){
outputStream.write(bytes);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
@Override
protected void onPostExecute(Integer result) {
if (result>0){
//保存到缓存中,更新键值对
cacheMap.put(urlString, file.getPath());
Drawable drawable=Drawable.createFromPath(file.getPath());
imageView.setImageDrawable(drawable);
}
}
}
主类:
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private EditText editText;
private Button button;
//新建url对象
private URL url;
//获取SDcard根目录
private String sdCardpath= Environment.getExternalStorageDirectory()+"/";
//设置缓存目录
private String cachePath=sdCardpath+"picCaches/";
private Map<String,String> cacheMap=new HashMap<String,String>();
private File file;
private String urlString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageview);
editText= (EditText) findViewById(R.id.urltext);
button= (Button) findViewById(R.id.send);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
urlString=editText.getText().toString();
if (urlString!=null&&urlString.length()>0){
//判断是否以http开头
urlString=urlString.startsWith("http://")?urlString:"http://"+urlString;
//判断是否进行过缓存
if (cacheMap!=null&&cacheMap.containsKey(urlString))
{
//获取保存的地址
String cachefilePath=cacheMap.get(urlString).toString();
//验证该地址文档是否存在
if (FilePathExist(cachefilePath)){
Log.e("file","isexist");
//存在就显示缓存内容
Drawable drawable=Drawable.createFromPath(cachefilePath);
imageView.setImageDrawable(drawable);
Log.e("显示","执行缓存");
}else {
Log.e("download","执行下载");
//下载内容
downFile(urlString);
}
}else {
Log.e("download-------","执行下载");
downFile(urlString);
}
}
}
});
}
//下载文件
private void downFile(String urlString) {
//开启异步任务
new DownloadTask(cachePath,file,imageView,cacheMap,urlString).execute(urlString);
}
//判断文件路径是否存在
private boolean FilePathExist(String cachefilepath) {
File file=new File(cachefilepath);
return file.exists();
}
}
下面是结果:
由于图片像素问题所以现实的不清楚这里就不多做说明了,下面是执行的logcat输出:
可以看到,当我第一次点击按钮时候,执行的是下载图片的操作,也就是
Log.e("download-------","执行下载");
downFile(urlString);
这个操作,然后我再次点击按钮时候,则跳出了执行缓存的操作,说明文件已经存在,我们直接加载到页面时就可以了