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 );
}
}