android載入網路gif圖片

來源:互聯網
上載者:User

標籤:

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

如果gif是網狀圖片,這個庫不支援直接載入一個url,但是提供了一個GifDrawable 類,可以通過檔案,輸入資料流等方式建立GifDrawable,

所以可以先下載下來或者獲得輸入資料流,通過建立drawable載入。下面例舉兩種方法:

1、下載到sd卡,再載入

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();                }            }        });

2、獲得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.java

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

 

android載入網路gif圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.