Toast和Dialog不同,它的工作过程就稍显复杂了。虽然我们使用起来很容易
Toast.makeText(context,"haha",Toast.LENGTH_SHORT).show();
但是Android实现这一功能做了很多工作。下面我们来分析一下吧。
首先Toast也是基于Window来实现的,但是由于Toast具有定时消失的功能,所以实现中使用了handle。Toast内部有两种IPC过程,第一种是Toast访问NotificationManagerService(后面简称NMS),第二种是NMS回调Toast里的TN。
Toast属于系统Window,它的内部试图有两种,一种是系统默认的,另一种是通过setView来设置的,Toast内部有一个mNextView变量,用来保存Toast的View,setView的代码如下:
/**
* Set the view to show.
* @see #getView
*/
public void setView(View view) {
mNextView = view;
}
Toast提供了show和cancel的方法,它们内部是一个IPC的过程,代码如下:
/**
* Show the view for the specified duration.
*/
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) {
// Empty
}
}
/**
* Close the view if it's showing, or don't show it if it isn't showing yet.
* You do not normally have to call this. Normally view will disappear on its own
* after the appropriate duration.
*/
public void cancel() {
mTN.hide();
try {
getService().cancelToast(mContext.getPackageName(), mTN);
} catch (RemoteException e) {
// Empty
}
}
通过代码可以看出,Toast显示时,先调运了service.enqueueToast(pkg, tn, mDuration)方法,第一个参数时包名,第二个参数TN,表示一个远程回调,他是一个Binder类,第三个参数是Taost显示的时长。
//NMS中维护了一个List来保存所以的Toast显示请求,并把Toast请求封装成ToastRecord对象。
final ArrayList mToastQueue = new ArrayList();
@Override
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));
final boolean isPackageSuspended =
isPackageSuspendedForUser(pkg, Binder.getCallingUid());
if (ENABLE_BLOCKED_TOASTS && (!noteNotificationOp(pkg, Binder.getCallingUid())
|| isPackageSuspended)) {
if (!isSystemToast) {
Slog.e(TAG, "Suppressing toast from package " + pkg
+ (isPackageSuspended
? " due to package suspended by administrator."
: " 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= MAX_PACKAGE_NOTIFICATIONS) {
Slog.e(TAG, "Package has already posted " + count
+ " toasts. Not showing more. Package=" + pkg);
return;
}
}
}
}
Binder token = new Binder();
mWindowManagerInternal.addWindowToken(token,
WindowManager.LayoutParams.TYPE_TOAST);
record = new ToastRecord(callingPid, pkg, callback, duration, token);
mToastQueue.add(record);
index = mToastQueue.size() - 1;
keepProcessAliveIfNeededLocked(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);
}
}
}
通过代码可以看出,NMS中内部维护了一个mToastQueue,每当有Toast请求时,就先判断这个Toast是不是存在,不存在就创建一个新的(前提是mToastQueue的大小小于50)。ToastRecord对象创建后,就调运showNextToastLocked显示出来。下面来看看showNextToastLocked:
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(record.token);
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);
}
keepProcessAliveIfNeededLocked(record.pid);
if (mToastQueue.size() > 0) {
record = mToastQueue.get(0);
} else {
record = null;
}
}
}
}
通过代码可以看出,调运record.callback.show(record.token)来回调Toast中的方法,这个方法就是前面提到的TN类里的方法。
Toast的show和cancel都是借助NMS来完成的,由于NMS是运行在系统进程中的,所以这个过程只能通过IPC来完成。这里要注意的是TN这个类,他是一个Binder类,当NMS需要显示或者隐藏Toast的时候,就会通过IPC来回调TN的show和hide方法,来看看这两个方法:
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
IBinder token = (IBinder) msg.obj;
handleShow(token);
}
};
...
/**
* schedule handleShow into the right thread
*/
@Override
public void show(IBinder windowToken) {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
mHandler.obtainMessage(0, windowToken).sendToTarget();
}
/**
* schedule handleHide into the right thread
*/
@Override
public void hide() {
if (localLOGV) Log.v(TAG, "HIDE: " + this);
mHandler.post(mHide);
}
通过代码可以看出,在TN的回调中,是使用handler来切换会当前线程的(即请求显示Toast的线程),所以这意味着,Toast无法在没有Looper的线程中弹出,这是因为Handler需要使用Looper才能完成线程的切换。
在接着看showNextToastLocked方法,在调运完record.callback.show(record.token)把Toast显示以后,还会调运 scheduleTimeoutLocked(record)方法,来发送一个延时消息。
static final int LONG_DELAY = PhoneWindowManager.TOAST_WINDOW_TIMEOUT;
static final int SHORT_DELAY = 2000; // 2 seconds
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);
}
看了一下PhoneWindowManager类,TOAST_WINDOW_TIMEOUT=3500。
/** Amount of time (in milliseconds) a toast window can be shown. */
public static final int TOAST_WINDOW_TIMEOUT = 3500; // 3.5 seconds
在延迟相应的时间后,NMS会调用cancelToastLocked来隐藏Toast,
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
}
ToastRecord lastToast = mToastQueue.remove(index);
mWindowManagerInternal.removeWindowToken(lastToast.token, true);
keepProcessAliveIfNeededLocked(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();
}
}
可以看出,调运了record.callback.hide()来隐藏Toast,这里实际上就是回调了Toast的TN中的hide方法。
总结,通过上面的分析可以看出,Toast的显示和隐藏实际上是通过Toast 的TN类来完成的,具体是由show和hide方法来完成的。由于这两个方法是NMS跨进程调运的,因此它们是运行在Binder线程池中的。为了将执行线程切换会Toast请求所在的线程中,在它们的内部使用了Handler,再来了看看这两个方法
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;
}
};
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
IBinder token = (IBinder) msg.obj;
handleShow(token);
}
};
/**
* schedule handleShow into the right thread
*/
@Override
public void show(IBinder windowToken) {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
mHandler.obtainMessage(0, windowToken).sendToTarget();
}
/**
* schedule handleHide into the right thread
*/
@Override
public void hide() {
if (localLOGV) Log.v(TAG, "HIDE: " + this);
mHandler.post(mHide);
}
可以看出,显示和隐藏是分别通过handleShow和handleHide来完成的,它们都是在handler的looper所在的线程中完成的。看看他们的代码:
public void handleShow(IBinder windowToken) {
if (localLOGV) Log.v(TAG, "HANDLE SHOW: " + this + " mView=" + mView
+ " mNextView=" + mNextView);
if (mView != mNextView) {
// remove the old view if necessary
handleHide();
mView = mNextView;
...
mWM = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
...
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();
}
}
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.removeViewImmediate(mView);
}
mView = null;
}
}
可以看出,Toast的显示是通过WindowManager把View添加到Window上,隐藏则是WindowManager把View从Window上移除。
自定义Toast demo
通过源码分析Android窗口的创建:
Android创建窗口(一)创建应用窗口
Android创建窗口(二)创建Dialog
Android 创建窗口(三) 创建Toast