編輯:關於 Android 程式設計
在 App 開發中,ListView 的非同步載入圖片能帶來流暢的使用體驗,也是衡量程式效能的重要指標。網路上相關範例不少,核心概念大同小異,但有些版本存在 bug 或效能待優化的問題。本文在理想版本的基礎上加以改良,並深入說明其中的原理。
public class LoaderAdapter extends BaseAdapter {
private static final String TAG = "LoaderAdapter";
private boolean mBusy = false;
public void setFlagBusy(boolean busy) {
this.mBusy = busy;
}
private ImageLoader mImageLoader;
private int mCount;
private Context mContext;
private String[] urlArrays;
public LoaderAdapter(int count, Context context, String[] url) {
this.mCount = count;
this.mContext = context;
urlArrays = url;
mImageLoader = new ImageLoader(context);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
@Override
public int getCount() {
return mCount;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, null);
viewHolder = new ViewHolder();
viewHolder.mTextView = (TextView) convertView.findViewById(R.id.tv_tips);
viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
String url = urlArrays[position % urlArrays.length];
viewHolder.mImageView.setImageResource(R.drawable.ic_launcher);
if (!mBusy) {
mImageLoader.DisplayImage(url, viewHolder.mImageView, false);
viewHolder.mTextView.setText("--" + position + "--IDLE ||TOUCH_SCROLL");
} else {
mImageLoader.DisplayImage(url, viewHolder.mImageView, true);
viewHolder.mTextView.setText("--" + position + "--FLING");
}
return convertView;
}
static class ViewHolder {
TextView mTextView;
ImageView mImageView;
}
}
public class ImageLoader {
private MemoryCache memoryCache = new MemoryCache();
private AbstractFileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
// 執行緒池
private ExecutorService executorService;
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
// 最主要的方法
public void DisplayImage(String url, ImageView imageView, boolean isLoadOnlyFromCache) {
imageViews.put(imageView, url);
// 先從記憶體快取中查找
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else if (!isLoadOnlyFromCache) {
// 若沒有的話則開啟新執行緒載入圖片
queuePhoto(url, imageView);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// 先從檔案快取中查找是否有
Bitmap b = null;
if (f != null && f.exists()) {
b = decodeFile(f);
}
if (b != null) {
return b;
}
// 最後從指定的 url 下載圖片
try {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
Bitmap bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
Log.e("", "getBitmap catch Exception...\nmessage = " + ex.getMessage());
return null;
}
}
// decode 這個圖片並按比例縮放以減少記憶體消耗
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_SIZE = 100;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
// 更新的操作放在 UI 執行緒中
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
// 防止圖片錯位
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// 用於在 UI 執行緒中更新界面
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
Log.e("", "CopyStream catch Exception...");
}
}
}
優化一:子執行緒讀取。先從記憶體載入,沒有則開啟執行緒從 SD 卡或網路取得。從 SD 卡讀取放在子執行緒中執行,否則快速滑動時畫面會卡頓。
優化二:滑動時只讀記憶體。Adapter 中的 busy 變數代表 ListView 是否處於滑動狀態。若是滑動中,就只從記憶體取圖,不再額外開啟執行緒去讀外部儲存或網路。
優化三:先落盤再載入。從網路取得圖片時先存到 SD 卡,再載入記憶體。這樣做的優點是載入時能做壓縮處理,減少佔用的記憶體。此外,ImageLoader 使用執行緒池,避免頻繁建立與銷毀執行緒(每次 new 一個執行緒是很不可取的寫法,即使 AsyncTask 內部其實也用到了執行緒池)。
錯位的根源在於 ListView 複用了 convertView。舉例來說,一屏顯示九個項目,當拉出第十個項目時,它其實重複使用了第一個項目;而當第一個項目的圖片才剛從網路下載完準備顯示時,該項目可能早已滾出可視範圍,於是圖片就被錯誤地貼到了第十個項目上。
解法是「可見則顯示,不可見則不顯示」。ImageLoader 中的 imageViews 這個 Map 就是用來記錄當前可視區域圖片對應的 URL,顯示前先比對一下即可。
public class MemoryCache {
private static final String TAG = "MemoryCache";
// 最後一個參數 true 代表依最近使用次數由少到多排列,即 LRU
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
private long size = 0; // 目前佔用的位元組
private long limit = 1000000; // 最大可佔用的堆記憶體
public MemoryCache() {
// 使用可用堆大小的比例
setLimit(Runtime.getRuntime().maxMemory() / 10);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
// 嚴格控制堆記憶體,超過時優先移除最近最少使用的那張圖片
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
cache.clear();
}
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
這裡用 LinkedHashMap 實作 LRU:每次加入圖片就檢查是否超過上限,超過便從「最近最少使用」的一端移除,直到符合限制為止。這種做法能最大化利用記憶體中的圖片快取,避免重複產生垃圾加重 GC 負擔——OOM 往往就是因為瞬間記憶體暴增、回收不及時所造成。
相對於早期常用的軟引用(SoftReference),LinkedHashMap 的圖片在未被移除前不會被 GC 回收,因此命中率更高。若想更進一步,可以把兩者結合形成二級快取:從 LinkedHashMap 移出的圖片再放進 SoftReference 中,兼顧命中率與彈性,有興趣的讀者不妨一試。
Android TagFlowLayout 標籤布局完全解析
FlowLayout 適合排列標籤,但在商品選擇、搜尋關鍵字等互動場景中,還需要處理選取、回呼與狀態保存。TagFlowLayout 在 FlowLayout 基礎上加入
Android View 體系(一):視圖坐標系完全解析
前言 Android 的 View 體系是介面程式設計的核心,其重要性不亞於四大元件。這個系列會依序談到 View 坐標系、View 的滑動、View 的事件分發等主題,
Android View 繪製流程解析:measure、layout 與 draw
Android 的 View 繪製流程可以概括為 measure、layout 與 draw 三個階段。當 Activity 取得焦點後,系統會從根節點開始,對整棵 Vi
Android APK 反編譯詳解:取得 Java 原始碼
在此鄭重聲明,貼出這篇文章的目的不是為了破解他人軟體,而是抱持一種學習的態度;不過透過這種方式,確實也能用來漢化一些國外軟體。 準備工具 要反編譯 APK 取得 Jav