Android learning notes ---- asynchronous image loading

Source: Internet
Author: User

Image downloading is a time-consuming process when developing network applications. Thanks to the good asynchronous download experience, it is our first choice to asynchronously load network images.

I have read some information on the Internet and found that some people have shared their experience in this area. After learning, the younger brother has made some optimizations based on them. Let's take a look at the implementation process of asynchronous loading.

In asynchronous loading, the background thread is used to download images. After the download is completed, the images are displayed on the UI. So should we open a thread for each image? What if I want to load one hundred images? It would be too wasteful to do so, so we thought of the thread pool! The thread pool can maximize resource utilization by repeatedly scheduling existing threads. We can obtain such a thread pool through executors. newfixedthreadpool (); and then use it to manage download threads.

Of course, we are lucky that android provides us with a simpler way!

We know that android provides a very useful asynchronous task-asynctask. by viewing the source code of asynctask, we can see the following line of code:

private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,            MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);

Core_pool_size limits the number of running threads.

This shows that the internal implementation of asynctask is to schedule through the thread pool. Using this feature, combined with the above ideas, we can use asynctask to implement the asynchronous loading function for us. For more information about the implementation, see the Code. For the convenience of extension and use, I encapsulated the asynchronous download function into the custom component remoteimageview. The Code is as follows:

Public class remoteimageview extends imageview {public static hashmap <string, bitmap> imagecache = new hashmap <string, bitmap> (); // 1. as a cache, there are other better implementations: Private Static final int max_fail_time = 5; private int mfails = 0; private string murl; Public remoteimageview (context, attributeset attrs) {super (context, attrs);} public void setdefaultimage (INT resid) {This. setimageresource (resid);} publi C void setimageurl (string URL) {If (murl! = NULL & murl. equals (URL) {mfails ++;} else {mfails = 0; murl = URL;} If (mfails> = max_fail_time) return; murl = URL; if (iscached (URL) return; startdownload (URL);} public Boolean iscached (string URL) {If (imagecache. containskey (URL) {This. setimagebitmap (imagecache. get (URL); Return true;} return false;} private void startdownload (string URL) {try {New downloadtask(cmd.exe cute (URL);} catch (reje Ctedexecutionexception e) {// 2. capturing rejectedexecutionexception while loading too many images, causing program crash} private void redownload (string URL) {setimageurl (URL);} class downloadtask extends asynctask <string, void, string> {private string imageurl; @ override protected string doinbackground (string... params) {imageurl = Params [0]; inputstream is = NULL; bitmap BMP = NULL; try {URL url = new URL (imageurl); is = URL. openstr EAM (); BMP = bitmapfactory. decodestream (is); If (BMP! = NULL) {imagecache. put (imageurl, BMP);} else {redownload (imageurl) ;}} catch (malformedurlexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} finally {If (is! = NULL) {try {is. close ();} catch (ioexception e) {// todo auto-generated Catch Block E. printstacktrace () ;}}return imageurl;} @ override protected void onpostexecute (string result) {bitmap BMP = NULL; If (imagecache. containskey (result) {BMP = imagecache. get (result); remoteimageview. this. setimagebitmap (BMP);} else {redownload (imageurl);} super. onpostexecute (result );}}}

Here I will mainly explain the two Annotations:

1. Because image resources consume a lot of traffic, we need to cache them after downloading them locally. There are many cache methods, among which the following are welcome: (1) softreference is used for temporary storage. softreference is optimized for memory, which is a good method. (2) external storage space stored through files.

2. Because the thread pool has a limit on the number of threads, when there are too many images loaded, A rejectedexecutionexception will be thrown.

In this way, we can use remoteimageview to asynchronously load images. If you have any errors, please correct them ~~~~

Below is a demo project source code: http://download.csdn.net/download/chenshaoyang0011/4428075

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.