安卓Toast显示流程分析

我们在开发apk的过程中,经常会用到Toast,它的确很方便,不用开发者编写UI布局,只需要传入字符串就能给用户提示,那么它的显示与消失的流程是怎样的呢,本来就来讲一讲这个流程(所用源码为android 8.0版本)。

1、首先我们来看一下Toast的弹出的写法:

Toast.makeText(ServiceTestActivity.this,"test",Toast.LENGTH_LONG).show();

1.1 我们看一下Toast.makeText都做了什么:

/**
     * Make a standard toast that just contains a text view.
     *
     * @param context  The context to use.  Usually your {@link android.app.Application}
     *                 or {@link android.app.Activity} object.
     * @param text     The text to show.  Can be formatted text.
     * @param duration How long to display the message.  Either {@link #LENGTH_SHORT} or
     *                 {@link #LENGTH_LONG}
     *
     */
    public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
        return makeText(context, null, text, duration);
    }

    /**
     * Make a standard toast to display using the specified looper.
     * If looper is null, Looper.myLooper() is used.
     * @hide
     */
    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;
    }

我们直接看第二个makeText方法,注意参数Looper对象此时为null,此方法里面,先是new一个Toast对象,然后加载了一个布局,这个布局就是Toast的布局,布局代码如下:

<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对象设置了布局和周期,返回了这个Toast对象。我们需要看一下Toast的构造函数都干了什么:

/**
     * Constructs an empty Toast object.  If looper is null, Looper.myLooper() is used.
     * @hide
     */
    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);
    }

Toast的构造函数里面又new了一个TN对象,然后给这个对象的两个属性设了值。我们来看一下TN是何方神圣:

private static class TN extends ITransientNotification.Stub
TN(String packageName, @Nullable Looper looper) {
            // XXX This should be changed to use a Dialog, with a Theme.Toast
            // defined that sets up the layout params appropriately.
            final WindowManager.LayoutParams params = mParams;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.width = WindowManager.LayoutParams.WRAP_CONTENT;
            params.format = PixelFormat.TRANSLUCENT;
            params.windowAnimations = com.android.internal.R.style.Animation_Toast;
            params.type = WindowManager.LayoutParams.TYPE_TOAST;
            params.setTitle("Toast");
            params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;

            mPackageName = packageName;

            if (looper == null) {
                // Use Looper.myLooper() if looper is not specified.
                looper = Looper.myLooper();
                if (looper == null) {
                    throw new RuntimeException(
                            "Can't toast on a thread that has not called Looper.prepare()");
                }
            }
            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();
                            // Don't do this in handleHide() because it is also invoked by
                            // handleShow()
                            mNextView = null;
                            break;
                        }
                        case CANCEL: {
                            handleHide();
                            // Don't do this in handleHide() because it is also invoked by
                            // handleShow()
                            mNextView = null;
                            try {
                                getService().cancelToast(mPackageName, TN.this);
                            } catch (RemoteException e) {
                            }
                            break;
                        }
                    }
                }
            };
        }

TN继承了一个Stub接口,可知其是一个IBinder对象,用来进程间通信的,其作用是为了和系统服务NOTIFICATION_SERVICE进行相互通信,具体的服务类是WindowManagerImpl.java。我们看一下TN的构造方法,其先检查了looper对象是否为null,若为null,则获取线程的looper对象,如果线程的looper对象仍为空,则会报

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

所以,如果想要用Toast,是需要我们的线程有looper的,系统在创建进程和main线程的时候,已经给我们创建好了main线程的looper对象,所以平时我们在Activity、Fragment、Service里面可以直接使用Toast,没有问题。

到这里Toast.makeText方法的关键信息都讲述完了,这里小结一下该方法里面都做了什么:

(1)新建了一个Toast对象,为Toast对象设置了布局和周期。

(2)Toast对象里面有新建了一个TN对象,这个对象是传给远程服务NITIFICATION_SERVICE方便回调的,TN对象里面又创建了一个handler,handler的looper是调用Toast的线程的looper,即handler是在调用Toast的线程处理消息的。

1.2 我们接下来看一下Toast.show()

/**
     * Show the view for the specified duration.
     */
    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
        }
    }

1.2.1 show()方法里面会调用getService方法获取服务,我们看一下获取什么服务:

static private INotificationManager getService() {
        if (sService != null) {
            return sService;
        }
        sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
        return sService;
    }

可知其实是通过Binder获取到名称为“notification”的系统服务的代理对象。“notification”服务的启动是在SystemServer.startOtherService里面启动的

mSystemServiceManager.startService(NotificationManagerService.class);

NotificationManagerService的onStart里面回把服务注册到ServiceManager类里面。系统服务的启动和注册有关流程见我的另两篇博客《SystemServer类解析》和《getSystemService追根溯源》。

1.2.2 返回到show方法,接下来会调用INotificationManager的enqueueToast方法,参数是本应用的包名、TN对象、周期。根据Binde机制的原理,我们可知在NotificationManagerSrevice里面会有一个INotificationManager.Stub类的实现类,该实现类会实现enqueueToast方法:

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

        @Override
        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));
            final boolean isPackageSuspended =
                    isPackageSuspendedForUser(pkg, Binder.getCallingUid());

            if (ENABLE_BLOCKED_TOASTS && (!noteNotificationOp(pkg, Binder.getCallingUid())
                    || isPackageSuspended)) {
                if (!isSystemToast) {
                    Slog.e(TAG, "Suppressing toast from package " + pkg
                            + (isPackageSuspended
                                    ? " due to package suspended by administrator."
                                    : " 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;
                                     }
                                 }
                            }
                        }

                        Binder token = new Binder();
                        mWindowManagerInternal.addWindowToken(token,
                                WindowManager.LayoutParams.TYPE_TOAST);
                        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);
                }
            }
        }

