1, 概述
Toast是一种向用户快速展示少量信息的视图。当它显示时,它会浮在整个应用层的上面,并且不会获取到焦点。它的设计思想是能够向用户展示些信息,但又能尽量不显得唐突。本篇我们来研读一下Toast的源码,并探明它的显示及隐藏机制。
2 实现
从Toast的最简单调用开始,它的调用代码是:
Toast.makeText(context,"Show toast",Toast.LENGTH_LONG).show();
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
Toast result = new Toast(context); // 新建Toast对象
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; // 设置显示的view
result.mDuration = duration; // 设置持续时间
return result;
}
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>
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定义如下,
private static class TN extends ITransientNotification.Stub {
这很明显是用于IPC跨进程调用的,是系统服务所在的进程回调第三方apk用于显示view的。
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); // IPC
} catch (RemoteException e) {
// Empty
}
}
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
return sService;
}
INotificationManager到底对应服务端的哪个服务呢?
NotificationManagerService服务中, 有INotificationManager.Stub的匿名内部类实例,
private final IBinder mService = new INotificationManager.Stub() {
什么时候添加到ServiceManager中的呢?
在NotificationManagerService的onStart方法中,
publishBinderService(Context.NOTIFICATION_SERVICE, mService);
并且Context中,
public static final String NOTIFICATION_SERVICE = "notification";
终于确定了, INotificationManager对应的服务就该匿名内部类。
3 流程解析
完整的流程图如下,
、
其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) { //对Toast队列加锁
int callingPid = Binder.getCallingPid();//获取调用进程id
long callingId = Binder.clearCallingIdentity();//重置当前线程上进来的IPC的ID
try {
ToastRecord record;
int index = indexOfToastLocked(pkg, callback); //判断mTN是否存在队列中
// 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) {
//如果不是系统Toast,则限制toast的数量,以避免DOS攻击及内存泄露。
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) { // 50次
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); // 创建一个ToastRecord对象,并加入队列。
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);
}
}
}
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;
}
}
}
}
首先来论述显示流程,首先利用mHandler切换到主线程中,
public void show() {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
mHandler.post(mShow);
}
final Runnable mShow = new Runnable() {
@Override
public void run() {
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();
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) {
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); // 刷新界面,这样toast就显示了
trySendAccessibilityEvent();
}
}
scheduleTimeoutLocked方法关闭toast如下,
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);
}
static final int LONG_DELAY = 3500; // 3.5 seconds
static final int SHORT_DELAY = 2000; // 2 seconds
所以,toast的显示时间为2s或者3.5s
和toast的显示一样, handleHide方法关闭toast
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;
}
}
4 方法
除了使用固定的View和时间之外,可以自定义Toast吗?看看Toast的方法,
show | 显示 |
cancel | 关闭 |
setView可以设置自定义的View, setDuration可以设置显示时间,并且还可以通过setText方法设置显示的字符。
setView / getView | 设置自定义的View |
setDuration/ getDuration | 设置显示时间 |
setText | 显示字符 |
还可以利用setMargin和setGravity方法设置View在父视图中的位置。
5,小结
1, Toast的显示及取消是通过NotificationManagerService来管理的,它跨进程,使用AIDL来实现进程间通信。
2, 所有Toast都会加到NotificationManagerService的队列中,对于非系统程序,它会限制Toast的数量(当前我所读的代码中该值为50)以防止DOS攻击及内存泄露的问题。
3,所有Toast都是有一个mToastQueue对象进行管理,
final ArrayList<ToastRecord> mToastQueue = new ArrayList<ToastRecord>();
并且按照进入顺序逐个显示,前一个显示完了才显示后一个。
4,只要可以获取进程的上下文,就可以显示Toast,所以可以不需要activity.
5,可以利用Toast的方法自定义Toast。