Android Load Network GIF pictures

Source: Internet
Author: User
Tags sendmsg

GIF-enabled ImageView, using the open source framework on GitHub, project address https://github.com/koral--/android-gif-drawable

If GIF is a network image, this library does not support loading a URL directly, but provides a gifdrawable class that can create gifdrawable through files, input streams, and so on .

So you can download it first or get the input stream by creating a drawable load. The following examples illustrate two methods:

1. Download to SD card, then load

Downloadutils.java
 Public classDownloadutils {Private Final intDown_start = 1;//Handler message type (start download)    Private Final intDown_position = 2;//handler message type (download location)    Private Final intDown_complete = 3;//handler message type (download complete)    Private Final intDown_error = 4;//handler message type (download failed)    PrivateOndownloadlistener Ondownloadlistener;  Public voidSetondownloadlistener (Ondownloadlistener ondownloadlistener) { This. Ondownloadlistener =Ondownloadlistener; }    /*** Download File * *@paramURL file path *@paramfilepath Save Address*/     Public voidDownload (string URL, string filepath) {myrunnable Mr=Newmyrunnable (); Mr.url=URL; Mr.filepath=filepath; NewThread (MR). Start (); } @SuppressWarnings ("Unused")    Private voidSendmsg (intWhat ) {sendmsg (What,NULL); }    Private voidSendmsg (intWhat , Object mess) {Message m=Myhandler.obtainmessage (); M.what=what ; M.obj=mess;    M.sendtotarget (); } Handler MyHandler=NewHandler () { Public voidhandlemessage (Message msg) {Switch(msg.what) { CaseDown_start://Start Download                    intFileSize =(Integer) msg.obj;                    Ondownloadlistener.ondownloadconnect (filesize);  Break;  CaseDown_position://Download Location                    intpos =(Integer) msg.obj;                    Ondownloadlistener.ondownloadupdate (POS);  Break;  CaseDown_complete://Download CompleteString URL =(String) msg.obj;                    Ondownloadlistener.ondownloadcomplete (URL);  Break;  CaseDown_error://Download FailedException e =(Exception) msg.obj;                    E.printstacktrace ();                    Ondownloadlistener.ondownloaderror (e);  Break; }            Super. Handlemessage (msg);    }    }; classMyrunnableImplementsRunnable {PrivateString url = ""; PrivateString filepath = ""; @Override Public voidrun () {Try{dodownloadthefile (URL, filepath); } Catch(Exception e) {sendmsg (Down_error, E); }        }    }    /*** Download File * *@paramURL Download Path *@paramfilepath Save path *@throwsException*/    Private voidDodownloadthefile (string URL, string filepath)throwsException {if(!urlutil.isnetworkurl (URL)) {sendmsg (Down_error,NewException ("not valid:" +URL)); return; } URL Myurl=Newurl (URL); URLConnection Conn=myurl.openconnection ();        Conn.connect (); InputStream is=NULL; intFileSize = 0; Try{ is=Conn.getinputstream (); FileSize= Conn.getcontentlength ();//get file size based on responsesendmsg (Down_start, filesize); } Catch(Exception e) {sendmsg (Down_error,NewException (NewException ("Cannot get File"))); return; } FileOutputStream Fos=NewFileOutputStream (filepath);//creates a write-to-file memory stream,//write a file with this flow to target        byteBuf[] =New byte[1024]; intNumread = 0; inttemp = 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

Download monitoring in Activity settings

Downloadutils downloadutils =Newdownloadutils (); Downloadutils.download ("Http://img15.3lian.com/2015/gif/1/78/1.gif", Getapppath () + "/1.gif"); Downloadutils.setondownloadlistener (NewOndownloadlistener () {@Override Public voidOndownloadupdate (intpercent) {} @Override Public voidOndownloaderror (Exception e) {} @Override Public voidOndownloadconnect (intfilesize) {} @Override Public voidondownloadcomplete (Object result) {Try{gifdrawable gifdrawable=NewGifdrawable (Getapppath () + "/1.gif");                Gifimageview.setbackgrounddrawable (gifdrawable); } Catch(IOException e) {e.printstacktrace (); }            }        });

2. Get byte [] type stream, create drawable, use network request frame Commons-httpclient-3.0.1.jar

Loadgifutils loadgifutils =Newloadgifutils (); Loadgifutils.setlistener (NewLoadgifutils.oncompltedlistener () {@Override Public voidOncomplted (byte[] bt) {                Try{gifdrawable drawable=Newgifdrawable (BT);                Gifimageview.setbackgrounddrawable (drawable); } Catch(IOException e) {e.printstacktrace ();        }            }        }); Loadgifutils.loadgif ("Http://img15.3lian.com/2015/gif/1/78/1.gif");

Loadgifutils.java

 Public classLoadgifutils {PrivateOncompltedlistener Listener;  Public voidloadgif (String url) {myrunnable myrunnable=Newmyrunnable (URL); NewThread (myrunnable). Start (); }    classMyrunnableImplementsRunnable {String URL; myrunnable (String URL) { This. url =URL; } @Override Public voidrun () {byte[] bt=New byte[1024]; Try{HttpClient Client=NewHttpClient (); GetMethod Get=Newgetmethod (URL);                Client.executemethod (get); BT=Get.getresponsebody (); Sendmsg (1, BT); } Catch(Throwable ex) {System.out.println (ex.tostring ()); }        }    }    Private voidSendmsg (intWhat , Object mess) {Message m=Handler.obtainmessage (); M.what=what ; M.obj=mess;    M.sendtotarget (); } Handler Handler=NewHandler () {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Case1://Start Download                    byte[] bt = (byte[]) msg.obj; if(listener!=NULL) {listener.oncomplted (BT); }                     Break; }            Super. Handlemessage (msg);    }    }; InterfaceOncompltedlistener {voidOncomplted (byte[] bt); }    voidSetlistener (Oncompltedlistener listener) { This. listener=Listener; }}
View Code

Android Load Network GIF pictures

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.