呀呀呀,校招就要來了,撸完這篇就安心準備各種筆試面試啦啦,今天還是繼續分析有關Window的内容,系統級Window,就是Toast啦;
我們平常是醬紫使用Toast的:
Toast.makeText(MainActivity.this, "這是一個Toast", Toast.LENGTH_LONG).show();
簡單到有點吓人了吧,然而源碼層面上面可沒那麼簡單,我們來一起看看吧!
首先是調用的Toast的靜态方法makeText:
Toast$makeText
public static Toast makeText(Context context, CharSequence text, 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;
}
makeText中首先會建立一個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);
}
這個構造函數裡面最關鍵的就是會建立一個TN對象出來了,TN是什麼鬼呢?他是Toast的靜态内部類,具體定義如下:
private static class TN extends ITransientNotification.Stub {}
他繼承自ITransientNotification.Stub,而ITransientNotification.Stub是一個靜态抽象類,他繼承了Binder類,也就是說他其實上是用于跨程序通信的,因為我們使用系統的Window和我們的應用不是處于同一個程序的,勢必要用到跨程序通信,具體的怎麼通信等會後面會講到啦!
檢視TN的構造函數,其實就是設定了一些LayoutParams參數而已啦,TN建立完成之後,回到makeText方法裡面,接着獲得LayoutInflater對象,并且通過LayoutInflater的inflate方法利用pull解析的方式解析transient_notification.xml檔案,這個xml檔案是位于/android/frameworks/base/core/res/res/layout/transient_notification.xml下面的。檢視他的代碼如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="?android:attr/toastFrameBackground">
<TextView
android:id="@android:id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:textAppearance="@style/TextAppearance.Toast"
android:textColor="@color/bright_foreground_dark"
android:shadowColor="#BB000000"
android:shadowRadius="2.75"
/>
</LinearLayout>
比較簡單,其實就是LinearLayout中嵌套了TextView而已;
回到makeText方法,解析完xml檔案之後,擷取到他id為message的控件,設定控件顯示的内容,除了這種方法之後,我們是可以為Toast指定自己的布局的,具體就是調用Toast的setView方法了,傳入我們自定義的View即可;
public void setView(View view) {
mNextView = view;
}
接着就是一些設定語句了,最後傳回建立的Toast就可以了;
有了Toast之後,我們調用他的show方法顯示出來,具體show方法怎麼實作的呢?
public void show() {
if (mNextView == null) {
throw new RuntimeException("setView must have been called");
}
INotificationManager service = getService();
String pkg = mContext.getPackageName();
TN tn = mTN;
tn.mNextView = mNextView;
try {
service.enqueueToast(pkg, tn, mDuration);
} catch (RemoteException e) {
// Empty
}
}
首先通過getService方法傳回一個NotificationManagerService對象,具體我們來看看getService是怎麼實作的:
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
return sService;
}
其實就是通過ServiceManager的getService方法傳回一個服務名為"notification"的Service對象,具體這個Service對象是在什麼時候添加到ServiceManager裡面呢?當然是在Androdi系統啟動的時候啦;具體來講的話就是在SystemServer的main方法裡面會執行ServerThread的initAndLoop方法,而在initAndLoop裡面有下面這段代碼:
notification = new NotificationManagerService(context, statusBar, lights);
ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
這段代碼中的Context.NOTIFICATION_SERVICE的值就是"notification";
回到show方法裡面,接着第6行獲得包名,第7行獲得我們在Toast構造函數中建立的TN對象,最後調用了NotificationManagerService的enqueueToast方法來将目前Toast加入隊列,來看看enqueueToast的實作:
NotificationManagerService$enqueueToast
public void enqueueToast(String pkg, ITransientNotification callback, int duration)
{
if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
if (pkg == null || callback == null) {
Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
return ;
}
final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));
if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
if (!isSystemToast) {
Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
return;
}
}
synchronized (mToastQueue) {
int callingPid = Binder.getCallingPid();
long callingId = Binder.clearCallingIdentity();
try {
ToastRecord record;
int index = indexOfToastLocked(pkg, callback);
// If it's already in the queue, we update it in place, we don't
// move it to the end of the queue.
if (index >= 0) {
record = mToastQueue.get(index);
record.update(duration);
} else {
// Limit the number of toasts that any given package except the android
// package can enqueue. Prevents DOS attacks and deals with leaks.
if (!isSystemToast) {
int count = 0;
final int N = mToastQueue.size();
for (int i=0; i<N; i++) {
final ToastRecord r = mToastQueue.get(i);
if (r.pkg.equals(pkg)) {
count++;
if (count >= MAX_PACKAGE_NOTIFICATIONS) {
Slog.e(TAG, "Package has already posted " + count
+ " toasts. Not showing more. Package=" + pkg);
return;
}
}
}
}
record = new ToastRecord(callingPid, pkg, callback, duration);
mToastQueue.add(record);
index = mToastQueue.size() - 1;
keepProcessAliveLocked(callingPid);
}
// If it's at index 0, it's the current toast. It doesn't matter if it's
// new or just been updated. Call back and tell it to show itself.
// If the callback fails, this will remove it from the list, so don't
// assume that it's valid after this.
if (index == 0) {
showNextToastLocked();
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
}
代碼相對來說比較長,但是很有邏輯的;首先進行的是一些參數合法性的檢查,接着第24行調用indexOfToastLocked方法檢視在Toast隊列中是否已經存在目前Toast,我們來看看indexOfToastLocked方法:
NotificationManagerService$indexOfToastLocked
private int indexOfToastLocked(String pkg, ITransientNotification callback)
{
IBinder cbak = callback.asBinder();
ArrayList<ToastRecord> list = mToastQueue;
int len = list.size();
for (int i=0; i<len; i++) {
ToastRecord r = list.get(i);
if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
return i;
}
}
return -1;
}
其實就是周遊已經存在在Toast隊列mToastQueue,檢視是否存在等于目前想要添加的Toast,有的話傳回在隊列中的索引值,沒有的話傳回-1;
回到enqueueToast方法,第27行對indexOfToastLocked的傳回值進行判斷,如果這個傳回值大于0表示Toast隊列中已經存在目前Toast,從25-26行的注釋可以看出來,如果已經存在想要添加的Toast的話,我們會更新已經存在的那個Toast而不會将目前Toast添加到隊列裡面,如果不存在的話,則執行第31行的語句塊,具體要做的事情就是将目前Toast添加到mToastQueue隊列中,但是在添加之前會進行一些判斷操作,具體檢視第31-32行的注釋可以知道對于非系統應用來說mToastQueue的大小是受限制的,确切的講最大是50,這樣做的目的是為了防止DOS攻擊;
第33行如果不是系統應用的話,會進入if語句塊中,檢視mToastQueue中與目前應用處于同一包下面的Toast,也就是38行所做的事情,如果處于同一包下的Toast個數超過了MAX_PACKAGE_NOTIFICATIONS,則輸出錯誤日志資訊,MAX_PACKAGE_NOTIFICATIONS的具體值是50;如果沒有超過50的話,則執行49行,建立ToastRecord對象,在50行将其添加到mToastQueue隊列中;接着執行第58行,如果剛剛添加進去的Toast是就是我們mToastQueue隊列中的第一個Toast的話,那麼我們需要馬上顯示出來,也就是執行第59行的showNextToastLocked方法;
NotificationManagerService$showNextToastLocked
private void showNextToastLocked() {
ToastRecord record = mToastQueue.get(0);
while (record != null) {
if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
try {
record.callback.show();
scheduleTimeoutLocked(record);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Object died trying to show notification " + record.callback
+ " in package " + record.pkg);
// remove it from the list and let the process die
int index = mToastQueue.indexOf(record);
if (index >= 0) {
mToastQueue.remove(index);
}
keepProcessAliveLocked(record.pid);
if (mToastQueue.size() > 0) {
record = mToastQueue.get(0);
} else {
record = null;
}
}
}
}
首先擷取到mToastQueue的隊首元素,對手不為null的話,則執行到while循環裡面,執行第6行,這裡callback的值其實就是實作了ITransientNotification接口的對象,也就是我們在建立Toast的時候在Toast構造函數裡面中建立的TN對象,那麼執行callback的show方法其實就是執行TN的show方法了,檢視TN的show方法:
TN$show()
public void show() {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
mHandler.post(mShow);
}
可以看到在這個方法裡面實際上調用了Handler的post方法,為什麼這裡要用到Handler呢?原因我個人認為因為你想要顯示一個Toast出來,那麼你肯定需要在主線程中顯示嘛,而TN是繼承ITransientNotification.Stub的,而ITransientNotification.Stub繼承自Binder類,那麼TN中的方法是運作在Binder線程池中的,顯然不能直接更新UI,是以建立了一個Handler類型的對象,而這個Handler是在TN内部定義的,那麼就該保證這個Handler是處于主線程中的,這是怎麼保證的呢?原因在于TN是Toast的靜态内部類,而Toast是在主線程中建立的,也就保證了Handler處于主線程,扯的有點遠了;繼續分析,調用Handler的post其實上執行的是post參數的run方法,也就是mShow的run方法,這裡的mShow實際上是Runnable對象,檢視源碼:
final Runnable mShow = new Runnable() {
@Override
public void run() {
handleShow();
}
};
他的run方法實際上執行的是handleShow方法,這個方法是在TN裡面實作的;
TN$handleShow
public void handleShow() {
if (localLOGV) Log.v(TAG, "HANDLE SHOW: " + this + " mView=" + mView
+ " mNextView=" + mNextView);
if (mView != mNextView) {
// remove the old view if necessary
handleHide();
mView = mNextView;
Context context = mView.getContext().getApplicationContext();
if (context == null) {
context = mView.getContext();
}
mWM = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
// We can resolve the Gravity here by using the Locale for getting
// the layout direction
final Configuration config = mView.getContext().getResources().getConfiguration();
final int gravity = Gravity.getAbsoluteGravity(mGravity, config.getLayoutDirection());
mParams.gravity = gravity;
if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
mParams.horizontalWeight = 1.0f;
}
if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
mParams.verticalWeight = 1.0f;
}
mParams.x = mX;
mParams.y = mY;
mParams.verticalMargin = mVerticalMargin;
mParams.horizontalMargin = mHorizontalMargin;
if (mView.getParent() != null) {
if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this);
mWM.removeView(mView);
}
if (localLOGV) Log.v(TAG, "ADD! " + mView + " in " + this);
mWM.addView(mView, mParams);
trySendAccessibilityEvent();
}
}
剛進來首先執行的是handleHide方法移除掉已經存在的舊的Toast,這也就說明了一點,你不可能見到同時顯示兩個Toast的情況,第8行獲得一個Application對象,接着第12行獲得一個WindowManager對象,WindowManager對象的獲得實際上調用的是ContextImpl的getSystemService方法,接着便是一些對LayoutParams參數的設定過程,最後執行WindowManager的addView将目前View添加到Window上面,而WindowManager是個接口,具體實作的話是WindowManagerImpl,而WindowManagerImpl會通過橋接模式由WindowManagerGlobal來進行添加,具體的添加過程大家可以檢視:我眼中的Window建立/添加/删除/更新過程這篇部落格;這樣子的話,一個Toast就顯示出來了;
繼續回到NotificationManagerService的showNextToastLocked方法裡面,現在是第6行執行完了,接着執行第7行,執行scheduleTimeoutLocked方法,這個scheduleTimeoutLocked裡面實際上做的事情就是保證我們Toast顯示一段時間之後自動消失,來看看裡面是怎麼實作的呢?
NotificationManagerService$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);
}
其實就是封裝了一個帶有MESSAGE_TIMEOUT标志的Message消息,并且通過Handler對象發送一條延時消息,至于延長多長時間,這個需要看我們建立Toast的時候傳入的參數了,如果傳入了Toast.LENGTH_LONG,延時3.5秒,否則延時2秒,可想而知,我們應該看看mHandler的handleMessage方法了:
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MESSAGE_TIMEOUT:
handleTimeout((ToastRecord)msg.obj);
break;
}
}
裡面執行的方法也比較簡單,就隻有一個case語句,執行了handleTimeout方法,來看這個方法:
NotificationManagerService$handleTimeout
private void handleTimeout(ToastRecord record)
{
if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
synchronized (mToastQueue) {
int index = indexOfToastLocked(record.pkg, record.callback);
if (index >= 0) {
cancelToastLocked(index);
}
}
}
做的事情還是比較簡單的,首先是先檢視想要消除的Toast在mToastQueue裡面是否存在,如果存在的話,則調用cancelToastLocked方法:
NotificationManagerService$cancelToastLocked
private void cancelToastLocked(int index) {
ToastRecord record = mToastQueue.get(index);
try {
record.callback.hide();
} catch (RemoteException e) {
Slog.w(TAG, "Object died trying to hide notification " + record.callback
+ " in package " + record.pkg);
// don't worry about this, we're about to remove it from
// the list anyway
}
mToastQueue.remove(index);
keepProcessAliveLocked(record.pid);
if (mToastQueue.size() > 0) {
// Show the next one. If the callback fails, this will remove
// it from the list, so don't assume that the list hasn't changed
// after this point.
showNextToastLocked();
}
}
和顯示show不同的是,這裡執行的是第4行callback的hide方法,而callback實際上是TN對象了,那麼也就執行TN的hide方法了,具體下面的過程其實就和show方法一緻了:
TN$hide
public void hide() {
if (localLOGV) Log.v(TAG, "HIDE: " + this);
mHandler.post(mHide);
}
同樣也是使用Handler的post方法切換到主線程中,實際上會執行mHide的run方法,因為mHide是Runnable對象嘛;
final Runnable mHide = new Runnable() {
@Override
public void run() {
handleHide();
// Don't do this in handleHide() because it is also invoked by handleShow()
mNextView = null;
}
};
而mHide的run方法實際上執行的是TN裡面的handleHide方法:
public void handleHide() {
if (localLOGV) Log.v(TAG, "HANDLE HIDE: " + this + " mView=" + mView);
if (mView != null) {
// note: checking parent() just to make sure the view has
// been added... i have seen cases where we get here when
// the view isn't yet added, so let's try not to crash.
if (mView.getParent() != null) {
if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this);
mWM.removeView(mView);
}
mView = null;
}
}
具體是怎麼删掉Toast的呢,就是通過調用WindowManager的removeView方法了,而WindowManager的實作類是WindowManagerImpl,具體的删除過程大家可以檢視:我眼中的Window建立/添加/删除/更新過程這篇部落格;
這樣的話,一個Toast就被删除掉了,那麼接下來mToastQueue隊列中如果存在剩餘的Toast的話,是怎麼顯示這些Toast的呢?别急,我們的cancelToastLocked方法還沒分析完畢,回到cancelToastLocked方法,第11行将目前Toast從mToastQueue中删除掉避免再次顯示嘛,接着判斷mToastQueue是否非空,如果非空的話,執行showNextToastLocked繼續進行顯示了,而showNextToastLocked方法在前面我們的enqueueToast方法裡面是有見到的,這樣間接形成了遞歸,直到mToastQueue為空為止,則停止顯示;
至此,Toast的源碼部分分析結束啦,中間不免有疏漏之處,望大神能批評指正!!!!!!