編輯:關於 Android 程式設計
Android 生態爆發之後,自定義控制項與第三方框架大量湧現。回想 2011 年前後,專案裡的 UI 幾乎全靠系統原生控制項,動畫與版面都很樸素,網路請求一律用 HttpClient,圖片則是「下載完再顯示」——當時的開源資源遠不如現在豐富。
從工程角度看,App 架構恆久不變的兩大支柱是:網路通訊框架與圖片載入框架。通訊部分已有 async-http、okhttp 等選擇,而 Volley 則同時涵蓋兩者,不少人為了省事整套採用;Facebook 的 Fresco 同樣自帶網路與圖片能力,品質相當不錯。
public class ImageDownloader {
private static ImageDownloader instance = null;
private static File cacheDir;
public static Map<String, SoftReference<Bitmap>> bitMapCache = new HashMap<>();
public static ImageDownloader getInstance() {
if (instance == null) {
instance = new ImageDownloader();
}
return instance;
}
private ImageDownloader() {
// 決定快取目錄:優先外部儲存,其次應用私有目錄
if (android.os.Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "WholeMag");
} else {
cacheDir = WholeMagApplication.getInstance().getCacheDir();
}
if (!cacheDir.exists()) { cacheDir.mkdirs(); }
}
public void download(String actName, String url, ImageView imageView) {
new BitmapDownloaderTask(imageView, actName).execute(url);
}
class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference; // 用弱引用避免記憶體洩漏
private String actName;
BitmapDownloaderTask(ImageView imageView, String actName) {
imageViewReference = new WeakReference<ImageView>(imageView);
this.actName = actName;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap rebmp = getLocalBitmap(params[0], actName);
if (rebmp == null) { rebmp = downloadBitmap(params[0], actName); }
return rebmp;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled() || bitmap == null) { return; }
ImageView imageView = imageViewReference.get();
if (imageView == null) { return; }
// 依裝置寬度等比放大,並加上淡入動畫
double widthX = (float) WholeMagDatas.getDeviceWidth() / bitmap.getWidth();
int bitmapHight = bitmap.getHeight();
imageView.setImageBitmap(bitmap);
if (actName.equals(AppData.NEWS_DETAIL_ACT)) {
imageView.setLayoutParams(new FrameLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.FILL_PARENT,
(int) (bitmapHight * widthX), Gravity.CENTER));
}
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(500);
imageView.startAnimation(alphaAnimation);
}
}
/** 先讀本地快取 */
static Bitmap getLocalBitmap(String url, String actName) {
if (bitMapCache.containsKey(url)) {
return bitMapCache.get(url).get();
}
File f = Tools.getFile(actName, url);
InputStream inputStream = null;
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inPreferredConfig = Bitmap.Config.RGB_565; // 每像素 2 位元組,省一半記憶體
o.inDither = false;
o.inPurgeable = true;
inputStream = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, o);
bitMapCache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (Exception e) {
// 忽略,回傳 null 交由上層重試
} finally {
if (inputStream != null) {
try { inputStream.close(); } catch (Exception ex) { }
}
}
return null;
}
/** 從網路下載並落地 */
static Bitmap downloadBitmap(String url, String actName) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("linux");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) { return null; }
File f = Tools.getFile(actName, url);
OutputStream os = new FileOutputStream(f);
InputStream inputStream = null;
try {
inputStream = entity.getContent();
BitmapFactory.Options o = new BitmapFactory.Options();
o.inPreferredConfig = Bitmap.Config.RGB_565;
o.inDither = false;
o.inPurgeable = true;
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, o);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
bitMapCache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} finally {
if (inputStream != null) { inputStream.close(); }
if (os != null) { os.close(); }
entity.consumeContent();
}
} catch (Exception e) {
getRequest.abort();
} finally {
if (client != null) { client.close(); }
}
return null;
}
}
當時為了避免圖片把記憶體撐爆而 OOM,快取一律使用軟引用(SoftReference),效果還算不錯。歸納起來,圖片載入的基本原理就是:把 url 與 ImageView 配對拋進背景執行緒,下載 byte 流後 decode 成 Bitmap,最後切回 UI 執行緒設定到 ImageView 上。
這版實作的不足也很明顯:只做應用層快取、沒有標準化的磁碟快取策略;沒有依目標尺寸做 decode 縮放,也沒有統一設定色彩格式,記憶體使用不夠精緻。後來的 LruCache 思路與此類似,但多了「限制快取總容量」與「依使用頻率淘汰」兩項關鍵設計,並把記憶體層與 SD 卡層各自封裝。
把開源 universal-image-loader 的 ImageLoaderConfiguration 攤開來看,就能理解一個完整框架要照顧多少細節:
public final class ImageLoaderConfiguration {
final Resources resources; // 計算圖片尺寸時需要螢幕寬高
final int maxImageWidthForMemoryCache; // 記憶體快取允許的最大寬
final int maxImageHeightForMemoryCache; // 記憶體快取允許的最大高
final int maxImageWidthForDiskCache; // 磁碟快取允許的最大寬
final int maxImageHeightForDiskCache; // 磁碟快取允許的最大高
final BitmapProcessor processorForDiskCache; // 從磁碟讀出的後處理器
final Executor taskExecutor; // 載入圖片的執行緒池
final Executor taskExecutorForCachedImages; // 載入快取圖片的執行緒池
final boolean customExecutor; // 是否自訂執行緒池
final boolean customExecutorForCachedImages;
final int threadPoolSize; // 核心線程數,可控制當前頁面的併發載入量
final int threadPriority; // 線程優先級
final QueueProcessingType tasksProcessingType; // LIFO 或 FIFO
final MemoryCache memoryCache; // 記憶體快取實作
final DiskCache diskCache; // 磁碟快取實作
final ImageDownloader downloader; // 依 http/file/content/drawable/asset 分派
final ImageDecoder decoder; // 把位元組解析成 Bitmap
final DisplayImageOptions defaultDisplayImageOptions;
final ImageDownloader networkDeniedDownloader; // 僅離線載入(等同讀 SD 卡)
final ImageDownloader slowNetworkDownloader; // 慢網路最佳化
}
而每一次載入的行為,則由 DisplayImageOptions 決定:
public final class DisplayImageOptions {
private final int imageResOnLoading; // 載入中的佔位圖資源
private final int imageResForEmptyUri; // url 為空時的圖
private final int imageResOnFail; // 載入失敗時的圖
private final Drawable imageOnLoading;
private final Drawable imageForEmptyUri;
private final Drawable imageOnFail;
private final boolean resetViewBeforeLoading; // 載入前是否重置(放棄舊請求)
private final boolean cacheInMemory; // 是否記憶體快取
private final boolean cacheOnDisk; // 是否磁碟快取
private final ImageScaleType imageScaleType; // 縮放策略
private final Options decodingOptions; // BitmapFactory.Options
private final int delayBeforeLoading; // 延遲載入,適合非當前頁
private final boolean considerExifParams; // 是否套用 EXIF 旋轉/翻轉
private final Object extraForDownloader; // 傳給下載器的額外參數
private final BitmapProcessor preProcessor; // 快取未命中時的前處理
private final BitmapProcessor postProcessor; // 快取命中時的後處理
private final BitmapDisplayer displayer; // 顯示動畫
private final Handler handler; // 與主線程溝通
private final boolean isSyncLoading; // 是否同步載入
}
此外它還支援以像素為單位指定佔位尺寸,讓框架在 decode 階段就能縮放到目標大小,避免把大圖整個讀進記憶體。
這些框架大多誕生於 universal-image-loader 之後,因此設計上多少受其影響。就原創性而言,真正跳脫既有框架思維的主要是 Fresco(分階段管線與自訂 Drawee)與 Glide(生命週期感知)。
如果是新專案,清單型畫面多、追求輕量與生命週期自動管理,Glide 通常是首選;需要圓形頭像、漸進式載入、GIF 與高度自訂顯示效果,Fresco 更合適;只是想快速塞圖片且團隊已熟悉,Picasso 足夠。若專案仍需維護舊版程式碼,則先確認目前使用的 API 是否已被標記為棄用(例如 Picasso.with() 已改為 Picasso.get()),再評估遷移成本。
RecyclerView 下拉刷新與上拉加載實戰(一):從事件分發開始解決頭尾布局難題
之前寫過 ListView 的下拉刷新與上拉加載,最近一直在琢磨 RecyclerView 該怎麼做。原因很簡單:RecyclerView 的用量越來越大,遲早要換過去。
Android 自訂 Dialog 樣式與進度更新實作
客製化 Dialog 常用於提示、載入或進度回饋。下圖為本文要呈現的效果。 核心思路 自訂 Dialog 繼承 android.app.Dialog,透過建構子傳入 l
打造通用的 Android ListView、GridView 適配器
1、簡述 在 Android 開發中,與 adapter 打交道幾乎無可避免。一般做法是繼承 BaseAdapter、重寫其中幾個方法,然後一個 ListView 對應一
Android 的 AdapterViewFlipper 與 StackView 詳解
AdapterViewFlipper 簡介 AdapterViewFlipper 繼承自 AdapterViewAnimator,每次只顯示一個子組件,通過 showPr