編輯:關於 Android 程式設計
資訊類 App 幾乎一定要從網路載入大量圖片。若要兼顧速度、流量與流暢度,標準做法是「二級緩存 + 異步載入」:先找記憶體,再找本機檔案,最後才走網路。
一級緩存(記憶體)本質上是一個以圖片網址為 key、Bitmap 為 value 的 Map。由於直接持有 Bitmap 容易造成堆記憶體洩漏、管理也較複雜,實務上常借助第三方元件;有經驗者也可以自己實作,這裡選擇自行撰寫以便清楚呈現原理。二級緩存(檔案)則相對單純,自行封裝即可。
這裡有兩個值得注意的設計:使用 SoftReference 包裝 Bitmap,讓記憶體吃緊時能被 GC 回收;以及用 LinkedHashMap 覆寫 removeEldestEntry(),實作出「超過 30 張就淘汰最舊項目」的 LRU 行為。
public class MemoryCache {
// 最大的緩存數
private static final int MAX_CACHE_CAPACITY = 30;
// 用 Map 軟引用的 Bitmap 對象,保證內存空間足夠情況下不會被垃圾回收
private HashMap<String, SoftReference<Bitmap>> mCacheMap =
new LinkedHashMap<String, SoftReference<Bitmap>>() {
private static final long serialVersionUID = 1L;
// 當緩存數量超過規定大小(返回 true)會清除最早放入緩存的
protected boolean removeEldestEntry(Map.Entry<String, SoftReference<Bitmap>> eldest){
return size() > MAX_CACHE_CAPACITY;
}
};
/**
* 從緩存裡取出圖片
* @param id
* @return 如果緩存有,並且該圖片沒被釋放,則返回該圖片,否則返回 null
*/
public Bitmap get(String id){
if(!mCacheMap.containsKey(id)) return null;
SoftReference<Bitmap> ref = mCacheMap.get(id);
return ref.get();
}
/**
* 將圖片加入緩存
*/
public void put(String id, Bitmap bitmap){
mCacheMap.put(id, new SoftReference<Bitmap>(bitmap));
}
/**
* 清除所有緩存
*/
public void clear() {
try {
for(Map.Entry<String, SoftReference<Bitmap>> entry : mCacheMap.entrySet()) {
SoftReference<Bitmap> sr = entry.getValue();
if(null != sr) {
Bitmap bmp = sr.get();
if(null != bmp) bmp.recycle();
}
}
mCacheMap.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
}
把圖片以網址編碼後的檔名存到本機。這裡有兩個實用細節:有 SD 卡時優先使用外部儲存,沒有時退回 context.getCacheDir();以及用 URLEncoder.encode() 處理網址,避免中文或特殊字元造成檔案路徑錯誤。
public class FileCache {
// 緩存文件目錄
private File mCacheDir;
/**
* 創建緩存文件目錄,如果有 SD 卡,則使用 SD,如果沒有則使用系統自帶緩存目錄
* @param context
* @param cacheDir 圖片緩存的一級目錄
* @param dir
*/
public FileCache(Context context, File cacheDir, String dir){
if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
mCacheDir = new File(cacheDir, dir);
else
mCacheDir = context.getCacheDir(); // 獲取系統內置的緩存存儲路徑
if(!mCacheDir.exists()) mCacheDir.mkdirs();
}
public File getFile(String url){
File f = null;
try {
// 對 url 進行編輯,解決中文路徑問題
String filename = URLEncoder.encode(url, "utf-8");
f = new File(mCacheDir, filename);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return f;
}
public void clear(){
// 清除緩存文件
File[] files = mCacheDir.listFiles();
for(File f : files) f.delete();
}
}
Android 採單執行緒模型,UI 執行緒必須即時回應,否則會引發 ANR。因此圖片載入這種耗時工作必須放到背景,完成後再通知主執行緒更新。這裡刻意不用 AsyncTask,而是直接以「固定大小執行緒池 + 任務佇列 + Activity.runOnUiThread」手寫實作,讓異步溝通的本質更清楚。
public class AsyncImageLoader {
private MemoryCache mMemoryCache; // 內存緩存
private FileCache mFileCache; // 文件緩存
private ExecutorService mExecutorService; // 線程池
// 記錄已經加載圖片的 ImageView
private Map<ImageView, String> mImageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
// 保存正在加載圖片的 url
private List<LoadPhotoTask> mTaskQueue = new ArrayList<LoadPhotoTask>();
/**
* 默認采用一個大小為 5 的線程池
*/
public AsyncImageLoader(Context context, MemoryCache memoryCache, FileCache fileCache) {
mMemoryCache = memoryCache;
mFileCache = fileCache;
mExecutorService = Executors.newFixedThreadPool(5);
}
/**
* 根據 url 加載相應的圖片
* 先從一級緩存中取圖片,有則直接返回,如果沒有則異步從文件(二級緩存)中取,如果沒有再從網絡端獲取
*/
public Bitmap loadBitmap(ImageView imageView, String url) {
// 先將 ImageView 記錄到 Map 中,表示該 ui 已經執行過圖片加載了
mImageViews.put(imageView, url);
Bitmap bitmap = mMemoryCache.get(url); // 先從一級緩存中獲取圖片
if(bitmap == null) {
enquequeLoadPhoto(url, imageView); // 再從二級緩存和網絡中獲取
}
return bitmap;
}
/**
* 加入圖片下載隊列
*/
private void enquequeLoadPhoto(String url, ImageView imageView) {
// 如果任務已經存在,則不重新添加
if(isTaskExisted(url)) return;
LoadPhotoTask task = new LoadPhotoTask(url, imageView);
synchronized (mTaskQueue) {
mTaskQueue.add(task); // 將任務添加到隊列中
}
mExecutorService.execute(task);
}
/**
* 判斷下載隊列中是否已經存在該任務
*/
private boolean isTaskExisted(String url) {
if(url == null) return false;
synchronized (mTaskQueue) {
int size = mTaskQueue.size();
for(int i = 0; i < size; i++) {
LoadPhotoTask task = mTaskQueue.get(i);
if(task != null && task.getUrl().equals(url)) return true;
}
}
return false;
}
/**
* 從緩存文件或者網絡端獲取圖片
*/
private Bitmap getBitmapByUrl(String url) {
File f = mFileCache.getFile(url); // 獲得緩存圖片路徑
Bitmap b = ImageUtil.decodeFile(f); // 獲得文件的 Bitmap 信息
if (b != null) // 不為空表示獲得了緩存的文件
return b;
return ImageUtil.loadBitmapFromWeb(url, f); // 從網絡獲得圖片
}
/**
* 判斷該 ImageView 是否已經加載過圖片了
*/
private boolean imageViewReused(ImageView imageView, String url) {
String tag = mImageViews.get(imageView);
if (tag == null || !tag.equals(url)) return true;
return false;
}
private void removeTask(LoadPhotoTask task) {
synchronized (mTaskQueue) {
mTaskQueue.remove(task);
}
}
class LoadPhotoTask implements Runnable {
private String url;
private ImageView imageView;
LoadPhotoTask(String url, ImageView imageView) {
this.url = url;
this.imageView = imageView;
}
@Override
public void run() {
if (imageViewReused(imageView, url)) {// 判斷 ImageView 是否已經被復用
removeTask(this); // 如果已經被復用則刪除任務
return;
}
Bitmap bmp = getBitmapByUrl(url); // 從緩存文件或者網絡端獲取圖片
mMemoryCache.put(url, bmp); // 將圖片放入到一級緩存中
if (!imageViewReused(imageView, url)) {
// 若 ImageView 未加圖片則在 ui 線程中顯示圖片
BitmapDisplayer bd = new BitmapDisplayer(bmp, imageView, url);
Activity a = (Activity) imageView.getContext();
a.runOnUiThread(bd);
}
removeTask(this); // 從隊列中移除任務
}
public String getUrl() {
return url;
}
}
/**
* 由 UI 線程中執行該組件的 run 方法
*/
class BitmapDisplayer implements Runnable {
private Bitmap bitmap;
private ImageView imageView;
private String url;
public BitmapDisplayer(Bitmap b, ImageView imageView, String url) {
bitmap = b;
this.imageView = imageView;
this.url = url;
}
public void run() {
if (imageViewReused(imageView, url)) return;
if (bitmap != null) imageView.setImageBitmap(bitmap);
}
}
/**
* 釋放資源
*/
public void destroy() {
mMemoryCache.clear();
mMemoryCache = null;
mImageViews.clear();
mImageViews = null;
mTaskQueue.clear();
mTaskQueue = null;
mExecutorService.shutdown();
mExecutorService = null;
}
}
負責實際的網路下載與檔案解碼。下載時設定了 30 秒的連線與讀取逾時,並把資料串流寫入檔案後再解碼,這樣即使解碼失敗,檔案仍留在二級緩存中,下次可直接使用。
public class ImageUtil {
/**
* 從網絡獲取圖片,並緩存在指定的文件中
*/
public static Bitmap loadBitmapFromWeb(String url, File file) {
HttpURLConnection conn = null;
InputStream is = null;
OutputStream os = null;
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
is = conn.getInputStream();
os = new FileOutputStream(file);
copyStream(is, os); // 將圖片緩存到磁盤中
bitmap = decodeFile(file);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
try {
if(os != null) os.close();
if(is != null) is.close();
if(conn != null) conn.disconnect();
} catch (IOException e) {
}
}
}
public static Bitmap decodeFile(File f) {
try {
return BitmapFactory.decodeStream(new FileInputStream(f), null, null);
} catch (Exception e) {
}
return null;
}
private 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) {
ex.printStackTrace();
}
}
}

