博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android加载网络gif图片
阅读量:5817 次
发布时间:2019-06-18

本文共 6736 字,大约阅读时间需要 22 分钟。

支持gif的imageview,使用github上的开源框架,项目地址

如果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

 

转载于:https://www.cnblogs.com/3A87/p/5076090.html

你可能感兴趣的文章
SQL0101N 语句太长或者太复杂。SQLSTATE=54001 或 应用程序堆中没有足够的存储量可用来处理语句。SQLSTATUS=57011...
查看>>
Ubuntu 网站服务器环境搭建
查看>>
这个是我们公司的面试题。 特此共享
查看>>
Ubuntu Docker 简单安装 GitLab
查看>>
Ubuntu 16.04调节屏幕显示字体大小
查看>>
DNS Tunnel判定方法
查看>>
在MFC中使用SDL2.0(SDL窗口嵌入到MFC中)
查看>>
SQLSERVER SQL性能优化技巧
查看>>
BroadcastReceiver register 广播的动态注册方式
查看>>
Qt & VS2013 报错:There's no Qt version assigned to this project for platform Win32
查看>>
理解及快速测定 Azure 虚拟机的磁盘性能
查看>>
按名字寻找文件和文件夹 find命令
查看>>
Scanner的概述与String类的构造和使用_DAY12
查看>>
浅谈 Mybatis中的 ${ } 和 #{ }的区别
查看>>
Linq基础知识小记三
查看>>
mysql实现随机获取几条数据的方法
查看>>
Android通过Chrome Inspect调试WebView的H5 App出现空白页面的解决方法(不需要FQ)
查看>>
MySQL参数log_bin_trust_function_creators介绍
查看>>
(九)假设检验
查看>>
nginx URL重写
查看>>