In most cases, images are loaded from the network, and various loading effects are required. For example, when an image is loaded, the loading image is displayed on the image. When the image is loaded, the loading disappears, and the loading fails, the corresponding processing is performed. If the processing is not good, it will be very troublesome. The following describes a lightweight Method for loading images from the network.
Package com. jacp. util;
Import java. io. File;
Import java. io. IOException;
Import java.net. HttpURLConnection;
Import java.net. MalformedURLException;
Import java.net. URL;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android. OS. Handler;
Import android. OS. Message;
Public class Utils
{
/**
* Loading Images
* @ Param url the url of the image
* @ Param listener: callback listener
*/
Public void loadImage (final String url, final OnLoadImageListener listener)
{
If (null = url | null = listener)
{
Return;
}
Final Handler handler = new Handler ()
{
Public void handleMessage (Message msg)
{
Listener. onLoadImage (Bitmap) msg. obj, url );
}
};
// The path previously written to the local cache based on the url
String path = "";
File file = new File (path );
If (file. exists ())
{
Bitmap bm = BitmapFactory. decodeFile (path );
SendMessage (handler, bm );
Return;
}
New Thread (new Runnable ()
{
Public void run ()
{
Try
{
// Attach images to the network and add the time out Condition
URL u = new URL (url );
HttpURLConnection httpConnection = (HttpURLConnection) u. openConnection ();
If (httpConnection. getResponseCode () = HttpURLConnection. HTTP_ OK)
{
Bitmap bm = BitmapFactory. decodeStream (httpConnection. getInputStream ());
SendMessage (handler, bm );
// Cache the image at the same time...
Return;
}
// No image request
SendMessage (handler, null );
} Catch (MalformedURLException e)
{
SendMessage (handler, null );
} Catch (IOException e)
{
SendMessage (handler, null );
}
}
}). Start ();
}
/**
* Send the processed message to handler.
* @ Param handler
* @ Param bm
*/
Private void sendMessage (Handler handler, Bitmap bm)
{
Message msg = handler. obtainMessage ();
Msg. obj = bm;
Handler. sendMessage (msg );
}
/**
* Callback for image loading
*
*/
Public interface OnLoadImageListener
{
Public void onLoadImage (Bitmap bm, String imageUrl );
}
}
In this example, Handler is used, so AsyncTask is not required. AsyncTask is difficult to use and seems to have latency. In this case, you can directly set image processing in the callback, without worrying about the UI thread. As follows:
New Utils (). loadImage ("image link", new OnLoadImageListener ()
{
@ Override
Public void onLoadImage (Bitmap bm, String imageUrl)
{
If (null = bm)
{
ImageView. setImageResource (R. drawable. default_img );
}
Else
{
ImageView. setBitmapImage (bm );
}
}
});
If you have any omissions, please feel free to criticize them!
From: jacp's column