編輯:關於 Android 程式設計
前面我們已經剖析了 Activity、Dialog、PopupWindow 的加載繪製流程,相信大家对 Android 系統的窗口繪製機制已經有了較為清晰的認識。這一篇作為收尾,再來看看 Toast 的加載繪製流程。
Toast 窗口與前面三者有一個顯著不同:它屬於系統級窗口,和輸入框之類一樣,並不隸屬於某個具体应用、某個進程。因此,一旦涉及 Toast 的顯示流程,就必然牽涉到進程間通訊。而 Android 的進程間通訊採用的是其特有的 Binder 機制,所以 Toast 的顯示過程同樣離不開 Binder。
儘管如此,Toast 的顯示本質上仍是通過 Window 的窗口機制來完成加載繪製的,只是由於它是系統級窗口,才在過程中多了進程間通訊這一環。
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
這是最典型的用法:先通過 makeText 創建 Toast 對象,再調用 show 將窗口顯示出來。
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView) v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}方法體不長:先通過 Toast 的構造方法創建對象,再看構造方法做了什麼。
public Toast(Context context) {
mContext = context;
mTN = new TN();
mTN.mY = context.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.toast_y_offset);
mTN.mGravity = context.getResources().getInteger(
com.android.internal.R.integer.config_toastDefaultGravity);
}可以看到,這裡初始化了成員變量 mContext 和 mTN。其中 mTN 是什麼?它的定義是:
private static class TN extends ITransientNotification.Stub
由此不難看出,TN 是一個繼承自 ITransientNotification.Stub 的類——本質上是一個 Binder 對象,可用於進程間通訊。回到 makeText,在創建 Toast 對象後,我們又通過 LayoutInflater 加載了 Toast 的布局文件:
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);這個布局文件非常簡單,只有一個 LinearLayout,內部僅包含一個用於顯示文本的 TextView:
隨後,我們初始化布局、設置 mNextView 與 mDuration 並返回 Toast 對象,至此 Toast 對象構造完成。
調用完 makeText 後,show 方法負責真正把窗口顯示出來:
public void show() {
if (mNextView == null) {
throw new RuntimeException("setView must have been called");
}
INotificationManager service = getService();
String pkg = mContext.getOpPackageName();
TN tn = mTN;
tn.mNextView = mNextView;
try {
service.enqueueToast(pkg, tn, mDuration);
} catch (RemoteException e) { }
}首先判斷 mNextView 是否為空——若為空則無從顯示,直接拋出異常。接著執行:
INotificationManager service = getService();
其中 INotificationManager 是服務端 NotificationManagerService 的 Binder 客戶端,getService 的實現如下:
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(
ServiceManager.getService("notification"));
return sService;
}拿到 INotificationManager 對象後,我們調用 service.enqueueToast 並傳入 pkg、TN 對象與 duration。這裡實際執行的是 NotificationManagerService 內部類 INotificationManager.Stub 的 enqueueToast 方法。而 NotificationManagerService 運行在 SystemServer 進程中,底層正是通過 Binder 機制完成跨進程數據傳輸的。
@Override
public void enqueueToast(String pkg, ITransientNotification callback, int duration) {
synchronized (mToastQueue) {
int callingPid = Binder.getCallingPid();
long callingId = Binder.clearCallingIdentity();
try {
ToastRecord record;
int index = indexOfToastLocked(pkg, callback);
if (index >= 0) {
record = mToastQueue.get(index);
record.update(duration); // 已在隊列中則原地更新
} else {
// 限制每個應用的 Toast 數量,防止惡意轟炸
// ...
record = new ToastRecord(callingPid, pkg, callback, duration);
mToastQueue.add(record);
index = mToastQueue.size() - 1;
keepProcessAliveLocked(callingPid);
}
if (index == 0) {
showNextToastLocked(); // 位於隊首,直接顯示
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
}可以看到,這裡先把 Toast 在服務端的封裝對象 ToastRecord 保存到列表 mToastQueue 中,再調用 showNextToastLocked。其實現如下:
void showNextToastLocked() {
ToastRecord record = mToastQueue.get(0);
while (record != null) {
try {
record.callback.show(); // 回調 TN 的 show
scheduleTimeoutLocked(record); // 安排超時移除
return;
} catch (RemoteException e) {
// 進程已死,移除並保持進程存活
int index = mToastQueue.indexOf(record);
if (index >= 0) {
mToastQueue.remove(index);
}
keepProcessAliveLocked(record.pid);
record = mToastQueue.size() > 0 ? mToastQueue.get(0) : null;
}
}
}這裡執行的 record.callback.show,其 callback 就是創建 Toast 時傳入的 TN 對象,因此調用的正是 Toast 內部類 TN 的 show 方法。隨後調用 scheduleTimeoutLocked 安排超時:
private void scheduleTimeoutLocked(ToastRecord r) {
mHandler.removeCallbacksAndMessages(r);
Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;
mHandler.sendMessageDelayed(m, delay);
}可以看到,這裡發送了一個延遲消息,延遲時間正是 duration 對應的 SHORT_DELAY 或 LONG_DELAY——我們在 Toast 端傳遞的 duration 就是由此生效的。超時後 MESSAGE_TIMEOUT 消息最終會被 handleTimeout 處理:
private void handleTimeout(ToastRecord record) {
synchronized (mToastQueue) {
int index = indexOfToastLocked(record.pkg, record.callback);
if (index >= 0) {
cancelToastLocked(index);
}
}
}它又調用了 cancelToastLocked:
void cancelToastLocked(int index) {
ToastRecord record = mToastQueue.get(index);
try {
record.callback.hide(); // 回調 TN 的 hide
} catch (RemoteException e) { }
mToastQueue.remove(index);
keepProcessAliveLocked(record.pid);
if (mToastQueue.size() > 0) {
showNextToastLocked(); // 繼續顯示下一個
}
}這裡調用的 record.callback.hide 與前面的 show 相對應,同樣是 TN 內部類的方法。可見 Toast 的顯示與隱藏操作,都是在 Toast 內部類 TN 的 show 與 hide 方法中實現的;而 cancelToastLocked 在移除當前 Toast 後,會繼續調用 showNextToastLocked 顯示隊列中的下一個,直到 mToastQueue 清空為止。
先看 TN 的 show:
@Override
public void show() {
mHandler.post(mShow);
}這裡同樣是發送異步消息,mShow 的定義如下:
final Runnable mShow = new Runnable() {
@Override
public void run() {
handleShow();
}
};其 run 方法中調用了 handleShow,這才是真正執行顯示邏輯的地方:
public void handleShow() {
if (mView != mNextView) {
handleHide(); // 先移除舊的 View
mView = mNextView;
Context context = mView.getContext().getApplicationContext();
String packageName = mView.getContext().getOpPackageName();
if (context == null) {
context = mView.getContext();
}
mWM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
final Configuration config =
mView.getContext().getResources().getConfiguration();
final int gravity = Gravity.getAbsoluteGravity(mGravity, config.getLayoutDirection());
mParams.gravity = gravity;
// ... 設置 x、y、margin、packageName 等參數
if (mView.getParent() != null) {
mWM.removeView(mView);
}
mWM.addView(mView, mParams); // 通過 WindowManager 添加 View,完成顯示
trySendAccessibilityEvent();
}
}在 handleShow 中,經過一系列初始化——準備好 mWM(WindowManager)、mView 與 mParams 之後,調用 mWM.addView,便完成了 Toast 窗口的顯示。這部分邏輯與 Activity 等窗口的顯示流程如出一轍,都是通過 Window 機制添加 View 來呈現界面。
再看 TN 的 hide:
@Override
public void hide() {
mHandler.post(mHide);
}
final Runnable mHide = new Runnable() {
@Override
public void run() {
handleHide();
// 不放在 handleHide 中,是因為 handleShow 也會調用它
mNextView = null;
}
};與 show 類似,hide 也是發送異步消息,最終在 handleHide 中執行銷毀邏輯:
public void handleHide() {
if (mView != null) {
if (mView.getParent() != null) {
mWM.removeView(mView); // 通過 WindowManager 移除 View,完成銷毀
}
mView = null;
}
}可以看到,這裡調用了 mWM.removeView(mView),又是熟悉的代碼。至此,我們便完整走通了 Toast 窗口的顯示與銷毀流程。
Toast 是一個系統級窗口,其顯示與銷毀流程涉及進程間通訊(由 Binder 機制實現)。
Toast 的 show 方法會先初始化 Toast 對象,然後將內部對象 TN 與 duration 傳遞給 NotificationManagerService,後者在服務端維護一個 Toast 對象列表。
NotificationManagerService 接收到 show 請求後,保存 Toast 對象並回調 Toast.TN 的 show 方法,具體實現窗口的顯示邏輯。
Toast 窗口的顯示與銷毀機制與 Activity、Dialog、PopupWindow 類似,都是通過 WindowManager 對 View 的 add/remove 來完成。
此外,NotificationManagerService 在執行 show 時會發送一個延遲的 MESSAGE_TIMEOUT 異步消息,延遲時間即為 duration。到時它會觸發一連串取消流程,最終調用 TN 的 hide 銷毀窗口——這正是我們設置的顯示時長得以生效的關鍵所在。
Android 仿騰訊 QQ 實現滑動刪除(附完整源碼)
看了許多高手寫的文章,受益良多,也非常欣賞大家的分享精神,於是決定開始寫 Blog,把自己的心得記錄下來與各位交流。 先來看看效果圖: 原本我打算在 ListView
Android 內存洩露全解析:成因、典型場景與檢測排查
什麼是內存洩露? Android 虛擬機的垃圾回收採用的是根搜索算法。GC 會從根節點(GC Roots)出發遍歷整個 heap,最終那些無法直接或間接引用到 GC Ro
Android TabLayout 選項卡布局實戰入門教程
TabLayout 是許多人開發 Android 應用時經常會用到的組件,本文就帶大家一起動手玩轉這個官方選項卡控件,希望對正在學習的朋友有所幫助。 為什麼選擇 Tab
Android View 的繪製機制:Canvas 與 Paint 怎麼用
前面談過了 Android 如何測量,但只知道一個控制項長到哪裡、有多寬多高,當然還不夠。只要簡單覆寫 onDraw,再拿 Canvas(畫布)配上一支 Paint(畫筆