该方法显得略长,无关主流程的逻辑不在赘述,我们只捡重要的说。直接进到synchronized关键字修饰的同步代码段,先调用了indexOfToastLocked方法,该方法是返回相同包名并且TN对象相同的的ToastRecord对象在队列中的索引,找不到返回-1,根据我们99%的惯用写法,返回值为-1,所以我们直接看index为-1的逻辑。然后会判断是否为系统弹出的toast,若不是系统Toast,则会对每个应用所能在队列中存留的Toast的数量不能超过MAX_PACKAGE_NOTIFICATIONS(值为50),即一个应用连续发送Toast,超过50个Toast未处理就会报异常。接下来就是新建一个ToastRecord对象,入队列,添加到队列末尾。最后有一个判断,如果index为0,则会调用showNextToastLocked方法,看到这里可能有读者可能会有疑问,这里为什么要加一个index==0的判断,如果index不为0,那么如何显示Toast呢,别着急,其实这些逻辑就在showNextToastLocked里面。

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

进入到该方法,第一就代码就是获取到队列的首部的ToastRecord对象,然后进入了一个while循环。我们来看一下循环体的逻辑。

1.3.1 while循环体里面调用了record.callback.show(record.token),我们来分一下这句代码的逻辑。record.callback其实就是前面讲到TN对象,我们来看一下TN.show方法:

/**
         * schedule handleShow into the right thread
         */
        @Override
        public void show(IBinder windowToken) {
            if (localLOGV) Log.v(TAG, "SHOW: " + this);
            mHandler.obtainMessage(SHOW, windowToken).sendToTarget();
        }

可知是调用mHandler发送了一个SHOW的message,该handler创建请见TN的构造函数。消息处理是在TN.handleShow方法里面:

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);
                // 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;
                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);
                }
                if (localLOGV) Log.v(TAG, "ADD! " + mView + " in " + this);
                // Since the notification manager service cancels the token right
                // after it notifies us to cancel the toast there is an inherent
                // race and we may attempt to add a window after the token has been
                // invalidated. Let us hedge against that.
                try {
                    mWM.addView(mView, mParams);
                    trySendAccessibilityEvent();
                } catch (WindowManager.BadTokenException e) {
                    /* ignore */
                }
            }
        }

该方法核心逻辑是获取WINDOWS_SERVICE服务,该服务类是WindowManagerImpl,该服务是在SystemReServiceRegistry.java的静态代码块里面注册到的,调用WindowManagerImpl.addView方法来显示Toast。至于WindowsManagerImpl是如何加载布局的,本文这里就不在分析了,感兴趣的朋友可以去研究一下。到这里的朋友可能会注意到,Toast的布局的显示利用了WINDOW_SERVICE服务,该处代码是运行在handler所在的进程,如果handler是子线程的,那么该处代码是运行在子线程的,android的子线程不是不能操作UI吗,这里不会有问题吗,该问题请见我的另一篇博客《子线程能弹Toast吗》。

1.3.2 再回到NoificationManagerService的showNextToastLocked方法,接下来我们看一下scheduleTimeroutLocked方法:

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

该方法就是利用Handler发送一个延时消息MESSAGE_TIMEOUT,延迟时间为LONG_DELAY或者SHORT_DELAY,这个延迟时间是根据我们创建Toast的传的参数LENGTH_LONG或者LENGTH_SHORT来决定的,我们来看看分别到时代表多长时间:

static final int LONG_DELAY = PhoneWindowManager.TOAST_WINDOW_TIMEOUT;
    static final int SHORT_DELAY = 2000; // 2 seconds
/**PhoneWindowManager
Amount of time (in milliseconds) a toast window can be shown. */
public static final int TOAST_WINDOW_TIMEOUT = 3500; // 3.5 seconds

可知LENGHT_LONG对应的时间是3.5秒,LENGHT_SHORT对应的时间为2秒。需要注意的是,现在的handler不是TOAST里面的handler了,是NotificationManagerService里面的handler,我们来看一下其是如何处理MESSAGE_TIMEOUT消息的:

case MESSAGE_TIMEOUT:
                    handleTimeout((ToastRecord)msg.obj);
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);
            }
        }
    }

在handleTimeout方法里面,会对mToastQueue加锁,如果队列里面知道到了对应的ToastRecord(即当前正在显示的Toast),调用cancelToastLocked方法,看一下该方法:

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
        }

        ToastRecord lastToast = mToastQueue.remove(index);
        mWindowManagerInternal.removeWindowToken(lastToast.token, true);

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

1.3.2.1 我们来看一下record.callback.hide()方法都干了什么,其调用的是Toast里面的TN的hide方法,该方法也就是发送了一个HIDE消息,我们来看一下handler是如何处理该消息的,直接来看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.removeViewImmediate(mView);
                }

                mView = null;
            }
        }

该方法就是调用WidowManageImpl的removeViewImmediate方法使Toast消失。

1.3.2.2 回到cancelToastLocked方法,我们看一下后面的逻辑,后面的逻辑就是mToastQueue删除掉刚才的ToastRecord对象,因为该Toast的显示与消失工作已经做完了。最后就是判断mToastQueue里面还有没有ToastRecord,如果有,调用showNextToastLocked方法继续处理剩余的ToastRecord。

到这里Toast的显示与消失的处理流程就讲述完了,这里总结一下:

1、Toast的显示主要的代码都在Toast.java和NotificationManagerService.java里面,利用了Handler机制和binder机制;

2、Toast显示是利用了WindowsManagerImpl,这个方法避开了操作UI必须在UI线程的限制。

猜你喜欢

转载自blog.csdn.net/baidu_27196493/article/details/81663266