Android窗口管理系統是很是大的一塊,涉及AMS、InputManagerService、輸入法管理等,這麼複雜的一個系統,若是直接扎進入分析看源碼可能會比較混亂,因此,本文以Toast顯示原理做爲切入點,但願能簡單點初窺一下WMS。首先,簡單看下Toast用法:javascript
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();複製代碼
下面跟一下源碼:java
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實例,併爲其建立了一個無主TextView,並沒多少特殊邏輯。那麼看下關鍵的show代碼:android
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獲取通知管理服務,多線程
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
return sService;
} 複製代碼
以後再將Toast的顯示請求發送給該服務,在發送的過程當中傳遞一個Binder實體,提供給NotificationManagerService回調使用,不過若是看下NotificationManagerService就會發現,該類並非Binder實體,因此自己不是服務邏輯的承載體,在NotificationManagerService中,真正的服務對象是INotificationManager.Stub,所以到Service端,真正請求的服務是INotificationManager.Stub的enqueueToast:async
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)能夠知道,這是個支持多線程的操做的對象,其實很好當即,既然上面牽扯到插入節點的操做,那麼就必定在某個地方有摘除節點的操做。接着看下showNextToastLocked,若是當前沒有Toast在顯示,就會執行showNextToastLocked,固然若是有正在顯示的Toast,這裏就只執行插入操做,其實這裏有點小計倆,那就是下一個Toast的執行是依賴超時進行處理的,也就是必須等到生一個Toast超時,顯示完畢,才顯示下一個Toast,具體讓下看:ide
void showNextToastLocked() {
ToastRecord record = mToastQueue.get(0);
while (record != null) {
try {
<!--關鍵點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;
}
}
}
}複製代碼
看一下關鍵點1,這裏雖然是while循環,可是隻取到一個有效的ToastRecord就返回了,也就是隊列上的後續TaskRecord要依賴其餘手段來顯示了。這裏並沒看到WindowManagerService的身影,其實View添加到窗口顯示的時機都是在APP端,而不是在服務端,對這裏而言,就是經過CallBack回調,前面不是傳遞過來一個Binder實體麼,這個實體在NotificationManagerService端就是做爲Proxy,以回調APP端,其實Android裏面的系統服務都是採用這種處理模式APP與Service互爲C/S,record.callback就是APP端TN的代理,這裏簡單看一下其實現:函數
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) {
<!--關鍵點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) {
<!--關鍵點2-->
if (mView.getParent() != null) {
mWM.removeView(mView);
}
mView = null;
}
}
}複製代碼
其show函數,歸根到底就是經過WindowManagerService,將View添加到Window, mWM.addView(mView, mParams);這樣Toast就顯示出來了。那麼怎麼隱藏呢?不能一個Toast老是佔據屏幕吧。oop
接着看NotificationManagerService端的showNextToastLocked函數,在callback後,會繼續經過scheduleTimeoutLocked爲Toast添加一個TimeOut監聽,並利用該監聽將過時的Toast從系統移出,看下實現:post
void showNextToastLocked() {
ToastRecord record = mToastQueue.get(0);
while (record != null) {
try {
<!--關鍵點1-->
record.callback.show();
<!--關鍵點2--> scheduleTimeoutLocked(record); return; } catch (RemoteException e) { ... } }複製代碼
scheduleTimeoutLocked其實就是經過Handler添加一個延時執行的Action,ui
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來隱藏當前顯示的Toast,固然,若是隊列中還有Toast要顯示,就繼續showNextToastLocked顯示下一個,這裏將顯示放在cancle裏完成Loop監聽也挺奇葩的。
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移除當前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呢,答案是確定的,有興趣能夠本身看下。
答案是:並不必定在主線程,可是要在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環境,在分析Toast顯示的時候,APP端是經過Handler執行的,這樣作的好處是不阻塞Binder線程,由於在這個點APP端Service端。另外,若是addView的線程不是Loop線程,執行完就結束了,固然就沒機會執行後續的請求,這個是由Hanlder的構造函數保證的
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,這就是爲何說「必定要在主線程」,其實準確的說應該是 「必定要在Looper非空的線程」。