今天看了一下Toast的源码,或者若是你对AIDL感兴趣,能够看下去。java
Toast不会同一时间显示多个,好像全部Toast都是排队了同样,并且不一样的App都是排的一个队列同样。是的,这里有一个队列。并且由于不一样App都是使用这一个队列,这里就用到了AIDL跨进程通讯。android
跨进程有一个C/S的概念,就是服务端和客户端的概念,客户端调用服务端的服务,服务端把结果返回给客户端。bash
显示一个Toast有2个过程:ide
1.一个toast包装好,去队列里排队。oop
这个过程,队列是服务端,toast.show()是客户端。
复制代码
2.队列中排到这个Toast显示了,就会呼叫toast去本身显示。布局
这个过程,队列是客户端,toast.show()是服务端。
复制代码
想要显示一个Toast,代码以下:post
Toast.makeText(context, text, duration).show();
复制代码
先看看makeText()
方法,它只是一个准备过程,加载好布局,而后要显示的内容设置好,要显示的时长设置好。结果还是返回一个Toast对象。ui
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 result = new Toast(context, looper);
中初始化了一个TN对象mTN:this
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中。 而后就是调用show()
方法显示了:spa
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
}
}
复制代码
这里getService()
取到了服务,而后调用service.enqueueToast(pkg, tn, mDuration);
去排队。
这里的getService()其实是拿到了一个Service的本地代理:
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
return sService;
}
复制代码
***.Stub.asInterface
就是AIDL中的一个典型的写法。
我本身新建了一个AIDL,定义了2个方法。
// IMyTest.aidl
package top.greendami.aidl;
// Declare any non-default types here with import statements
interface IMyTest {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
int add(int a, int b);
String hello(String s);
}
复制代码
而后build一下,下面代码由AS自动生成,在build文件夹下面:
package top.greendami.aidl;
public interface IMyTest extends android.os.IInterface {
public static abstract class Stub extends android.os.Binder implements top.greendami.aidl.IMyTest {
private static final java.lang.String DESCRIPTOR = "top.greendami.aidl.IMyTest";
/**
* Construct the stub at attach it to the interface.
*/
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an top.greendami.aidl.IMyTest interface,
* generating a proxy if needed.
*/
public static top.greendami.aidl.IMyTest asInterface(android.os.IBinder obj) {
···
}
@Override
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
···
}
private static class Proxy implements top.greendami.aidl.IMyTest {
···
}
static final int TRANSACTION_add = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_hello = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
public int add(int a, int b) throws android.os.RemoteException;
public java.lang.String hello(java.lang.String s) throws android.os.RemoteException;
}
复制代码
先看看上面用到的asInterface
方法:
public static top.greendami.aidl.IMyTest asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof top.greendami.aidl.IMyTest))) {
return ((top.greendami.aidl.IMyTest) iin);
}
return new top.greendami.aidl.IMyTest.Stub.Proxy(obj);
}
复制代码
这里是先在本地查找看看有没有对象,若是有就说明没有跨进程,直接返回本地对象。若是没有就要返回一个代理了。这里能够看作服务端为客户端准备一个‘假’的本身,让客户端看起来就像拥有一个真正的服务端对象。
Proxy(obj)
中把代理中每一个方法都进行了处理,若是有add和hello两个方法:
private static class Proxy implements top.greendami.aidl.IMyTest {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
@Override
public int add(int a, int b) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(a);
_data.writeInt(b);
mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public java.lang.String hello(java.lang.String s) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.lang.String _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(s);
mRemote.transact(Stub.TRANSACTION_hello, _data, _reply, 0);
_reply.readException();
_result = _reply.readString();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_add = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_hello = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
复制代码
大体就是把须要传递的参数序列化,而后调用方法的真正实现,而后拿到返回的结果而且返回。咱们看到真正的方法实如今mRemote.transact
这里,这个Proxy就真的只是代理,和客户端交互,传递一下参数而已。
在onTransact
方法中实现了真正的调用:
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_add: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _arg1;
_arg1 = data.readInt();
int _result = this.add(_arg0, _arg1);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
case TRANSACTION_hello: {
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
java.lang.String _result = this.hello(_arg0);
reply.writeNoException();
reply.writeString(_result);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
复制代码
这里调用的this.add(_arg0, _arg1);
和this.hello(_arg0);
就是在AIDL中定义好的接口。由于abstract class Stub
中实现了top.greendami.aidl.IMyTest
接口(固然它也是一个Bind),在top.greendami.aidl.IMyTest
接口中声明了add
和hello
这两个方法,因此这两个方法是在实现Stub
这个类的时候实现的。
通常状况下,在Service
的onBind
方法中返回一个Stub
对象,new
这个Stub
对象的时候就实现了这两个方法。这样服务端就准备好了。
在客户端调用的时候bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
这里有个mServiceConnection
回调,在回调中public void onServiceConnected(ComponentName name, IBinder service)
能够拿到service
对象,经过***.Stub.asInterface(service)
就能够拿到代理对象,而后就能够调用方法了。
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
复制代码
经过这样,拿到了‘排队’的服务,而后调用service.enqueueToast(pkg, tn, mDuration);
就去排队了。这里的tn
是一个TN
类型的类型,保存了这个Toast相关信息,包括View,显示时长等等。同时TN
也是一个ITransientNotification.Stub
实现。这里就是第二步的时候做为服务端被调用(相似回调的做用)。
看看NotificationManagerService.java
中enqueueToast()
方法:
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)) {
...
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);
}
}
}
复制代码
这个方法首先校验了包名和回调是否是空,是的话就返回(代码省略)。 而后看看是否是被系统禁止显示通知的App(经过包名判断)。
前面的校验都经过了,就是开始排队了synchronized (mToastQueue)
,首先是拿到进程号,而后看看这个相同的App和回调以前有没有在队列中,若是在就更新一下显示时间,若是没在还要看看这个App有多少Toast,超过50就不让排队。若是这些都知足条件就进入队列排队。
if (index == 0) {
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);
下面这句是用handler
启用一个延时,取消显示 scheduleTimeoutLocked(record);
。这里的record.callback
就是以前传进来的TN
对象了,看看Toast
中TN
的实现:
private static class TN extends ITransientNotification.Stub {
...
static final long SHORT_DURATION_TIMEOUT = 4000;
static final long LONG_DURATION_TIMEOUT = 7000;
TN(String packageName, @Nullable Looper looper) {
...
mHandler = new Handler(looper, null) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW: {
IBinder token = (IBinder) msg.obj;
handleShow(token);
break;
}
case HIDE: {
handleHide();
mNextView = null;
break;
}
case CANCEL: {
handleHide();
mNextView = null;
try {
getService().cancelToast(mPackageName, TN.this);
} catch (RemoteException e) {
}
break;
}
}
}
};
}
/**
* schedule handleShow into the right thread
*/
@Override
public void show(IBinder windowToken) {
mHandler.obtainMessage(SHOW, windowToken).sendToTarget();
}
/**
* schedule handleHide into the right thread
*/
@Override
public void hide() {
if (localLOGV) Log.v(TAG, "HIDE: " + this);
mHandler.obtainMessage(HIDE).sendToTarget();
}
public void cancel() {
if (localLOGV) Log.v(TAG, "CANCEL: " + this);
mHandler.obtainMessage(CANCEL).sendToTarget();
}
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);
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);
}
try {
mWM.addView(mView, mParams);
trySendAccessibilityEvent();
} catch (WindowManager.BadTokenException e) {
/* ignore */
}
}
}
...
public void handleHide() {
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;
}
}
}
复制代码
这里就是简单的Handler的调用了。经过addView
进行显示。
Toast移除过程: scheduleTimeoutLocked
发送消息交给Handler处理。
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);//这里的延时就是显示时长
}
private final class WorkerHandler extends Handler
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MESSAGE_TIMEOUT:
handleTimeout((ToastRecord)msg.obj);
break;
}
}
}
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);
}
}
}
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();
}
}
复制代码