The study of Android loading images asynchronously from the network is summarized as follows:
(1) Since the Android UI update supports a single threading principle, fetching data from the network and updating it to the interface may first be thought of in order not to block the main thread.
New handler object in main thread, loading image method as follows
private void LoadImage (final String URL, final int id) {
handler.post (new Runnable () {public
void run () {
Dra Wable drawable = null;
try {
drawable = drawable.createfromstream (new URL (URL). OpenStream (), "Image.png"),
catch (IOException e) { c7/>}
((ImageView) LazyLoadImageActivity.this.findViewById (ID)). setimagedrawable (drawable);
}
);
The disadvantage of the above method is obvious, tested, if you want to load multiple pictures, this does not achieve asynchronous loading, but wait until all the pictures are loaded to display together, because they are running in a thread.
Then, we can simply improve, to change the handler+runnable mode to Handler+thread+message mode can not be implemented simultaneously to open multiple threads?
(2) New handler object in main thread, the code is as follows:
Final Handler handler2=new Handler () {
@Override public
void Handlemessage (msg) {(
ImageView) LazyLoadImageActivity.this.findViewById (MSG.ARG1)). Setimagedrawable ((drawable) msg.obj);
}
;
The corresponding loading image code is as follows:
Using Handler+thread mode to implement multithreading asynchronous loading
private void LoadImage2 (final String URL, final int id) {
thread thread = new Thread () {
@Override public
void Run () {
drawable drawable = null;
try {
drawable = drawable.createfromstream (new URL (URL). OpenStream (), "Image.png"),
catch (IOException e) { c9/>} message
message= handler2.obtainmessage ();
MESSAGE.ARG1 = ID;
Message.obj = drawable;
Handler2.sendmessage (message);
}
;
Thread.Start ();
thread = null;
}
This makes the asynchronous load simple. Think about it, you can also optimize, such as the introduction of the thread pool, the introduction of caching, and so on, we first introduced the thread pool.
(3) Introduce the Executorservice interface, so the code can be optimized as follows:
Add in main thread: private executorservice Executorservice = Executors.newfixedthreadpool (5);
The corresponding load image method changes as follows:
Introduce a thread pool to manage multithreaded
private void LoadImage3 (final String URL, final int id) {
executorservice.submit (new Runnable () c3/>public void Run () {
try {
final drawable drawable = drawable.createfromstream (new URL (URL). OpenStream (), " Image.png ");
Handler.post (New Runnable () {public
void run () {(
ImageView) LazyLoadImageActivity.this.findViewById (ID)). Setimagedrawable (drawable);
}
);
catch (Exception e) {
throw new RuntimeException (e);}}}
);