android 图片库的封装

大家在做安卓应用的时候  经常要从网络中获取图片 都是通过URL去获取 可是如果本地有图片数据 从本地获取数据不更加快一些  自己在工作中遇到这个问题 所以采用了一个URL和本地图片的一个映射关系  先从本地区获取 假如本地没有再从网络中获取  本方法考虑到多线程问题  欢迎大家一起共同探讨!

public class PictureLibrary {
    /*
     * 图片库的操作
     */

    File file;

    URL url;
    HttpURLConnection conn;
    InputStream is;
    FileOutputStream fos;

    private Lock lock = new ReentrantLock();

    private Condition downFile = lock.newCondition();

    // 通过URL将数据下载到本地操作
    private String toLocalFile(String strURL) {
        String fileName = Utils.getFileName(strURL);
        String path = Environment.getExternalStorageDirectory() + "/"
                + EcologicalTourism.FILE_PATH + "/images/" + fileName;

        return path;
    }

    // 通过URL将数据下载到本地临时文件中
    private String toLocalFileTemp(String strURL) {
        String s = Utils.getFileName(strURL);
        String fileName = s+"temp";
        String path_url = Environment.getExternalStorageDirectory() + "/"
                + EcologicalTourism.FILE_PATH + "/tempimages/" + fileName;

        return path_url;
    }


    /*
     * 保存图片到本地,并返回本地url(此函数是阻塞的)
     * main
     * @参数:strURL,参数为图片的URL.返回值:该图片在本地SD卡暂存的位置
     * 函数的工作是负责将图片从互联网上取得,存在本地存储中,并返回本地存储的文件路径,供调用者直接使用。如果文件已经存在本地,直接返回
     * 如果文件未在本地,则直接从服务器下载,函数阻塞。
     */
    public String getReadSD(String strURL) {
        Log.i("test", "拿到网络的地址是:" + strURL);
        String strLocalFile = toLocalFile(strURL);  //k:把服务器URL转换为本地URL
        String strLocalFileTemp = toLocalFileTemp(strURL); //k:把服务器URL转换为本地临时URL
        while (true) {
            File file = new File(strLocalFile);
            Log.i("test", "本地文件是:" + strLocalFile);
            File tfile = new File(strLocalFileTemp);
            Log.i("test", "临时文件是:" + strLocalFileTemp);
            // 1上锁
            lock.lock();

            if (file.exists()) {
                // 2if 本地文件存在
                // 解锁
                // 返回本地路径
                lock.unlock();
                Log.i("test", "返回本地路径:" + file);
                return strLocalFile;
            } else if (tfile.exists()) {
                // if 对应的暂存文件存在
                // 解锁
                lock.unlock();
                try {
                    // 睡眠
                    downFile.await();
                } catch (Exception e) {
                     e.printStackTrace();
                    Log.i("test", "e 出现了异常1" + e);
                }

            } else {
                try {
                    // 创建对应的暂存文件
                    tfile.createNewFile();
                } catch (IOException e) {
                    Log.i("test", "e 出现了异常2" + e);

                }
                // 解锁
                lock.unlock();
                // 下载文件内容到暂存文件中
                downURL2(strURL, strLocalFile);
                // 上锁
                lock.lock();
                // 修改暂存文件名字为本地文件名
                tfile.renameTo(file);
                // 解锁
                lock.unlock();
            }

        }
    }
    
    

