研究了android從網路上非同步載入映像,現總結如下:
(1)由於android UI更新支援單一線程原則,所以從網路上取資料並更新到介面上,為了不阻塞主線程首先可能會想到以下方法。
在主線程中new 一個Handler對象,載入映像方法如下所示
複製代碼 代碼如下:
private void loadImage(final String url, final int id) {
handler.post(new Runnable() {
public void run() {
Drawable drawable = null;
try {
drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
} catch (IOException e) {
}
((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
}
});
}
上面這個方法缺點很顯然,經測試,如果要載入多個圖片,這並不能實現非同步載入,而是等到所有的圖片都載入完才一起顯示,因為它們都運行在一個線程中。
然後,我們可以簡單改進下,將Handler+Runnable模式改為Handler+Thread+Message模式不就能實現同時開啟多個線程嗎?
(2)在主線程中new 一個Handler對象,代碼如下:
複製代碼 代碼如下:
final Handler handler2=new Handler(){
@Override
public void handleMessage(Message msg) {
((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
}
};
對應載入映像代碼如下:
複製代碼 代碼如下:
//採用handler+Thread模式實現多線程非同步載入
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) {
}
Message message= handler2.obtainMessage() ;
message.arg1 = id;
message.obj = drawable;
handler2.sendMessage(message);
}
};
thread.start();
thread = null;
}
這樣就簡單實現了非同步載入了。細想一下,還可以最佳化的,比如引入線程池、引入緩衝等,我們先介紹線程池。
(3)引入ExecutorService介面,於是代碼可以最佳化如下:
在主線程中加入:private ExecutorService executorService = Executors.newFixedThreadPool(5);
對應載入映像方法更改如下:
複製代碼 代碼如下:
// 引入線程池來管理多線程
private void loadImage3(final String url, final int id) {
executorService.submit(new Runnable() {
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);
}
}
});
}
4)為了更方便使用我們可以將非同步載入映像方法封裝一個類,對外界只暴露一個方法即可,考慮到效率問題我們可以引入記憶體緩衝機制,做法是建立一個HashMap,其鍵(key)為載入映像url,其值(value)是映像對象Drawable。先看一下我們封裝的類
複製代碼 代碼如下:
public class AsyncImageLoader3 {
//為了加快速度,在記憶體中開啟緩衝(主要應用於重複圖片較多時,或者同一個圖片要多次被訪問,比如在ListView時來復原動)
public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
private ExecutorService executorService = Executors.newFixedThreadPool(5); //固定五個線程來執行任務
private final Handler handler=new Handler();
/**
*
* @param imageUrl 映像url地址
* @param callback 回調介面
* <a href="\"http://www.eoeandroid.com/home.php?mod=space&uid=7300\"" target="\"_blank\"">@return</a> 返回記憶體中緩衝的映像,第一次載入返回null
*/
public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
//如果緩衝過就從緩衝中取出資料
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
if (softReference.get() != null) {
return softReference.get();
}
}
//緩衝中沒有映像,則從網路上取出資料,並將取出的資料緩衝到記憶體中
executorService.submit(new Runnable() {
public void run() {
try {
final Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
handler.post(new Runnable() {
public void run() {
callback.imageLoaded(drawable);
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
return null;
}
//從網路上取資料方法
protected Drawable loadImageFromUrl(String imageUrl) {
try {
return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//對外界開放的回調介面
public interface ImageCallback {
//注意 此方法是用來設定目標對象的映像資源
public void imageLoaded(Drawable imageDrawable);
}
}
這樣封裝好後使用起來就方便多了。在主線程中首先要引入AsyncImageLoader3 對象,然後直接調用其loadDrawable方法即可,需要注意的是ImageCallback介面的imageLoaded方法是唯一可以把載入的圖 像設定到目標ImageView或其相關的組件上。
在主線程調用代碼:
先執行個體化對象 private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();
調用非同步載入方法:
複製代碼 代碼如下:
//引入線程池,並引入記憶體緩衝功能,並對外部調用封裝了介面,簡化調用過程
private void loadImage4(final String url, final int id) {
//如果緩衝過就會從緩衝中取出映像,ImageCallback介面中方法也不會被執行
Drawable cacheImage = asyncImageLoader.loadDrawable(url,new AsyncImageLoader.ImageCallback() {
//請參見實現:如果第一次載入url時下面方法會執行
public void imageLoaded(Drawable imageDrawable) {
((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
}
});
if(cacheImage!=null){
((ImageView) findViewById(id)).setImageDrawable(cacheImage);
}
}
5)同理,下面也給出採用Thread+Handler+MessageQueue+記憶體緩衝代碼,原則同(4),只是把線程池換成了Thread+Handler+MessageQueue模式而已。代碼如下:
複製代碼 代碼如下:
public class AsyncImageLoader {
//為了加快速度,加入了緩衝(主要應用於重複圖片較多時,或者同一個圖片要多次被訪問,比如在ListView時來復原動)
private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
/**
*
* @param imageUrl 映像url地址
* @param callback 回調介面
* @return 返回記憶體中緩衝的映像,第一次載入返回null
*/
public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
//如果緩衝過就從緩衝中取出資料
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
if (softReference.get() != null) {
return softReference.get();
}
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
callback.imageLoaded((Drawable) msg.obj);
}
};
new Thread() {
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
handler.sendMessage(handler.obtainMessage(0, drawable));
}
}.start();
/*
下面注釋的這段代碼是Handler的一種代替方法
*/
// new AsyncTask() {
// @Override
// protected Drawable doInBackground(Object... objects) {
// Drawable drawable = loadImageFromUrl(imageUrl);
// imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
// return drawable;
// }
//
// @Override
// protected void onPostExecute(Object o) {
// callback.imageLoaded((Drawable) o);
// }
// }.execute();
return null;
}
protected Drawable loadImageFromUrl(String imageUrl) {
try {
return Drawable.createFromStream(new URL(imageUrl).openStream(), "src");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//對外界開放的回調介面
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable);
}
}
至此,非同步載入就介紹完了,下面給出的代碼為測試用的完整代碼:
複製代碼 代碼如下:
package com.bshark.supertelphone.activity;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import com.bshark.supertelphone.R;
import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader;
import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader3;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class LazyLoadImageActivity extends Activity {
final Handler handler=new Handler();
final Handler handler2=new Handler(){
@Override
public void handleMessage(Message msg) {
((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
}
};
private ExecutorService executorService = Executors.newFixedThreadPool(5); //固定五個線程來執行任務
private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// loadImage("yun_qi_img/logo_new.gif", R.id.image1);
// loadImage("yun_qi_img/baidu_logo.gif", R.id.image2);
// loadImage("yun_qi_img/logo.gif", R.id.image3);
// loadImage("yun_qi_img/baidu_logo.gif", R.id.image4);
// loadImage("yun_qi_img/logo.gif", R.id.image5);
loadImage2("yun_qi_img/logo_new.gif", R.id.image1);
loadImage2("yun_qi_img/baidu_logo.gif", R.id.image2);
loadImage2("yun_qi_img/logo.gif", R.id.image3);
loadImage2("yun_qi_img/baidu_logo.gif", R.id.image4);
loadImage2("yun_qi_img/logo.gif", R.id.image5);
// loadImage3("yun_qi_img/logo_new.gif", R.id.image1);
// loadImage3("yun_qi_img/baidu_logo.gif", R.id.image2);
// loadImage3("yun_qi_img/logo.gif", R.id.image3);
// loadImage3("yun_qi_img/baidu_logo.gif", R.id.image4);
// loadImage3("yun_qi_img/logo.gif", R.id.image5);
// loadImage4("yun_qi_img/logo_new.gif", R.id.image1);
// loadImage4("yun_qi_img/baidu_logo.gif", R.id.image2);
// loadImage4("yun_qi_img/logo.gif", R.id.image3);
// loadImage4("yun_qi_img/baidu_logo.gif", R.id.image4);
// loadImage4("yun_qi_img/logo.gif", R.id.image5);
// loadImage5("yun_qi_img/logo_new.gif", R.id.image1);
// //為了測試緩衝而類比的網路延時
// SystemClock.sleep(2000);
// loadImage5("yun_qi_img/baidu_logo.gif", R.id.image2);
// SystemClock.sleep(2000);
// loadImage5("yun_qi_img/logo.gif", R.id.image3);
// SystemClock.sleep(2000);
// loadImage5("yun_qi_img/baidu_logo.gif", R.id.image4);
// SystemClock.sleep(2000);
// loadImage5("yun_qi_img/logo.gif", R.id.image5);
// SystemClock.sleep(2000);
// loadImage5("yun_qi_img/baidu_logo.gif", R.id.image4);
}
@Override
protected void onDestroy() {
executorService.shutdown();
super.onDestroy();
}
//線程載入映像基本原理
private void loadImage(final String url, final int id) {
handler.post(new Runnable() {
public void run() {
Drawable drawable = null;
try {
drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
} catch (IOException e) {
}
((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
}
});
}
//採用handler+Thread模式實現多線程非同步載入
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) {
}
Message message= handler2.obtainMessage() ;
message.arg1 = id;
message.obj = drawable;
handler2.sendMessage(message);
}
};
thread.start();
thread = null;
}
// 引入線程池來管理多線程
private void loadImage3(final String url, final int id) {
executorService.submit(new Runnable() {
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);
}
}
});
}
//引入線程池,並引入記憶體緩衝功能,並對外部調用封裝了介面,簡化調用過程
private void loadImage4(final String url, final int id) {
//如果緩衝過就會從緩衝中取出映像,ImageCallback介面中方法也不會被執行
Drawable cacheImage = asyncImageLoader.loadDrawable(url,new AsyncImageLoader.ImageCallback() {
//請參見實現:如果第一次載入url時下面方法會執行
public void imageLoaded(Drawable imageDrawable) {
((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
}
});
if(cacheImage!=null){
((ImageView) findViewById(id)).setImageDrawable(cacheImage);
}
}
//採用Handler+Thread+封裝外部介面
private void loadImage5(final String url, final int id) {
//如果緩衝過就會從緩衝中取出映像,ImageCallback介面中方法也不會被執行
Drawable cacheImage = asyncImageLoader3.loadDrawable(url,new AsyncImageLoader3.ImageCallback() {
//請參見實現:如果第一次載入url時下面方法會執行
public void imageLoaded(Drawable imageDrawable) {
((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
}
});
if(cacheImage!=null){
((ImageView) findViewById(id)).setImageDrawable(cacheImage);
}
}
}
xml檔案大致如下:
複製代碼 代碼如下:
<SPAN style="FONT-SIZE: 18px"><STRONG>< ?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent" >
<ImageView android:id="@+id/image1" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
<ImageView android:id="@+id/image2" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
<ImageView android:id="@+id/image3" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
<ImageView android:id="@+id/image5" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
<ImageView android:id="@+id/image4" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
< /LinearLayout></STRONG></SPAN>