Android学习(34) -- 带缓存的网络图片下载

加入缓存图片的功能

  • 把服务器返回的流里的数据读取出来,然后通过文件输入流写至本地文件

    //1.拿到服务器返回的输入流
    InputStream is = conn.getInputStream();
    //2.把流里的数据读取出来,并构造成图片
    
    FileOutputStream fos = new FileOutputStream(file);
    byte[] b = new byte[1024];
    int len = 0;
    while((len = is.read(b)) != -1){
        fos.write(b, 0, len);
    }
    
  • 创建bitmap对象的代码改成

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    
  • 每次发送请求前检测一下在缓存中是否存在同名图片,如果存在,则读取缓存

代码:

public class MainActivity extends Activity {

static ImageView iv;
static MainActivity ma;
static Handler handler = new Handler(){
    //此方法在主线程中调用,可以用来刷新ui
    public void handleMessage(android.os.Message msg) {
        //处理消息时,需要知道到底是成功的消息,还是失败的消息
        switch (msg.what) {
        case 1:
            //把位图对象显示至imageview
            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){
    //下载图片
    //1.确定网址
    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 {
                    //2.把网址封装成一个url对象
                    URL url = new URL(path);
                    //3.获取客户端和服务器的连接对象,此时还没有建立连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //4.对连接对象进行初始化
                    //设置请求方法,注意大写
                    conn.setRequestMethod("GET");
                    //设置连接超时
                    conn.setConnectTimeout(5000);
                    //设置读取超时
                    conn.setReadTimeout(5000);
                    //5.发送请求,与服务器建立连接
                    conn.connect();
                    //如果响应码为200,说明请求成功
                    if(conn.getResponseCode() == 200){
                        //获取服务器响应头中的流,流里的数据就是客户端请求的数据
                        InputStream is = conn.getInputStream();

                        //读取服务器返回的流里的数据,把数据写到本地文件,缓存起来

                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] b = new byte[1024];
                        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);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值