public class MainActivity extends Activity {
ListView list;
ListViewAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById(R.id.list);
adapter = new ListViewAdapter(this, mStrings);
list.setAdapter(adapter);
}
public void onDestroy(){
list.setAdapter(null);
super.onDestroy();
adapter.destroy();
}
private String[] mStrings = {
"https://news.jb51.net/UserFiles/x_Image/x_20150606083511_0.jpg",
"https://news.jb51.net/UserFiles/x_Image/x_20150606082847_0.jpg",
.....
};
public class ListViewAdapter extends BaseAdapter {
private Activity mActivity;
private String[] data;
private static LayoutInflater inflater = null;
private AsyncImageLoader imageLoader; // 異步組件
public ListViewAdapter(Activity mActivity, String[] d) {
this.mActivity = mActivity;
data = d;
inflater = (LayoutInflater)mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MemoryCache mcache = new MemoryCache(); // 內存緩存
File sdCard = android.os.Environment.getExternalStorageDirectory(); // 獲得 SD 卡
File cacheDir = new File(sdCard, "jereh_cache"); // 緩存根目錄
FileCache fcache = new FileCache(mActivity, cacheDir, "news_img"); // 文件緩存
imageLoader = new AsyncImageLoader(mActivity, mcache, fcache);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh = null;
if(convertView == null){
convertView = inflater.inflate(R.layout.item, null);
vh = new ViewHolder();
vh.tvTitle = (TextView)convertView.findViewById(R.id.text);
vh.ivImg = (ImageView)convertView.findViewById(R.id.image);
convertView.setTag(vh);
} else {
vh = (ViewHolder)convertView.getTag();
}
vh.tvTitle.setText("標題信息測試———— " + position);
vh.ivImg.setTag(data[position]);
// 異步加載圖片,先從一級緩存、再二級緩存、最後網絡獲取圖片
Bitmap bmp = imageLoader.loadBitmap(vh.ivImg, data[position]);
if(bmp == null) {
vh.ivImg.setImageResource(R.drawable.default_big);
} else {
vh.ivImg.setImageBitmap(bmp);
}
return convertView;
}
private class ViewHolder{
TextView tvTitle;
ImageView ivImg;
}
public void destroy() {
imageLoader.destroy();
}
}
ivImg.setTag(url) 加上 imageViewReused() 檢查。ListView 會重用檢視,若背景執行緒載完圖才發現這個 ImageView 已被配給其他項目,就必須放棄設定,否則會出現「圖片跑錯列」的經典 bug。isTaskExisted() 檢查佇列,同一個網址不會被送進佇列兩次。這套實作非常適合理解原理,但正式專案建議直接採用 Glide、Picasso 或 Coil。它們在快取策略(記憶體 + 磁碟 + 依尺寸解碼)、請求取消、生命週期綁定、GIF 與 SVG 支援等方面都遠比自行實作完善。另外提醒,範例中的 Bitmap.recycle() 在 Android 8.0 之後已無實際效果,且手動呼叫容易與其他持有參考的程式碼衝突,目前官方建議交由 GC 處理即可。
跟著 Google 學 Android(3.1):如何管好 Activity 的生命週期
當我們在 App 的各個頁面之間穿梭時,頁面背後的 Activity 也在自己的生命週期中不斷切換狀態。每當使用者進入或離開某個 Activity,Android 系統就
OpenGL ES 2.0 for Android 實戰:從三角形到彩色立方體
前面幾篇都在處理 OpenGL ES 2.0 的二維繪製,現在該邁進三維世界了。三維远比二維有趣,但複雜度也高出不少——在 Unity3D 裡拖一下就有一個立方體,而在
Android 逆向之旅:sharedUserId 屬性深入解析
一、前言 sharedUserId 大概是每個 Android 開發者都聽過、卻未必真正弄懂的屬性。最近專案剛好用到它,雖然知道一點皮毛,心裡還是有點模糊,於是寫了這篇來
把廣告改成「每開啟 8 次彈一次」, resulted在審核眼中卻是零廣告
前陣子做了一個 App,怕廣告影響使用體驗,就把策略調成每啟動 8 次才攔一次廣告。心裡還覺得挺體貼,結果上傳到應用寶之後,審核結果是這樣的: 看到了吧——無病毒、無廣