类似【网页图片查看器】,增加了缓存机制
如果是初次加载图片,会缓存到data/data/包/cache/目录下;如果是加载以前的图片,会直接从缓存文件夹中加载图片。
注:【1】需要访问网络操作需要:
【1.1】加载权限
【1.2】使用子线程
【2】不能在子线程更新UI 需要使用handler
思路:
【1】新建一个缓存文件夹并使用Base64加密
【1.1】
File file=new File(getCacheDir(),Base64.encodeToString(path.getBytes(), Base64.DEFAULT));
【2】初次加载
【2.1】实现文件的缓存,即将文件写入到cache文件夹中。这里涉及到文件的写入操作
【3】加载缓存
【3.1】直接加载绝对路径的缓存文件夹中的图片,这里用到的是decodeFile方法
Bitmap cacheBitmap = BitmapFactory.
decodeFile(file.getAbsolutePath());
【4】使用handler更新UI
代码如下:
package com.example.imagedemo;
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 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.util.Base64;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity {
private EditText et_web;
private ImageView iv;
private Handler handler=new Handler(){
public void handleMessage(Message msg) {
Bitmap bitmap=(Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//[1]找id
et_web = (EditText) findViewById(R.id.et_web);
iv = (ImageView) findViewById(R.id.iv);
}
public void click(View v){
new Thread(){
public void run(){
try {
String path=et_web.getText().toString().trim();
//缓存图片
//新建图片缓存地址并使用Base64加密
File file=new File(getCacheDir(),Base64.encodeToString(path.getBytes(), Base64.DEFAULT));
if(file.exists()&&file.length()>0){
System.out.println("使用缓存");
//直接从文件的绝对路径找到图片
Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg = Message.obtain();
msg.obj=cacheBitmap;
handler.sendMessage(msg);
}else{
System.out.println("第一次加载");
//找路径
//创建URL对象
URL url =new URL(path);
//拿到httpurlconnection对象 用于发送或接收请求
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
//设置发送请求
conn.setRequestMethod("GET");
//设置超时时长
conn.setConnectTimeout(5000);
//接收返回码
int code = conn.getResponseCode();
if(code==200){
InputStream in=conn.getInputStream();
//初始化输出流并输出
FileOutputStream fos=new FileOutputStream(file);
byte[] buf=new byte[1024];
int len=-1;
while((len=in.read(buf))!=-1){
fos.write(buf,0,len);
}
fos.close();
in.close();
//将流转换成bitmap格式
Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
//设置msg对象
Message msg=Message.obtain();
msg.obj=bitmap;
handler.sendMessage(msg);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}