編輯:關於 Android 程式設計
在 Android 開發中,網路請求、資料庫讀取這類耗時操作幾乎無處不在,而它們絕對不能放在主執行緒裡執行。一旦在主執行緒做這些事,介面就會被卡住,最終導致 ANR(應用無回應)。
因此我們只能另開子執行緒去處理這些繁重工作,完成後再把結果呈現到畫面上。由於控制項的更新只能發生在主執行緒,從子執行緒切回主執行緒就成了每個開發者都繞不開的課題。
Android 中實現執行緒切換,最常見的是 AsyncTask 與 Handler 兩種方案。
AsyncTask 是官方封裝好的類,上手簡單、效率也還過得去,但並非所有場景都適用,我自己用過一兩次之後就很少再碰它了。Handler 則堪稱萬能,它的核心是訊息迴圈:在主執行緒建立 Handler 時就啟動了訊息迴圈,會逐一取出並處理訊息佇列中的任務。不過 Handler 也有惱人的地方——麻煩。
每回都要專門宣告一個 Handler,再透過 handleMessage(Message msg) 把訊息取出來做介面操作,中間還牽涉到參數傳遞等瑣事,寫起來著實繁瑣。
既然現有方案各有優劣,我們不妨動手封裝一層,兼取其長。
先梳理一下需求:
沿用 Handler 做執行緒切換;在子執行緒中只要一行簡單呼叫就能切到主執行緒;切換時子執行緒可以選擇進入阻塞,直到主執行緒執行完畢;整體要保證效率;主執行緒的執行必須設上限時,不能久留以免拖垮介面。
再來規劃實作方式:
以 Handler 為基礎,主類別自然透過繼承 Handler 來實現;為了呼叫簡單,對外暴露靜態方法;為了兼顧效率又不錯過任何一次呼叫,內部用外部佇列緩衝;考慮到阻塞與非阻塞兩種情況,乾脆分成兩個佇列;針對主執行緒不能久留的要求,為佇列執行加上時間上限;最後,為了讓呼叫更簡潔,參數直接採用 Runnable。
先來看對外的兩個方法:
/**
* @author liuyazhuang
*/
public class ToolKit {
/**
* Asynchronously
* @param runnable Runnable Interface
*/
public static void runOnMainThreadAsync(Runnable runnable) { }
/**
* Synchronously
* @param runnable Runnable Interface
*/
public static void runOnMainThreadSync(Runnable runnable) { }
}
接著建立繼承自 Handler 的 HandlerPoster:
final class HandlerPoster extends Handler {
private final int ASYNC = 0x1;
private final int SYNC = 0x2;
private final Queue asyncPool;
private final Queue syncPool;
private final int maxMillisInsideHandleMessage;
private boolean asyncActive;
private boolean syncActive;
HandlerPoster(Looper looper, int maxMillisInsideHandleMessage) {
super(looper);
this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
asyncPool = new LinkedList<>();
syncPool = new LinkedList<>();
}
void dispose() {
this.removeCallbacksAndMessages(null);
this.asyncPool.clear();
this.syncPool.clear();
}
void async(Runnable runnable) {
synchronized (asyncPool) {
asyncPool.offer(runnable);
if (!asyncActive) {
asyncActive = true;
if (!sendMessage(obtainMessage(ASYNC))) {
throw new GeniusException(Could not send handler message);
}
}
}
}
void sync(SyncPost post) {
synchronized (syncPool) {
syncPool.offer(post);
if (!syncActive) {
syncActive = true;
if (!sendMessage(obtainMessage(SYNC))) {
throw new GeniusException(Could not send handler message);
}
}
}
}
@Override
public void handleMessage(Message msg) {
if (msg.what == ASYNC) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
Runnable runnable = asyncPool.poll();
if (runnable == null) {
synchronized (asyncPool) {
runnable = asyncPool.poll();
if (runnable == null) {
asyncActive = false;
return;
}
}
}
runnable.run();
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage(ASYNC))) {
throw new GeniusException(Could not send handler message);
}
rescheduled = true;
return;
}
}
} finally {
asyncActive = rescheduled;
}
} else if (msg.what == SYNC) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
SyncPost post = syncPool.poll();
if (post == null) {
synchronized (syncPool) {
post = syncPool.poll();
if (post == null) {
syncActive = false;
return;
}
}
}
post.run();
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage(SYNC))) {
throw new GeniusException(Could not send handler message);
}
rescheduled = true;
return;
}
}
} finally {
syncActive = rescheduled;
}
} else super.handleMessage(msg);
}
}
變數部分:兩個標識、兩個佇列、兩個執行狀態、一個時間上限。標識用來區分處理哪個佇列,佇列用來存放任務,執行狀態避免重複送訊息導致佇列堆積,時間上限則用來約束主執行緒的單次佔用。
方法部分:
構造函數 HandlerPoster(Looper looper, int maxMillisInsideHandleMessage) 傳入 Looper(綁定主執行緒)與時間上限,並初始化兩個佇列。
銷毀函數 dispose() 先移除尚未處理的訊息,再清空兩個佇列。
async(Runnable runnable) 進入後先進同步區塊,把任務 offer 進佇列,再判斷是否已在執行;若否,立刻切換狀態並送出一個帶標識的訊息。這裡刻意用 obtainMessage(ASYNC) 複用訊息物件,避免頻繁建立新 Message。
sync(SyncPost post) 邏輯相同,只是傳入的是為同步而封裝的 SyncPost。
handleMessage(Message msg) 是 Handler 的訊息處理入口。當收到 ASYNC 或 SYNC 訊息時,會在 while 迴圈中反覆從對應佇列 poll 出任務執行;每次執行後都檢查耗時,一旦超過上限就重新送訊息並返回,把主執行緒讓出來。poll 為空時會再進同步區塊二次確認,兼顧併發下剛好有新任務送達的情況。
SyncPost 的關鍵:
final class SyncPost {
boolean end = false;
Runnable runnable;
SyncPost(Runnable runnable) { this.runnable = runnable; }
public void run() {
synchronized (this) {
runnable.run();
end = true;
try { this.notifyAll(); } catch (Exception e) { e.printStackTrace(); }
}
}
public void waitRun() {
if (!end) {
synchronized (this) {
if (!end) {
try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
}
}
}
run() 執行完任務後把 end 設為 true 並 notifyAll 喚醒等待方;waitRun() 則先判斷 end,若已完成就直接返回,避免主執行緒尚未執行到 run() 而子執行緒已在 wait() 造成死等。end 與 try 的搭配正是為了處理這種先後順序不確定的競態。
回到 ToolKit:
public class ToolKit {
private static HandlerPoster mainPoster = null;
private static HandlerPoster getMainPoster() {
if (mainPoster == null) {
synchronized (ToolKit.class) {
if (mainPoster == null) {
mainPoster = new HandlerPoster(Looper.getMainLooper(), 20);
}
}
}
return mainPoster;
}
public static void runOnMainThreadAsync(Runnable runnable) {
if (Looper.myLooper() == Looper.getMainLooper()) {
runnable.run();
return;
}
getMainPoster().async(runnable);
}
public static void runOnMainThreadSync(Runnable runnable) {
if (Looper.myLooper() == Looper.getMainLooper()) {
runnable.run();
return;
}
SyncPost poster = new SyncPost(runnable);
getMainPoster().sync(poster);
poster.waitRun();
}
public static void dispose() {
if (mainPoster != null) {
mainPoster.dispose();
mainPoster = null;
}
}
}
這裡用一個靜態 HandlerPoster,並以雙重檢查鎖的同步方式完成初始化,適應多執行緒同時呼叫的情境;建構時傳入 Looper.getMainLooper() 表示綁定主執行緒,並把單次執行上限設為 20 毫秒。
runOnMainThreadAsync 會先判斷呼叫方是否已在主執行緒,若是就直接執行、不必繞一圈;否則丟進佇列。runOnMainThreadSync 同理,只是多了封裝與 waitRun() 等待,直到主執行緒執行完 SyncPost.run()。最後 dispose() 負責清理,善後不留垃圾。
對外就這麼兩個方法,簡潔好用:
// Runnable 的 run() 在主執行緒中執行,可進行介面操作 // 同步進入主執行緒,等待主執行緒處理完再繼續子執行緒 ToolKit.runOnMainThreadSync(Runnable runnable); // 異步進入主執行緒,無需等待 ToolKit.runOnMainThreadAsync(Runnable runnable);
大功告成。
利用 AbSlidingPlayView 打造高互動廣告輪播
在許多新聞與內容型 App 中,首頁常會出現可自動切換的橫幅或資訊卡片。這類效果不一定需要複雜的第三方元件,只要掌握 ViewPager、計時器與指示點的組合,就能完成流
自定義控件繪圖篇(十一):Paint 之 setXfermode 混合模式全解(下)
本文將逐一講解 PorterDuff.Mode 中剩餘各模式的含義。理解了這些模式後,回過頭再看 setColorFilter(new PorterDuffColorFi
Android AlertDialog 五種對話框完整實戰:確認、單選、多選、列表與自定義
幾乎每一款 App 都離不開對話框:刪除前的二次確認、性別選擇、興趣勾選、部門挑選,甚至是帶輸入框與圖片的「自定義彈窗」。本文用一個可直接跑起來的示例,把 AlertDi
SD 卡壞了怎麼辦?先別急著格式化,資料還有救
學習、工作、拍照,SD 卡幾乎無所不在。它容量可觀,卻 also 相當脆弱——一旦罷工,往往欲哭無淚。 面對讀不到的 SD 卡,第一反應通常是格式化,但這恰恰是資料徹底消