Android简易实战教程--第二十六话《网络图片查看器在本地缓存》

本篇接第二十五话  点击打开链接   http://blog.csdn.net/qq_32059827/article/details/52389856

上一篇已经把王略中的图片获取到了。生活中有这么些场景:微信联网打开别人照片后,当手机断网的时候再去点击人家的额图片还能完整看到。这时候,已经不是去网路中获取图片了,其实微信在获取网络图片同时把图片在本地做咯额个缓存,这也是微信生成垃圾文件最多的原因之一。

本篇虽然以最简单直接的方式去对图片做缓存,但是,其实本质都差不多的。因为上一篇已经介绍的很详细了(读者可以去阅读),这一篇增加一点点功能就好了。代码如下:

package com.itydl.imageviewer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.ithiema.cacheimageviewer.R;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

	static ImageView iv;
	static MainActivity ma;
	static Handler handler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			
			switch (msg.what) {
			case 1:
				
				iv.setImageBitmap((Bitmap)msg.obj);
				break;

			case 0:
				Toast.makeText(ma, "请求失败", 0).show();
				break;
			}
			
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv = (ImageView) findViewById(R.id.iv);
		ma = this;
	}

	public void click(View v){
		
		final String path = "http://192.168.13.13:8080/dd.jpg";
		final File file = new File(getCacheDir(), getFileName(path));
		//判断,缓存中是否存在该文件
		if(file.exists()){
			//如果缓存存在,从缓存读取图片
			System.out.println("从缓存读取的");
			Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
			iv.setImageBitmap(bm);
		}
		else{
			//如果缓存不存在,从网络下载
			System.out.println("从网上下载的");
			Thread t = new Thread(){
				@Override
				public void run() {
					
					try {
						
						URL url = new URL(path);
						
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						
						conn.setRequestMethod("GET");
						
						conn.setConnectTimeout(5000);
						
						conn.setReadTimeout(5000);
						
						conn.connect();
						
						if(conn.getResponseCode() == 200){
							//获取服务器响应头中的流,流里的数据就是客户端请求的数据
							InputStream is = conn.getInputStream();
							
							//读取服务器返回的流里的数据,把数据写到本地文件,缓存起来
							
							FileOutputStream fos = new FileOutputStream(file);
							byte[] b = new byte[10240];
							int len = 0;
							while((len = is.read(b)) != -1){
								fos.write(b, 0, len);
							}
							fos.close();
							
							//读取出流里的数据,并构造成位图对象
							//流里已经没有数据了
//							Bitmap bm = BitmapFactory.decodeStream(is);
							Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
							
							
							Message msg = new Message();
							
							msg.obj = bm;
							msg.what = 1;
							//把消息发送至主线程的消息队列
							handler.sendMessage(msg);
							
						}
						else{
//							Toast.makeText(MainActivity.this, "请求失败", 0).show();
							
							Message msg = handler.obtainMessage();
							msg.what = 0;
							handler.sendMessage(msg);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			t.start();
		}
		
		
	}
	
	public String getFileName(String path){
		int index = path.lastIndexOf("/");
		return path.substring(index + 1);
	}

}

可以看到,首先是去本地缓存文件中获取图片信息的,如果获取不到,就去访问网络图片。只要一次访问网络成功,就会在本地获取到。除非做了清理。那么断网之后,再来运行一下效果看看吧:


原文地址:https://www.cnblogs.com/wanghang/p/6299598.html