Toast 的 Window 创建过程

Toast 在开发中经常会被用到,那么它是怎么实现的呢?我们今天就来探讨一下,看看它是怎么被添加到窗口上面的。看看它的构造方法和 makeText() 方法

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

    public static Toast makeText(Context context, CharSequence text, @Duration 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;
    }
transient_notification:
<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>

在 makeText() 方法中,把 xml 布局转换为 view,里面的 TextView 显示我们添加的文字,然后把 view 和 duration 时间两个属性传递给 Toast,我们看看 Toast 的构造方法,它里面创建了 TN,设置了两个默认的属性 mY 和 mGravity,TN 中的构造方法中给 WindowManager.LayoutParams mParams = new WindowManager.LayoutParams() 这个对象设置了一些列的参数值,重点看下 params.type = WindowManager.LayoutParams.TYPE_TOAST 这个设置,type 属性值为 2005,如果我们通过WindowManager添加自定义view时,可以也设置这个值,伪装成 Toast 欺骗系统。

再看看 Toast 的 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;

扫描二维码关注公众号,回复: 9780806 查看本文章

        try {
            service.enqueueToast(pkg, tn, mDuration);
        } catch (RemoteException e) {
        }
    }
    
    static private INotificationManager getService() {
        if (sService != null) {
            return sService;
        }
        sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
        return sService;
    }
    
很简洁,pkg 是程序的包名,下面操作是把 Toast 的 mNextView 属性,也就是上面从 xml 中转换的view,赋值给 TN 的 mNextView 属性; getService() 则是获取到一个IInterface,这里一看就是用的IPC的 aidl 模式,其实这里获取的是 NotificationManagerService 里面的 mService 属性

    private final IBinder mService = new INotificationManager.Stub() {

        @Override
        public void enqueueToast(String pkg, ITransientNotification callback, int duration)
        {
            ...
        }
        
        ...
    }

重点在 enqueueToast() 方法
    public void enqueueToast(String pkg, ITransientNotification callback, int duration)
        {
            ...
            final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));

            synchronized (mToastQueue) {
                int callingPid = Binder.getCallingPid();
                long callingId = Binder.clearCallingIdentity();
                try {
                    ToastRecord record;
                    int index = indexOfToastLocked(pkg, callback);
                    if (index >= 0) {
                        record = mToastQueue.get(index);
                        record.update(duration);
                    } else {
                        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 (index == 0) {
                        showNextToastLocked();
                    }
                } finally {
                    Binder.restoreCallingIdentity(callingId);
                }
            }
        }
方法中刚进来就有一些非空判断,然后判断是否为系统Toast, mToastQueue 是个集合,对它加上了锁,防止并发出错,进入try..catch... 代码中,ToastRecord 是个包装类,封装了几个对象,然后是 indexOfToastLocked() 方法,这个方法是判断传进来的 callback 是否已经存在 mToastQueue 集合中了,如果有,就找出它的索引,无就返回 -1

    private static final class ToastRecord
    {
        final int pid;
        final String pkg;
        final ITransientNotification callback;
        int duration;

        ToastRecord(int pid, String pkg, ITransientNotification callback, int duration)
        {
            this.pid = pid;
            this.pkg = pkg;
            this.callback = callback;
            this.duration = duration;
        }

        void update(int duration) {
            this.duration = duration;
        }
    }

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

注意 IBinder cbak = callback.asBinder() 这行代码,这个 cbak 可以作为每个 IInterface 唯一标示。看看返回的索引值,如果索引 index 大于等于0,说明存在,这时候就找到 callback所在的对象,更新时间;如果小于0,判断 isSystemToast 值,是否属于系统的 Toast,如果不是系统而是我们应用程序的,则有个数 MAX_PACKAGE_NOTIFICATIONS = 50 限制,也就是说我们每一个应用层程序同时在这个集合中 Toast 的最大个数是 50,超过50个了就不会往里面添加了,直到有移除后才会继续往里面添加。 接下来就是把 callback 等几个值封装到一个 ToastRecord 对象中,然后添加到 mToastQueue 集合中, keepProcessAliveLocked() 意思大概是把当前进程设置为前台进程; if (index == 0) 这个判断是说,如果集合中只有当前一个对象,那么执行 showNextToastLocked() 这个方法,这个方法中决定了Toast的展示

 void showNextToastLocked() {
        ToastRecord record = mToastQueue.get(0);
        while (record != null) {
            try {
                record.callback.show();
                scheduleTimeoutLocked(record);
                return;
            } catch (RemoteException e) {
               ...
            }
        }
    }
