带缓存功能的图片查看器

public void loadImg() {
        final String path = "http://8080:www.baidu.com/helle.jpg";
        final File file = new File(getCacheDir(), getFileName(path));
        //首先判断文件缓存是否存在
        if (file.exists()) {
            //通过文件的绝对路径构造Bitmap对象
            Bitmap bp = BitmapFactory.decodeFile(file.getAbsolutePath());
            ImageView iv = new ImageView(this);
            iv.setImageBitmap(bp);
        } else {
            Thread thread = new Thread() {

                @Override
                public void run() {
                    try {
                        //1、获取URL对象
                        URL url = new URL(path);
                        //2、获取连接对象
                        HttpURLConnection conn = (HttpURLConnection) url
                                .openConnection();
                        //3、设置连接方法
                        conn.setRequestMethod("GET");
                        //读取超时
                        conn.setReadTimeout(5000);
                        //连接超时
                        conn.setConnectTimeout(5000);
                        //4、和服务器建立连接
                        conn.connect();
                        if (conn.getResponseCode() == 200) {
                            //5、拿到服务器返回的流
                            InputStream in = conn.getInputStream();
                            //6、开启文件输出流,把读取到的流写到本地
                            FileOutputStream fos = new FileOutputStream(file);
                            int len = 0;
                            byte[] b = new byte[1024];
                            while ((len = in.read(b)) != -1) {
                                fos.write(b, 0, len);
                            }
                            fos.close();

                            Bitmap bp = BitmapFactory.decodeFile(file
                                    .getAbsolutePath());

                            // Bitmap bp = BitmapFactory.decodeStream(in);
                            // ImageView iv=new ImageView(getContext());
                            // iv.setImageBitmap(bp);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值