Android窗口管理系統(tǒng)是非常大的一塊逛漫,涉及AMS、InputManagerService锤灿、輸入法管理等挽拔,這么復(fù)雜的一個系統(tǒng),如果直接扎進入分析看源碼可能會比較混亂但校,所以螃诅,本文以Toast顯示原理作為切入點,希望能簡單點初窺一下WMS状囱。首先术裸,簡單看下Toast用法:
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Toast的顯示原理
下面跟一下源碼:
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實例,并為其創(chuàng)建了一個無主TextView亭枷,并沒多少特殊邏輯袭艺。那么看下關(guān)鍵的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) {
}
}
這里首先通過getService獲取通知管理服務(wù),
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
return sService;
}
之后再將Toast的顯示請求發(fā)送給該服務(wù)叨粘,在發(fā)送的過程中傳遞一個Binder實體匹表,提供給NotificationManagerService回調(diào)使用门坷,不過如果看下NotificationManagerService就會發(fā)現(xiàn),該類并不是Binder實體袍镀,所以本身不是服務(wù)邏輯的承載體默蚌,在NotificationManagerService中,真正的服務(wù)對象是INotificationManager.Stub苇羡,因此到Service端绸吸,真正請求的服務(wù)是INotificationManager.Stub的enqueueToast:
private final IBinder mService = new INotificationManager.Stub() {
public void enqueueToast(String pkg, ITransientNotification callback, int 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 (index >= 0) {
record = mToastQueue.get(index);
record.update(duration);
} else {
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 (index == 0) {
showNextToastLocked();
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
... }
}
從上面的synchronized (mToastQueue)可以知道,這是個支持多線程的操作的對象设江,其實很好立即锦茁,既然上面牽扯到插入節(jié)點的操作,那么就一定在某個地方有摘除節(jié)點的操作叉存。接著看下showNextToastLocked码俩,如果當(dāng)前沒有Toast在顯示,就會執(zhí)行showNextToastLocked歼捏,當(dāng)然如果有正在顯示的Toast稿存,這里就只執(zhí)行插入操作,其實這里有點小計倆瞳秽,那就是下一個Toast的執(zhí)行是依賴超時進行處理的瓣履,也就是必須等到生一個Toast超時,顯示完畢练俐,才顯示下一個Toast袖迎,具體讓下看:
void showNextToastLocked() {
ToastRecord record = mToastQueue.get(0);
while (record != null) {
try {
<!--關(guān)鍵點1-->
record.callback.show();
scheduleTimeoutLocked(record);
return;
} catch (RemoteException e) {
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;
}
}
}
}
看一下關(guān)鍵點1,這里雖然是while循環(huán)腺晾,但是只取到一個有效的ToastRecord就返回了燕锥,也就是隊列上的后續(xù)TaskRecord要依賴其他手段來顯示了。這里并沒看到WindowManagerService的身影悯蝉,其實View添加到窗口顯示的時機都是在APP端脯宿,而不是在服務(wù)端,對這里而言泉粉,就是通過CallBack回調(diào)连霉,前面不是傳遞過來一個Binder實體么,這個實體在NotificationManagerService端就是作為Proxy嗡靡,以回調(diào)APP端跺撼,其實Android里面的系統(tǒng)服務(wù)都是采用這種處理模式APP與Service互為C/S,record.callback就是APP端TN的代理讨彼,這里簡單看一下其實現(xiàn):
private static class TN extends ITransientNotification.Stub {
final Runnable mShow = new Runnable() {
@Override
public void run() {
handleShow();
}
};
final Runnable mHide = new Runnable() {
@Override
public void run() {
handleHide();
mNextView = null;
}
};
private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
final Handler mHandler = new Handler();
int mGravity;
int mX, mY;
float mHorizontalMargin;
float mVerticalMargin;
View mView;
View mNextView;
WindowManager mWM;
TN() {
final WindowManager.LayoutParams params = mParams;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = com.android.internal.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
}
@Override
public void show() {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
mHandler.post(mShow);
}
...
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();
String packageName = mView.getContext().getOpPackageName();
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;
mParams.packageName = packageName;
if (mView.getParent() != null) {
<!--關(guān)鍵點1-->
mWM.removeView(mView);
}
if (localLOGV) Log.v(TAG, "ADD! " + mView + " in " + this);
mWM.addView(mView, mParams);
trySendAccessibilityEvent();
}
}
public void handleHide() {
if (localLOGV) Log.v(TAG, "HANDLE HIDE: " + this + " mView=" + mView);
if (mView != null) {
<!--關(guān)鍵點2-->
if (mView.getParent() != null) {
mWM.removeView(mView);
}
mView = null;
}
}
}
其show函數(shù)歉井,歸根到底就是通過WindowManagerService,將View添加到Window哈误, mWM.addView(mView, mParams);這樣Toast就顯示出來了哩至。那么怎么隱藏呢躏嚎?不能一個Toast總是占據(jù)屏幕吧。
Toast的隱藏原理
接著看NotificationManagerService端的showNextToastLocked函數(shù)菩貌,在callback后卢佣,會繼續(xù)通過scheduleTimeoutLocked為Toast添加一個TimeOut監(jiān)聽,并利用該監(jiān)聽將過期的Toast從系統(tǒng)移出,看下實現(xiàn):
void showNextToastLocked() {
ToastRecord record = mToastQueue.get(0);
while (record != null) {
try {
<!--關(guān)鍵點1-->
record.callback.show();
<!--關(guān)鍵點2-->
scheduleTimeoutLocked(record);
return;
} catch (RemoteException e) {
...
}
}
scheduleTimeoutLocked其實就是通過Handler添加一個延時執(zhí)行的Action箭阶,
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);
}
等到 Timeout的時候虚茶,Handler處理該事件,
private void handleTimeout(ToastRecord record)
{
synchronized (mToastQueue) {
int index = indexOfToastLocked(record.pkg, record.callback);
if (index >= 0) {
cancelToastLocked(index);
}
}
}
可以看到就是通過cancelToastLocked來隱藏當(dāng)前顯示的Toast仇参,當(dāng)然嘹叫,如果隊列中還有Toast要顯示,就繼續(xù)showNextToastLocked顯示下一個诈乒,這里將顯示放在cancle里完成Loop監(jiān)聽也挺奇葩的罩扇。
void cancelToastLocked(int index) {
ToastRecord record = mToastQueue.get(index);
try {
record.callback.hide();
} catch (RemoteException e) {
}
mToastQueue.remove(index);
keepProcessAliveLocked(record.pid);
if (mToastQueue.size() > 0) {
showNextToastLocked();
}
}
callback.hide()其實就是通過WindowManager移除當(dāng)前View,
public void handleHide() {
if (mView != null) {
if (mView.getParent() != null) {
if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this);
mWM.removeView(mView);
}
mView = null;
}
}
可以看到Toast的顯示跟隱藏還是APP端自己處理的怕磨,就是通過WindowManager喂饥,添加或者移除View,不過這兩個時機是通過NotificationManagerService進行管理的癌压,其實就是保證Toast按照順序一個個顯示,防止Toast覆蓋荆陆, 以上就是Toast的顯示與有隱藏原理 滩届,可以看到這里并未涉及任何的Activity或者其他組件的信息,也就是說View的顯示其實可以完全不必依賴Activity被啼,那么是不是子線程也能添加顯示View或者更新UI呢帜消,答案是肯定的,有興趣可以自己看下浓体。
一個小問題:Toast一定要在主線程泡挺?
答案是:并不一定在主線程,但是要在Hanlder可用線程
方案一:可行
new Thread() {
@Override
public void run() {
super.run();
Looper.prepare();
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Looper.loop();
}
}.start();
方案二:出錯崩潰
new Thread() {
@Override
public void run() {
super.run();
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}.start();
為什么方案一可以命浴,而方案二不行娄猫,其實很簡單因為方案一提供了Toast運行所需要的Looper環(huán)境,在分析Toast顯示的時候生闲,APP端是通過Handler執(zhí)行的媳溺,這樣做的好處是不阻塞Binder線程,因為在這個點APP端Service端碍讯。另外悬蔽,如果addView的線程不是Loop線程,執(zhí)行完就結(jié)束了捉兴,當(dāng)然就沒機會執(zhí)行后續(xù)的請求蝎困,這個是由Hanlder的構(gòu)造函數(shù)保證的
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
如果Looper==null 录语,就會報錯,而Toast對象在實例化的時候禾乘,也會為自己實例化一個Hanlder澎埠,這就是為什么說“一定要在主線程”,其實準(zhǔn)確的說應(yīng)該是 “一定要在Looper非空的線程”盖袭。
作者:看書的小蝸牛
原文鏈接: 從Toast顯示原理初窺Android窗口管理