    private void downURL2(String strURL, String strLocalFileTemp) {
        // TODO Auto-generated method stub
        URL url;
        try {
            url = new URL(strURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    FileOutputStream fos = new FileOutputStream(strLocalFileTemp);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                    }
                    is.close();
                    fos.close();
                    // 返回一个URI对象
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }

    
    /*
     * 阻塞式下载url到文件 toFile中
     */
    private boolean downURL(String strURL, String toFile) {
       
        URL url;
        try {
            url = new URL(strURL);
            HttpURLConnection httpUrl = (HttpURLConnection) url
                    .openConnection();
            httpUrl.setRequestMethod("GET");
            int fileSize = httpUrl.getContentLength();// 文件大小
            httpUrl.disconnect();// 关闭连接
            int threadSize = 6;// 默认设置6个线程
            threadSize = fileSize % threadSize == 0 ? threadSize
                    : threadSize + 1;
            int currentSize = fileSize / threadSize; // 每条线程下载大小

            String dowloadir = Environment.getExternalStorageDirectory() + "/"
                    + EcologicalTourism.FILE_PATH + "/images/";

            File dir = new File(dowloadir);

            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, toFile);
            RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
            randomFile.setLength(fileSize);// 指定 file 文件的大小
            for (int i = 0; i < threadSize; i++) {
                int startposition = i * currentSize;// 每条线程开始写入文件的位置
                RandomAccessFile threadFile = new RandomAccessFile(file, "rw");
                Log.i("syso", "toFile的内容是:" + toFile);
                threadFile.seek(startposition);
                new DownLoadThread(i, currentSize, threadFile, startposition,
                        url).start();
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.i("syso", "download下载失败" + e);
        }

        return true;
    }


    /**
     * 实现线程下载
     *
     */
    private static class DownLoadThread extends Thread {
        @SuppressWarnings("unused")
        private int threadId;// 线程编号
        private int currentSize;// 每条线程的大小
        private RandomAccessFile threadFile; // 每条线程 要写入文件类
        private int startposition;// 每条线程开始写入文件的位置
        private URL url;  //网络地址

        public DownLoadThread(int threadId, int currentSize,
                RandomAccessFile threadFile, int startposition, URL url) {
            this.threadId = threadId;
            this.currentSize = currentSize;
            this.threadFile = threadFile;
            this.startposition = startposition;
            this.url = url;
        }

        public void run() {
            try {
                HttpURLConnection httpUrl = (HttpURLConnection) url
                        .openConnection();
                httpUrl.setRequestMethod("GET");
                httpUrl.setRequestProperty("range", "bytes=" + startposition
                        + "-");// 指定服务器的位置
                InputStream is = httpUrl.getInputStream();
                byte[] data = new byte[1024];
                int len = -1;
                int threadFileSize = 0;
                while ((threadFileSize < currentSize)
                        && ((len = is.read(data)) != -1)) {
                    threadFile.write(data, 0, len);
                    threadFileSize += len;
                }
                httpUrl.disconnect();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    
    /**
    * 从本缓存中获取图片
    */
    public  Bitmap getBitmapFromCache(String imageURL) {
//        String bitmapName = imageURL.substring(imageURL.lastIndexOf("/") + 1);
        String bitmapName = Utils.getFileName(imageURL);
        File cacheDir = new File(Environment.getExternalStorageDirectory() + "/"
                + EcologicalTourism.FILE_PATH + "/images/");    
        File[] cacheFiles = cacheDir.listFiles();    
        int i = 0;    
        if(null!=cacheFiles){  
            for(; i<cacheFiles.length;i++){    
                if(bitmapName.equals(cacheFiles[i].getName())){    
                    break;    
                }    
            }    
                
            if(i < cacheFiles.length)    
            {    
                return BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/"
                        + EcologicalTourism.FILE_PATH + "/images/" + bitmapName);    
            }
          
        }
        return null;  
    }
   

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本人测试过,挺好用的,省去了好多麻烦:afinal 0.3 主要更新如下: 1、更新FinalBitmap模块,解决线程并发没有回收线程的问题 2、重写了FinalHttp模块 具体 change log 如下: FinalBitmap添加三个方法 public void onResume() public void onPause() public void onDestroy() 在activity生命周期方法中调用给方法释放内存和暂停图片加载线程 FinalHttp添加方法如下(目前AjaxCallBack泛型只支持String和file。有时间将会扩展JSONObject,xmlDom,byte[],bitmap等): public HttpClient getHttpClient() public HttpContext getHttpContext() public void configCookieStore(CookieStore cookieStore) //配置cookie public void configUserAgent(String userAgent) public void configTimeout(int timeout)//配置超时时间 public void configSSLSocketFactory(SSLSocketFactory sslSocketFactory) //配置https请求 public void configRequestExecutionRetryCount(int count)//配置网络异常自动重复连接请求次数 public void addHeader(String header, String value) //添加http请求头 //------------------get 请求----------------------- public void get( String url, AjaxCallBack<? extends Object> callBack) public void get( String url, AjaxParams params, AjaxCallBack<? extends Object> callBack) public void get( String url, Header[] headers, AjaxParams params, AjaxCallBack<? extends Object> callBack) public Object getSync( String url) //同步get请求,请在子线程执行这个操作,否则非常有可能报ANR public Object getSync( String url, AjaxParams params) public Object getSync( String url, Header[] headers, AjaxParams params) //------------------post 请求----------------------- public void post(String url, AjaxCallBack<? extends Object> callBack) public void post(String url, AjaxParams params, AjaxCallBack<? extends Object> callBack) public void post( String url, HttpEntity entity, String contentType, AjaxCallBack<? extends Object> callBack) public void post( String url, Header[] headers, AjaxParams params, String contentType,AjaxCallBack<? extends Object> callBack) public void post( String url, Header[] headers, HttpEntity entity, String contentType,AjaxCallBack<? extends Object> callBack) public Object postSync(String url) //同步post请求,请在子线程执行这个操作,否则非常有可能报ANR public Object postSync(String url, AjaxParams params) public Object postSync( String url, HttpEntity entity, String contentType) public Object postSync( String url, Header[] headers, AjaxParams params, String contentType) public Object postSync( String url, Header[] headers, HttpEntity entity, String contentType) //------------------put 请求----------------------- public void put(String url, AjaxCallBack<? extends Object> callBack) public void put( String url, AjaxParams params, AjaxCallBack<? extends Object> callBack) public void put( String url, HttpEntity entity, String contentType, AjaxCallBack<? extends Object> callBack) public void put(String url,Header[] headers, HttpEntity entity, String contentType, AjaxCallBack<? extends Object> callBack) public Object putSync(String url) //同步put请求,请在子线程执行这个操作,否则非常有可能报ANR public Object putSync( String url, AjaxParams params) public Object putSync(String url, HttpEntity entity, String contentType) public Object putSync(String url,Header[] headers, HttpEntity entity, String contentType) //------------------delete 请求----------------------- public void delete( String url, AjaxCallBack<? extends Object> callBack) public void delete( String url, Header[] headers, AjaxCallBack<? extends Object> callBack) public Object deleteSync(String url) //同步delete请求,请在子线程执行这个操作,否则非常有可能报ANR public Object deleteSync( String url, Header[] headers) //---------------------下载--------------------------------------- public void download(String url,String target,AjaxCallBack<File> callback) public void download( String url,AjaxParams params, String target, AjaxCallBack<? extends Object> callback) 附送请求demo和下载demo

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值