呀呀呀,校招就要来了,撸完这篇就安心准备各种笔试面试啦啦,今天还是继续分析有关Window的内容,系统级Window,就是Toast啦;
我们平常是酱紫使用Toast的:
Toast.makeText(MainActivity.this, "这是一个Toast", Toast.LENGTH_LONG).show();
简单到有点吓人了吧,然而源码层面上面可没那么简单,我们来一起看看吧!
首先是调用的Toast的静态方法makeText:
Toast$makeText
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对象出来,来看下他的构造函数:
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对象出来了,TN是什么鬼呢?他是Toast的静态内部类,具体定义如下:
private static class TN extends ITransientNotification.Stub {}
他继承自ITransientNotification.Stub,而ITransientNotification.Stub是一个静态抽象类,他继承了Binder类,也就是说他其实上是用于跨进程通信的,因为我们使用系统的Window和我们的应用不是处于同一个进程的,势必要用到跨进程通信,具体的怎么通信等会后面会讲到啦!
查看TN的构造函数,其实就是设置了一些LayoutParams参数而已啦,TN创建完成之后,回到makeText方法里面,接着获得LayoutInflater对象,并且通过LayoutInflater的inflate方法利用pull解析的方式解析transient_notification.xml文件,这个xml文件是位于/android/frameworks/base/core/res/res/layout/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>
比较简单,其实就是LinearLayout中嵌套了TextView而已;
回到makeText方法,解析完xml文件之后,获取到他id为message的控件,设置控件显示的内容,除了这种方法之后,我们是可以为Toast指定自己的布局的,具体就是调用Toast的setView方法了,传入我们自定义的View即可;
public void setView(View view) {
mNextView = view;
}
接着就是一些设置语句了,最后返回创建的Toast就可以了;
有了Toast之后,我们调用他的show方法显示出来,具体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) {
// Empty
}
}
首先通过getService方法返回一个NotificationManagerService对象,具体我们来看看getService是怎么实现的:
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
return sService;
}
其实就是通过ServiceManager的getService方法返回一个服务名为"notification"的Service对象,具体这个Service对象是在什么时候添加到ServiceManager里面呢?当然是在Androdi系统启动的时候啦;具体来讲的话就是在SystemServer的main方法里面会执行ServerThread的initAndLoop方法,而在initAndLoop里面有下面这段代码:
notification = new NotificationManagerService(context, statusBar, lights);
ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
这段代码中的Context.NOTIFICATION_SERVICE的值就是"notification";
回到show方法里面,接着第6行获得包名,第7行获得我们在Toast构造函数中创建的TN对象,最后调用了NotificationManagerService的enqueueToast方法来将当前Toast加入队列,来看看enqueueToast的实现:
NotificationManagerService$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) {
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;
}
}
}
}
record = new ToastRecord(callingPid, pkg, callback, duration);
mToastQueue.add(record);
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);
}
}
}
代码相对来说比较长,但是很有逻辑的;首先进行的是一些参数合法性的检查,接着第24行调用indexOfToastLocked方法查看在Toast队列中是否已经存在当前Toast,我们来看看indexOfToastLocked方法:
NotificationManagerService$indexOfToastLocked
private int indexOfToastLocked(String pkg, ITransientNotification callback)
{
IBinder cbak = callback.asBinder();
ArrayList<ToastRecord> list = mToastQueue;
int len = list.size();
for (int i=0; i<len; i++) {
ToastRecord r = list.get(i);
if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
return i;
}
}
return -1;
}
其实就是遍历已经存在在Toast队列mToastQueue,查看是否存在等于当前想要添加的Toast,有的话返回在队列中的索引值,没有的话返回-1;
回到enqueueToast方法,第27行对indexOfToastLocked的返回值进行判断,如果这个返回值大于0表示Toast队列中已经存在当前Toast,从25-26行的注释可以看出来,如果已经存在想要添加的Toast的话,我们会更新已经存在的那个Toast而不会将当前Toast添加到队列里面,如果不存在的话,则执行第31行的语句块,具体要做的事情就是将当前Toast添加到mToastQueue队列中,但是在添加之前会进行一些判断操作,具体查看第31-32行的注释可以知道对于非系统应用来说mToastQueue的大小是受限制的,确切的讲最大是50,这样做的目的是为了防止DOS攻击;
第33行如果不是系统应用的话,会进入if语句块中,查看mToastQueue中与当前应用处于同一包下面的Toast,也就是38行所做的事情,如果处于同一包下的Toast个数超过了MAX_PACKAGE_NOTIFICATIONS,则输出错误日志信息,MAX_PACKAGE_NOTIFICATIONS的具体值是50;如果没有超过50的话,则执行49行,创建ToastRecord对象,在50行将其添加到mToastQueue队列中;接着执行第58行,如果刚刚添加进去的Toast是就是我们mToastQueue队列中的第一个Toast的话,那么我们需要马上显示出来,也就是执行第59行的showNextToastLocked方法;
NotificationManagerService$showNextToastLocked
private 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;
}
}
}
}
首先获取到mToastQueue的队首元素,对手不为null的话,则执行到while循环里面,执行第6行,这里callback的值其实就是实现了ITransientNotification接口的对象,也就是我们在创建Toast的时候在Toast构造函数里面中创建的TN对象,那么执行callback的show方法其实就是执行TN的show方法了,查看TN的show方法:
TN$show()
public void show() {
if (localLOGV) Log.v(TAG, "SHOW: " + this);
mHandler.post(mShow);
}
可以看到在这个方法里面实际上调用了Handler的post方法,为什么这里要用到Handler呢?原因我个人认为因为你想要显示一个Toast出来,那么你肯定需要在主线程中显示嘛,而TN是继承ITransientNotification.Stub的,而ITransientNotification.Stub继承自Binder类,那么TN中的方法是运行在Binder线程池中的,显然不能直接更新UI,因此创建了一个Handler类型的对象,而这个Handler是在TN内部定义的,那么就该保证这个Handler是处于主线程中的,这是怎么保证的呢?原因在于TN是Toast的静态内部类,而Toast是在主线程中创建的,也就保证了Handler处于主线程,扯的有点远了;继续分析,调用Handler的post其实上执行的是post参数的run方法,也就是mShow的run方法,这里的mShow实际上是Runnable对象,查看源码:
final Runnable mShow = new Runnable() {
@Override
public void run() {
handleShow();
}
};
他的run方法实际上执行的是handleShow方法,这个方法是在TN里面实现的;
TN$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();
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;
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();
}
}
刚进来首先执行的是handleHide方法移除掉已经存在的旧的Toast,这也就说明了一点,你不可能见到同时显示两个Toast的情况,第8行获得一个Application对象,接着第12行获得一个WindowManager对象,WindowManager对象的获得实际上调用的是ContextImpl的getSystemService方法,接着便是一些对LayoutParams参数的设置过程,最后执行WindowManager的addView将当前View添加到Window上面,而WindowManager是个接口,具体实现的话是WindowManagerImpl,而WindowManagerImpl会通过桥接模式由WindowManagerGlobal来进行添加,具体的添加过程大家可以查看:我眼中的Window创建/添加/删除/更新过程这篇博客;这样子的话,一个Toast就显示出来了;
继续回到NotificationManagerService的showNextToastLocked方法里面,现在是第6行执行完了,接着执行第7行,执行scheduleTimeoutLocked方法,这个scheduleTimeoutLocked里面实际上做的事情就是保证我们Toast显示一段时间之后自动消失,来看看里面是怎么实现的呢?
NotificationManagerService$scheduleTimeoutLocked
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);
}
其实就是封装了一个带有MESSAGE_TIMEOUT标志的Message消息,并且通过Handler对象发送一条延时消息,至于延长多长时间,这个需要看我们创建Toast的时候传入的参数了,如果传入了Toast.LENGTH_LONG,延时3.5秒,否则延时2秒,可想而知,我们应该看看mHandler的handleMessage方法了:
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MESSAGE_TIMEOUT:
handleTimeout((ToastRecord)msg.obj);
break;
}
}
里面执行的方法也比较简单,就只有一个case语句,执行了handleTimeout方法,来看这个方法:
NotificationManagerService$handleTimeout
private void handleTimeout(ToastRecord record)
{
if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
synchronized (mToastQueue) {
int index = indexOfToastLocked(record.pkg, record.callback);
if (index >= 0) {
cancelToastLocked(index);
}
}
}
做的事情还是比较简单的,首先是先查看想要消除的Toast在mToastQueue里面是否存在,如果存在的话,则调用cancelToastLocked方法:
NotificationManagerService$cancelToastLocked
private 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
}
mToastQueue.remove(index);
keepProcessAliveLocked(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();
}
}
和显示show不同的是,这里执行的是第4行callback的hide方法,而callback实际上是TN对象了,那么也就执行TN的hide方法了,具体下面的过程其实就和show方法一致了:
TN$hide
public void hide() {
if (localLOGV) Log.v(TAG, "HIDE: " + this);
mHandler.post(mHide);
}
同样也是使用Handler的post方法切换到主线程中,实际上会执行mHide的run方法,因为mHide是Runnable对象嘛;
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;
}
};
而mHide的run方法实际上执行的是TN里面的handleHide方法:
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;
}
}
具体是怎么删掉Toast的呢,就是通过调用WindowManager的removeView方法了,而WindowManager的实现类是WindowManagerImpl,具体的删除过程大家可以查看:我眼中的Window创建/添加/删除/更新过程这篇博客;
这样的话,一个Toast就被删除掉了,那么接下来mToastQueue队列中如果存在剩余的Toast的话,是怎么显示这些Toast的呢?别急,我们的cancelToastLocked方法还没分析完毕,回到cancelToastLocked方法,第11行将当前Toast从mToastQueue中删除掉避免再次显示嘛,接着判断mToastQueue是否非空,如果非空的话,执行showNextToastLocked继续进行显示了,而showNextToastLocked方法在前面我们的enqueueToast方法里面是有见到的,这样间接形成了递归,直到mToastQueue为空为止,则停止显示;
至此,Toast的源码部分分析结束啦,中间不免有疏漏之处,望大神能批评指正!!!!!!