Three ways to get network pictures in Android

Source: Internet
Author: User

Getting a network picture in Android is a time-consuming operation if you get direct access to situations where the application's unresponsive (anr:application not responding) dialog box may appear. In this case, the general approach is to use the thread to implement the time-consuming operation. There are three ways to get a URL picture in the following columns:
1. Direct access: (easy: ANR, not recommended)

Mimageview = (ImageView)this = loadimagefromnetwork (image_url); Mimageview.setimagedrawable ( drawable);

Common methods:Privatedrawable loadimagefromnetwork (String imageUrl) {drawable drawable=NULL; Try {  //This can be determined by the file name here, whether the picture is locallydrawable =Drawable.createfromstream (NewURL (IMAGEURL). OpenStream (), "Image.jpg"); } Catch(IOException e) {log.d ("Test", E.getmessage ()); } if(drawable = =NULL) {LOG.D ("Test", "null drawable"); } Else{LOG.D ("Test", "NOT null drawable"); }  returndrawable;}

2. Background thread gets the URL picture:

Mimageview = (ImageView) This. Findviewbyid (r.id.imagethreadconcept);NewThread (NewRunnable () {drawable drawable=loadimagefromnetwork (image_url); @Override Public voidrun () {//post () is especially important to update the image to the main UI thread.Mimageview.post (NewRunnable () {@Override Public voidrun () {//TODO auto-generated Method Stubmimageview.setimagedrawable (drawable);  }}) ; }}). Start ();

3.AsyncTask Get URL Picture

 Mimageview = (ImageView)  new   Downloadimagetask (). Execute (image_url);  private  class  Downloadimagetask extends  asynctask<string, Void, Drawable> { protected   drawable Doinbackground (S  Tring. URLs) { return  loadimagefromnetwork (urls[0]);  protected  void   OnPostExecute (drawable result) {mimageview.setimagedrawable (result); }}

Three ways to get network pictures in Android

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.