Just reviewed the previously learned asynchronous loading pictures, so decided to write down, enhance memory
To load a picture, you must get the URL address of all pictures. The URL address of the image here exists in the list array.
There are two ways to load a picture asynchronously (I use two ways here): 1. Thread your way to load the picture, and then use handler to update the UI;2. Use Asynctask to load the picture.
1. Use a child thread to load the picture.
1 PrivateHandler Handler =NewHandler ()2 {3 @Override4 Public voidhandlemessage (Message msg) {5 if(Mimageview.gettag (). Equals (murlstring))6 {7 Mimageview.setimagebitmap (mbitmap);8 }9 }Ten }; One Public voidLoadimagebythread (ImageView ImageView,FinalString urlstring) { AMimageview =ImageView; -Murlstring =urlstring; - NewThread () { the @Override - Public voidrun () { -Mbitmap =Getbitmap (murlstring); -Message message =Message.obtain (); +Message.obj =urlstring; - handler.sendmessage (message); + } A }.start (); at}
1 PrivateBitmap Getbitmap (String urlstring)2 {3Bitmap Bitmap =NULL;4 5URL url =NULL;6HttpURLConnection httpurlconnection =NULL;7InputStream is =NULL;8 Try {9URL =NewURL (urlstring);TenHttpURLConnection =(HttpURLConnection) url.openconnection (); Oneis =Httpurlconnection.getinputstream (); ABitmap =Bitmapfactory.decodestream (IS); -}Catch(malformedurlexception e) { - e.printstacktrace (); the}Catch(IOException e) { - e.printstacktrace (); - } - finally { + Try { - is.close (); +}Catch(IOException e) { A e.printstacktrace (); at } - } - returnbitmap; -}
2. Use Asynctask to load pictures
1 Private classMyasynctaskextendsAsynctask<string, Void, bitmap>2 {3 4 protectedBitmap doinbackground (String ... params) {5 returnGetbitmap (params[0]);6 }7 8 @Override9 protected voidOnPostExecute (Bitmap Bitmap) {Ten One if(Mimageview! =NULL&& Bitmap! =NULL&&murlstring.equals (Mimageview.gettag ())) A { - Mimageview.setimagebitmap (bitmap); - Utils.addbitmaptolrucache (bitmap, murlstring); the } - } -}
3. Use memory to cache pictures
1 Private Static LongMmaxmemory =runtime.getruntime (). MaxMemory ();2 Private Static LongMapplymemory = MMAXMEMORY/10;3 Private Staticlrucache<string, bitmap> Mlrucache =NewLrucache<string, Bitmap> ((int) mapplymemory)4 {5 @Override6 protected intsizeOf (String key, Bitmap value) {7 returnValue.getbytecount ();8 }9 };Ten Public Static BooleanIsbitmapexistsinlrucache (String urlstring) One { A returnMlrucache.get (urlstring)! =NULL; - } - Public Static voidAddbitmaptolrucache (Bitmap Bitmap, String urlstring) the { - //log.i ("main", "picture size =" + bitmap.getbytecount () * 1.0f/1024/1024); - mlrucache.put (urlstring, bitmap); - } + Public StaticBitmap Getbitmaolrucache (String urlstring) - { + returnMlrucache.get (urlstring); A}
android-Loading Pictures asynchronously