Three methods for obtaining network images in Android

Source: Internet
Author: User

Obtaining Network images in Android is a time-consuming operation. If you obtain images directly, an application may occur.ProgramNo response (ANR: application not responding) dialog box. In this case, the general method is to use threads for time-consuming operations. The following three methods are used to obtain URL images:
1. directly obtain: (easy: ANR, not recommended)

Mimageview = (imageview) This. findviewbyid (R. Id. imagethreadconcept );
Drawable = loadimagefromnetwork (image_url );
Mimageview. setimagedrawable (drawable );

Public method:

Private drawable loadimagefromnetwork (string imageurl)
{
Drawable = NULL;
Try {
// You can use the file name to determine whether the image exists locally.
Drawable = drawable. createfromstream (
New URL (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 ");
}

Return drawable;
}

2. The background thread obtains the URL image:

Mimageview = (imageview) This. findviewbyid (R. Id. imagethreadconcept );
New thread (New runnable (){
Drawable = loadimagefromnetwork (image_url );
@ Override
Public void run (){

// The Key to post () is to update the image in the main UI thread.
Mimageview. Post (New runnable (){
@ Override
Public void run (){
// Todo auto-generated method stub
Mimageview. setimagedrawable (drawable );
}});
}

}). Start ();

3. asynctask

Mimageview = (imageview) This. findviewbyid (R. Id. imagethreadconcept );
New downloadimagetask(cmd.exe cute (image_url );
Private class downloadimagetask extends asynctask <string, void, drawable>
{

Protected drawable doinbackground (string... URLs ){
Return loadimagefromnetwork (URLs [0]);
}

Protected void onpostexecute (drawable result ){
Mimageview. setimagedrawable (result );
}
}

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.