android加載網絡gif圖片

支持gif的imageview,使用github上的開源框架,項目地址https://github.com/koral--/android-gif-drawablejava

若是gif是網絡圖片,這個庫不支持直接加載一個url,可是提供了一個GifDrawable 類,能夠經過文件,輸入流等方式建立GifDrawable,android

因此能夠先下載下來或者得到輸入流,經過建立drawable加載。下面例舉兩種方法:git

一、下載到sd卡,再加載github

DownloadUtils.java
public class DownloadUtils {
    private final int DOWN_START = 1; // Handler消息類型(開始下載)
    private final int DOWN_POSITION = 2; // Handler消息類型(下載位置)
    private final int DOWN_COMPLETE = 3; // Handler消息類型(下載完成)
    private final int DOWN_ERROR = 4; // Handler消息類型(下載失敗)
    private OnDownloadListener onDownloadListener;

    public void setOnDownloadListener(OnDownloadListener onDownloadListener) {
        this.onDownloadListener = onDownloadListener;
    }

    /**
     * 下載文件
     *
     * @param url      文件路徑
     * @param filepath 保存地址
     */
    public void download(String url, String filepath) {
        MyRunnable mr = new MyRunnable();
        mr.url = url;
        mr.filepath = filepath;
        new Thread(mr).start();
    }

    @SuppressWarnings("unused")
    private void sendMsg(int what) {
        sendMsg(what, null);
    }

    private void sendMsg(int what, Object mess) {
        Message m = myHandler.obtainMessage();
        m.what = what;
        m.obj = mess;
        m.sendToTarget();
    }

    Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_START: // 開始下載
                    int filesize = (Integer) msg.obj;
                    onDownloadListener.onDownloadConnect(filesize);
                    break;
                case DOWN_POSITION: // 下載位置
                    int pos = (Integer) msg.obj;
                    onDownloadListener.onDownloadUpdate(pos);
                    break;
                case DOWN_COMPLETE: // 下載完成
                    String url = (String) msg.obj;
                    onDownloadListener.onDownloadComplete(url);
                    break;
                case DOWN_ERROR: // 下載失敗
                    Exception e = (Exception) msg.obj;
                    e.printStackTrace();
                    onDownloadListener.onDownloadError(e);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    class MyRunnable implements Runnable {
        private String url = "";
        private String filepath = "";

        @Override
        public void run() {
            try {
                doDownloadTheFile(url, filepath);
            } catch (Exception e) {
                sendMsg(DOWN_ERROR, e);
            }
        }
    }

    /**
     * 下載文件
     *
     * @param url      下載路勁
     * @param filepath 保存路徑
     * @throws Exception
     */
    private void doDownloadTheFile(String url, String filepath) throws Exception {
        if (!URLUtil.isNetworkUrl(url)) {
            sendMsg(DOWN_ERROR, new Exception("不是有效的下載地址:" + url));
            return;
        }
        URL myUrl = new URL(url);
        URLConnection conn = myUrl.openConnection();
        conn.connect();
        InputStream is = null;
        int filesize = 0;
        try {
            is = conn.getInputStream();
            filesize = conn.getContentLength();// 根據響應獲取文件大小
            sendMsg(DOWN_START, filesize);
        } catch (Exception e) {
            sendMsg(DOWN_ERROR, new Exception(new Exception("沒法獲取文件")));
            return;
        }
        FileOutputStream fos = new FileOutputStream(filepath); // 建立寫入文件內存流,
        // 經過此流向目標寫文件
        byte buf[] = new byte[1024];
        int numread = 0;
        int temp = 0;
        while ((numread = is.read(buf)) != -1) {
            fos.write(buf, 0, numread);
            fos.flush();
            temp += numread;
            sendMsg(DOWN_POSITION, temp);
        }
        is.close();
        fos.close();
        sendMsg(DOWN_COMPLETE, filepath);
    }
}
View Code

在activity設置下載監聽網絡

DownloadUtils downloadUtils = new DownloadUtils();
        downloadUtils.download("http://img15.3lian.com/2015/gif/1/78/1.gif", getAppPath()+"/1.gif");

        downloadUtils.setOnDownloadListener(new OnDownloadListener() {
            @Override
            public void onDownloadUpdate(int percent) {

            }

            @Override
            public void onDownloadError(Exception e) {

            }

            @Override
            public void onDownloadConnect(int filesize) {

            }

            @Override
            public void onDownloadComplete(Object result) {
                try {
                    GifDrawable gifDrawable = new GifDrawable(getAppPath()+"/1.gif");
                    gifImageView.setBackgroundDrawable(gifDrawable);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

二、得到byte []類型字節流,建立drawable,使用了網絡請求框架commons-httpclient-3.0.1.jar框架

LoadGifUtils loadGifUtils = new LoadGifUtils();
        loadGifUtils.setListener(new LoadGifUtils.onCompltedListener() {
            @Override
            public void onComplted(byte[] bt) {
                try {
                    GifDrawable drawable = new GifDrawable(bt);
                    gifImageView.setBackgroundDrawable(drawable);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        loadGifUtils.loadGif("http://img15.3lian.com/2015/gif/1/78/1.gif");

LoadGifUtils.javaide

public class LoadGifUtils {
    private onCompltedListener listener;

    public void loadGif(String url) {
        MyRunnable myRunnable = new MyRunnable(url);
        new Thread(myRunnable).start();
    }

    class MyRunnable implements Runnable {
        String url;
        MyRunnable(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            byte[] bt=new byte[1024];
            try {
                HttpClient client = new HttpClient();
                GetMethod get = new GetMethod(url);
                client.executeMethod(get);
                bt = get.getResponseBody();

                sendMsg(1,bt);
            } catch (Throwable ex) {
                System.out.println(ex.toString());
            }
        }
    }
    private void sendMsg(int what, Object mess) {
        Message m = handler.obtainMessage();
        m.what = what;
        m.obj = mess;
        m.sendToTarget();
    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: // 開始下載
                    byte[] bt = (byte[]) msg.obj;
                    if(listener!=null) {
                        listener.onComplted(bt);
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    interface onCompltedListener {
        void onComplted(byte[] bt);
    }

    void setListener(onCompltedListener listener){
        this.listener=listener;
    }
}
View Code
相關文章
相關標籤/搜索