这个方法实际上只看中间两行代码就可以了,先看看 record.callback.show(),这个是个回调,callback 对应的是 Toast 中的 TN,它的 show() 方法

   public void show() {
        mHandler.post(mShow);
    }

    final Runnable mShow = new Runnable() {
        @Override
        public void run() {
            handleShow();
        }
    };
通过 Handler 切换线程,最终执行 handleShow() 方法

    public void handleShow() {
        if (mView != mNextView) {
            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;
            if (mView.getParent() != null) {
                mWM.removeView(mView);
            }
            mWM.addView(mView, mParams);
            trySendAccessibilityEvent();
        }
    }

    public void handleHide() {
        if (mView != null) {
            if (mView.getParent() != null) {
                mWM.removeView(mView);
            }
            mView = null;
        }
    }

老样子,先判断 view 是否为同一个,只有不是同一个才弹出,显示当前view时判断之前的有没有移除,如果没有,则移除;getSystemService(Context.WINDOW_SERVICE) 获取 WindowManager 对象,实际上是 WindowManagerImpl 类型,这个是系统中单利的那个, mParams.x = mX; mParams.y = mY 是更新 LayoutParams 的值,它决定了view 所在屏幕中的位置;mWM.addView(mView, mParams) 这行代码把 mView 添加到了窗口上,到此,就交割给 ViewRootImpl 中了,后续逻辑这里就不分析了, record.callback.show() 执行完了,看看 scheduleTimeoutLocked(record) 代码

    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)
    {
        synchronized (mToastQueue) {
            int index = indexOfToastLocked(record.pkg, record.callback);
            if (index >= 0) {
                cancelToastLocked(index);
            }
        }
    }
通过一个 Handler,延迟时间执行操作,注意 long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY 代码,看看这里设置的删,非此即彼,3500 和 2000 毫秒,这也是我们往Toast中只能设置 LENGTH_SHORT 或 LENGTH_LONG ,设置其他值无效的原因,延迟 delay 时间执行 Handler 中操作,最终执行 handleTimeout() 方法,还是先找出对象在集合中的索引位置,如果存在,调用 cancelToastLocked() 方法

    void cancelToastLocked(int index) {
        ToastRecord record = mToastQueue.get(index);
        try {
            record.callback.hide();
        } catch (RemoteException e) {
        }
        mToastQueue.remove(index);
        keepProcessAliveLocked(record.pid);
        if (mToastQueue.size() > 0) {
            showNextToastLocked();
        }
    }
record.callback.hide() 对应的是 TN 中的 hide() 方法,上面也提到过一点

    public void hide() {
        if (localLOGV) Log.v(TAG, "HIDE: " + this);
        mHandler.post(mHide);
    }
    final Runnable mHide = new Runnable() {
        @Override
        public void run() {
            handleHide();
            mNextView = null;
        }
    };
    public void handleHide() {
        if (mView != null) {
            if (mView.getParent() != null) {
                mWM.removeView(mView);
            }
            mView = null;
        }
    }

最终是把 mView 从 WindowManager 中移除,并且置空 mNextView 、 mView 等对象,这是后显示的 Toast 的 view 控件就消失了。 继续 cancelToastLocked() 方法,从 mToastQueue 集合中移除该索引对应的对象;下面 if (mToastQueue.size() > 0) 语句判断,如果集合中还有元素,说明已经又有 Toast 加入集合中,然后再次执行 showNextToastLocked() 方法,重发开始的逻辑。
 

发布了176 篇原创文章 · 获赞 11 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Deaht_Huimie/article/details/96424038