你不会以为Android Toast就只是简单的吐司吧?

8,579 阅读7分钟

今天看了一下Toast的源码,或者如果你对AIDL感兴趣,可以看下去。

Toast不会同一时间显示多个,好像所有Toast都是排队了一样,而且不同的App都是排的一个队列一样。是的,这里有一个队列。而且因为不同App都是使用这一个队列,这里就用到了AIDL跨进程通信。

跨进程有一个C/S的概念,就是服务端和客户端的概念,客户端调用服务端的服务,服务端把结果返回给客户端。

显示一个Toast有2个过程:

  • 1.一个toast包装好,去队列里排队。

      这个过程,队列是服务端,toast.show()是客户端。
    
  • 2.队列中排到这个Toast显示了,就会呼叫toast去自己显示。

      这个过程,队列是客户端,toast.show()是服务端。
    

想要显示一个Toast,代码如下:

Toast.makeText(context, text, duration).show();

先看看makeText()方法,它只是一个准备过程,加载好布局,然后要显示的内容设置好,要显示的时长设置好。结果仍是返回一个Toast对象。

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:

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()方法显示了:

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的相关内容

我自己新建了一个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接口中声明了addhello这两个方法,所以这两个方法是在实现Stub这个类的时候实现的。

一般情况下,在ServiceonBind方法中返回一个Stub对象,new这个Stub对象的时候就实现了这两个方法。这样服务端就准备好了。

客户端调用的时候bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);这里有个mServiceConnection回调,在回调中public void onServiceConnected(ComponentName name, IBinder service)可以拿到service对象,通过***.Stub.asInterface(service)就可以拿到代理对象,然后就可以调用方法了。

回到Toast

sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));

通过这样,拿到了‘排队’的服务,然后调用service.enqueueToast(pkg, tn, mDuration);就去排队了。这里的tn是一个TN类型的类型,保存了这个Toast相关信息,包括View,显示时长等等。同时TN也是一个ITransientNotification.Stub实现。这里就是第二步的时候作为服务端被调用(类似回调的作用)。

看看NotificationManagerService.javaenqueueToast()方法:

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对象了,看看ToastTN的实现:

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进行显示。 图1

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();
        }
    }

兄弟都看到这儿了,不点个收藏吗?(回复666,有彩蛋哦!)