Toast 工作原理
Toast 的使用可以说是非常简单了,只需要一句话即可:
Toast.makeText(MainActivity.this, "message", Toast.LENGTH_SHORT).show();
然而,由于Android 系统的更新迭代,如此简单的Toast 也出现了问题,详见这篇《Android 7.1.1 系统使用Toast 可能出现的BadTokenException》,所以这里分析一下Toast 从创建到显示的一个工作过程。
一. 创建
先看一下创建Toast 第一步makeText 的源码
public static Toast makeText(@NonNull Context context, @Nullable Looper looper,
@NonNull CharSequence text, @Duration int duration) {
Toast result = new Toast(context, looper);
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 实例,并设置了布局界面和持续时间duration。下面再看一下Toast 的构造方法
public Toast(@NonNull Context context, @Nullable Looper looper) {
mContext = context;
mTN = new TN(context.getPackageName(), looper);
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);
}
看到其中有一行是mTN = new TN(),这里实例化了一个TN 对象,TN 是Toast 的一个内部类,其实是一个Binder 回调,本身也是一个Binder 对象,提供给NotificationManagerService 使用,用于进程间通信。实现的远程接口也比较简单,对应的是显示和隐藏Toast :
void hide() throws RemoteException;
void show() throws RemoteException;
二. 显示
Toast 显示需要调用show 方法,那么调用show 之后的执行过程是怎样的呢?先看一下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) {
// Empty
}
}
首先获取到了INotificationManager 的对象,这是一个远程的Service,所以enqueueToast 是一个远程调用,并将包名、Binder 回调、持续时间传递过去,INotificationManager 是一个接口,它的实现类是NotificationManagerService 类的一个属性,通过enqueueToast 方法的名字可以猜想是把Toast 信息放入到一个队列,实际上也是这样
@Override
public void enqueueToast(String pkg, ITransientNotification callback, int duration)
{
...
final boolean isSystemToast = isCallerSystemOrPhone() || ("android".equals(pkg));
final boolean isPackageSuspended =
isPackageSuspendedForUser(pkg, Binder.getCallingUid());
if (ENABLE_BLOCKED_TOASTS && !isSystemToast &&
(!areNotificationsEnabledForPackage(pkg, Binder.getCallingUid())
|| isPackageSuspended)) {
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<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;
}
}
}
}
Binder token = new Binder();
mWindowManagerInternal.addWindowToken(token, TYPE_TOAST, DEFAULT_DISPLAY);
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);
}
}
}
代码中有一个mToastQueue,这是一个ArrayList 用来保存ToastRecord,ToastRecord 是NotificationManagerService 的一个内部类,用来保存Toast 的信息,当一个新Toast 进来时,有大致如下流程:
1)判断当前Toast是否已经存在,如果已经存在就更新显示时长
2)如果不存在,遍历mToastQueue,如果是非系统Toast,统计相同包名的ToastRecord数量,如果大于MAX_PACKAGE_NOTIFICATIONS(50)则不继续添加。如注释所述防止DOS攻击。最后添加进mToastQueue
3)最后通过keepProcessAliveLocked(callingPid)方法来设置对应的进程为前台进程,保证不被销毁
4)如果当前是第一个,调用showNextToastLocked()开始依次显示mToastQueue中的Toast。
ToastRecord 用来保存Toast 的信息,如下所示:
private static final class ToastRecord
{
final int pid;
final String pkg;
final ITransientNotification callback;
int duration;
Binder token;
... //省略构造方法
}
其中的callback 属性就是Toast enqueueToast 传来的TN 对象。上面enqueueToast 方法调用了showNextToastLocked 来显示Toast,
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;
}
}
}
}
上面代码进行了如下操作:
1)取出ToastRecord 列表的第一个
2)调用record 内部callback 的show 方法,这是一个跨进程的调用,最后执行的是Toast 里的TN 的show 方法
3)执行超时取消方法即scheduleTimeoutLocked ,这也是Toast 的自动消失的关键方法
4)如果远程调用出现异常,则从ToastRecord 列表中删除当前record,如果列表不为空则取出第一个record 继续上述操作
上面第二步操作通过远程调用,又回到了应用进程执行TN 的show 方法,show 方法实现比较简单,就是向TN 内的mHandler 发送一个显示Toast 的Message,并把windowToken 传递过去,mHandler 在接收到Message 之后,调用了TN 的handleShow 方法
public void handleShow(IBinder windowToken) {
if (localLOGV) Log.v(TAG, "HANDLE SHOW: " + this + " mView=" + mView
+ " mNextView=" + mNextView);
// If a cancel/hide is pending - no need to show - at this point
// the window token is already invalid and no need to do any work.
if (mHandler.hasMessages(CANCEL) || mHandler.hasMessages(HIDE)) {
return;
}
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;
mParams.hideTimeoutMilliseconds = mDuration ==
Toast.LENGTH_LONG ? LONG_DURATION_TIMEOUT : SHORT_DURATION_TIMEOUT;
mParams.token = windowToken;
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);
// Since the notification manager service cancels the token right
// after it notifies us to cancel the toast there is an inherent
// race and we may attempt to add a window after the token has been
// invalidated. Let us hedge against that.
try {
mWM.addView(mView, mParams);
trySendAccessibilityEvent();
} catch (WindowManager.BadTokenException e) {
/* ignore */
}
}
}
主要就是获取系统服务WindowManager,为Toast 的View 显示设置相关的属性,然后调用WindowManager 的addView 方法将Toast 添加到屏幕上显示。至于WindowManager 是怎样添加View 的,就先不再深入追踪,到这里Toast 的显示就完事了,下面再看一下它的隐藏。刚才说了,在NotificationManagerService 远程调用show 方法之后又调用了scheduleTimeoutLocked 方法,这个方法就负责取消Toast,这个方法的实现比较简单,就是给内部的mHandler 发送一个包含当前ToastRecord 的延时消息,延时时长就是Toast 的duration,Handler 在接收到这个消息之后调用 handleTimeout 方法,handleTimeout 方法则调用了cancelToastLocked 方法,看一下cancelToastLocked 方法实现:
@GuardedBy("mToastQueue")
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, DEFAULT_DISPLAY);
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();
}
}
取消Toast 方法主要有以下操作:
1)调用record 中callback 的hide 方法,远程调用,执行TN 的hide 方法
2)将当前record 从Toast 队列中移除
3)移除当前Toast 绑定的token
4)如果Toast 队列不为空,显示下一个Toast
然后再来看一下TN 中的hide 方法,实现也是向Handler 发送一个取消Toast 的消息,mHandler 接收到消息执行handleHide 方法,handleHide 方法中则通过调用WindowManager 的removeViewImmediate 方法来移除Toast 的View。
至此,一个Toast 从创建到显示到自动消失就都分析完了,下面对整个过程进行一个简单的总结。
三. 流程概述
我们调用Toast的makeText 方法创建要显示的信息和显示时长,然后调用show 方法,Toast 类内部通过NotificationManager 告诉系统我要显示这个Toast,并且传递了自己的信息以及mTN 对象,NotificationManagerService 内部处理完成后远程调用mTN 对象的show 方法,这样就回到了应用进程,然后通过WindowManager 的addView 方法显示出该Toast。并且NotificationManagerService 在显示回调的时候会发一个时长为duration的延时消息,在该消息到达之后调用mTN 的hide 方法隐藏Toast。
时序图
image.png
注:1.x 表示显示过程,① 表示隐藏过程