記得之前做安卓應用時都是在2.2以下的版本,如果在UI線程中進行耗時操作,比如http,socket等
會產生android.os.NetworkOnMainThreadException
如果非同步載入網狀圖片,要在非UI線程中進行。通常有以下四種方式:
1.handler+runnable方式:
在activity中定義handler,然後用handler.post(Runnable)方法,此時會在主線程中執行,如果是sdk3.0以上會阻塞UI線程,報異常
2.handler+thread+message模式:
在handler中重寫handMessage方法,載入網狀圖片的操作在thread中執行,通過handler發送訊息,在handlerMessage中更新UI
3.handler+threadpool(線程池)+message
定義一個線程池,存放5個線程,然後使用handler的post方法執行UI更新操作
4.handler+threadpool+message+softreference緩衝
先從緩衝中載入圖片,如果沒有,就從網路中載入,然後儲存到緩衝,其他步驟同3
擷取網狀圖片的相關代碼如下:
View Code
package com.allen.utils;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class Utils {
/**
* 擷取網路中圖片資源
* @param src 圖片地址
* @return drawable對象
*/
public static Drawable loadImage(String src){
URL url=null;
try {
url = new URL(src);
} catch (MalformedURLException e) {
Log.e("-Utils-->MalformedURLExcetion--", e.toString());
}
InputStream is=null;
try {
is = url.openStream();
} catch (IOException e) {
Log.e("-Utils-->IOException--", e.toString());
}
Drawable drawable=Drawable.createFromStream(is, "img");
return drawable;
}
/**
* 從網路上下載
* @param url
* @return
*/
public static Bitmap getBitMapFromUrl(String url) {
Bitmap bitmap = null;
URL u =null;
HttpURLConnection conn = null;
InputStream is = null;
try {
u = new URL(url);
conn = (HttpURLConnection)u.openConnection();
is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 從緩衝中讀取
* @param url
* @return
* @throws Exception
*/
public static Bitmap getImgFromCache(String url,Map<String,SoftReference<Bitmap>> imgCache) throws Exception {
Bitmap bitmap = null;
//從記憶體中讀取
if(imgCache.containsKey(url)) {
synchronized (imgCache) {
SoftReference<Bitmap> bitmapReference = imgCache.get(url);
if(null != bitmapReference) {
bitmap = bitmapReference.get();
}
}
} else {//從網絡中下載
bitmap = getBitMapFromUrl(url);
//將圖片儲存進記憶體中
imgCache.put(url, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
}
}
所有源碼下載:/Files/Jaylong/loadImage.zip;
當然還有其他的方式,比如使用anysctask,或者timer,timertask……