android加载网络gif图片

支持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

 

posted on 2015-12-25 15:29  3A87  阅读(3537)  评论(0编辑  收藏  举报

导航