Toast顯示超詳細(xì)過(guò)程

前言

上次看到有人說(shuō)Toast屬于UI操作,只能在主線程中使用。其實(shí)不是這樣的,Toast是特殊的UI操作,由系統(tǒng)管理,我們只需在線程中創(chuàng)建MessageQueue和Looper讓Toast能夠回調(diào)當(dāng)前線程即可在任意線程使用,主線程由于屬于ActivityThread,默認(rèn)創(chuàng)建了消息隊(duì)列,所以可以直接使用Toast,Thread中則需要:

Looper.prepare();
Toast.makeText(context,text,duration).show();
Looper.loop();

注意:

  1. 文中大量涉及到進(jìn)程間通訊機(jī)制Binder的使用,建議先看些Binder的資料
  2. 文中源碼過(guò)長(zhǎng)的有省略,想要閱讀源碼的朋友可以在這兩個(gè)網(wǎng)站上查看:1、http://androidxref.com 2、 http://www.grepcode.com/

下面結(jié)合源碼詳細(xì)介紹一下Toast的顯示之路,為了方便理解,先展示UML圖:

總結(jié)

因?yàn)槊總€(gè)Toast顯示時(shí)間可能沖突,因此需要一個(gè)管理者來(lái)統(tǒng)一管理他們,在一個(gè)隊(duì)列中一個(gè)一個(gè)顯示,所以要使用管理者(NMS)的binder引用將Toast入隊(duì),顯示又要調(diào)用使用線程的binder引用,因此Toast的顯示大量用到了進(jìn)程間通信。

  1. 在使用線程中調(diào)用Toast.makeText(),創(chuàng)建一個(gè)Toast實(shí)例
  2. 調(diào)用toast.show();在這個(gè)方法中又調(diào)用getService()獲取NotificationManagerService的binder引用,將toast和mTN(繼承自ITransientNotification.Stub的TN類的實(shí)例,用來(lái)提供給NMS一個(gè)Binder引用,需要顯示Toast時(shí)可以調(diào)用TN的方法)等信息enqueue(),插入NMS中的待顯示序列。
  3. 輪到某個(gè)Toast顯示時(shí),在NMS中調(diào)用TN類的show()方法,在show方法中又通過(guò)handler在使用線程中直接獲取WindowManagerImpl然后addView,將Toast添加在Window中。
  4. 顯示的同時(shí)NMS也發(fā)送了一個(gè)延時(shí)消息,顯示時(shí)間過(guò)后就會(huì)調(diào)用TN的hide()方法,通過(guò)handler在使用線程中調(diào)用WindowManagerImpl的removeVIew()方法刪除該Toast
序列圖.png

源碼分析

Toast的創(chuàng)建

創(chuàng)建Toast我們都會(huì),最簡(jiǎn)單的方法就是 makeText();
看一下源碼:

public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
        //創(chuàng)建一個(gè)Toast
        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);
        
        //Toast中要顯示的TextView
        TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
        tv.setText(text);
        result.mNextView = v;
        //Toast顯示的時(shí)間
        result.mDuration = duration;

        return result;
    }

重要語(yǔ)句已注釋,現(xiàn)在我們知道在調(diào)用makeText時(shí)返回值就是創(chuàng)建完畢的Toast。下面看show()方法。

加入NMS的Toast隊(duì)列

系統(tǒng)中有可能很多程序都想要顯示Toast,如果同時(shí)出現(xiàn)就失去了原有的作用,因此必須有一個(gè)管理者來(lái)統(tǒng)一管理所有需要顯示的Toast,這個(gè)管理者就是系統(tǒng)服務(wù)之一:NotificationManagerService

 public void show() {
        if (mNextView == null) {
            throw new RuntimeException("setView must have been called");
        }
        //獲取NotificationManagerService的客戶端
        INotificationManager service = getService();
        
        String pkg = mContext.getOpPackageName();
        
        //tn是系統(tǒng)將會(huì)調(diào)用的回調(diào),來(lái)真正實(shí)現(xiàn)將Toast顯示在當(dāng)前Window
        TN tn = mTN;
        tn.mNextView = mNextView;

        try {
            service.enqueueToast(pkg, tn, mDuration);
        } catch (RemoteException e) {
            // Empty
        }
    }

看到這里,我們發(fā)現(xiàn)了兩個(gè)重要的類,INotificationManager和TN。

INotificationManager:(AIDL聲明的接口,具體實(shí)現(xiàn)在INotificationManager.Stub里,而系統(tǒng)服務(wù)NotificationManagerService正式繼承了INOtificationManager.Stub)是系統(tǒng)服務(wù)NMS在本地的binder引用,也就是客戶端,我們要跨進(jìn)程調(diào)用NMS的方法就要用到它。獲取方法:
      
static private INotificationManager getService() {
    if (sService != null) {
        return sService;
    }
    sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
    return sService;
}

TN:是真正實(shí)現(xiàn)將Toast顯示到當(dāng)前Window的工具,它繼承自ITransientNotification.Stub,也就是一個(gè)服務(wù)端,NMS可以調(diào)用TN的binder引用來(lái)調(diào)用TN的show()和hide()方法來(lái)顯示隱藏Toast。

通過(guò)調(diào)用NotificationManagerService的enqueue()方法,很明顯是要把包名,回調(diào)、顯示時(shí)間發(fā)送過(guò)去統(tǒng)一排隊(duì),一個(gè)一個(gè)顯示。下面看看排隊(duì)時(shí)發(fā)生了什么

NMS回調(diào)TN

排隊(duì)時(shí)發(fā)生了什么呢,貼上源碼:重要的就是這個(gè)同步的部分,前面省略

    synchronized (mToastQueue) {
            //這里獲取請(qǐng)求線程的pid和Uid
            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.
                //英文注釋很清楚了,這個(gè)index表示這條Toast是不是已經(jīng)存在在隊(duì)列中且尚未顯示,如果是,則刷新。
                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);
            }
        }

這其中的內(nèi)容主要就是判斷一下Toast在index中位置是不是0,如果是,就顯示,不是,就刷新自己。下面還要看看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 {
                //正主終于來(lái)了,當(dāng)年存入ToastRecord的回調(diào)終于派上用場(chǎng),這里調(diào)用的,就是TN的show方法。
                record.callback.show();
                //計(jì)算好時(shí)間,顯示既定時(shí)間之后就刪除,這個(gè)函數(shù)一會(huì)兒再說(shuō)。
                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;
                }
            }
        }
    }

剛才終于通過(guò)binder引用回調(diào)了TN的show方法,那么我們回過(guò)頭去看:

TN調(diào)用WMS顯示Toast

代碼很長(zhǎng),但是總結(jié)一下其實(shí)就是在請(qǐng)求線程中執(zhí)行handleShow()方法,利用WindowManager的addView()方法,在Window中添加toast。

@Override
public void show() {
    if (localLOGV) Log.v(TAG, "SHOW: " + this);
    mHandler.post(mShow);
}
final Runnable mShow = new Runnable() {
    @Override
    public void run() {
        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();
                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;
                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();
            }
        }

NMS回調(diào)TN

在NMS中又是怎么計(jì)時(shí)的呢,還記得剛才在回調(diào)TN的show()方法之后調(diào)用的方法嗎?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);
    }

很簡(jiǎn)單的一個(gè)函數(shù),取需要顯示的時(shí)間delay,然后發(fā)送一個(gè)延遲delay時(shí)間的消息,并且將ToastRecorder對(duì)象傳遞過(guò)去,這個(gè)消息是干嘛呢,繼續(xù)往下看:

private final class WorkerHandler extends Handler
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case MESSAGE_TIMEOUT:
                    handleTimeout((ToastRecord)msg.obj);
                    break;
            }
        }
    }

收到消息后,執(zhí)行handleTimeOut方法,并且將該ToastRecorder對(duì)象傳遞過(guò)去:

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

直接看最后一句,cancelToastLocked,在一個(gè)Toast顯示的時(shí)候其他Toast不能顯示,現(xiàn)在肯定是先取消這個(gè)鎖,繼續(xù)看:

private void cancelToastLocked(int index) {
        ToastRecord record = mToastQueue.get(index);
        try {
            //在這里調(diào)用了TN的hide()方法
            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();
        }
    }

在這個(gè)函數(shù)里面,首先是調(diào)用TN的hide()方法,隱藏顯示完畢的Toast,然后判斷還有沒(méi)有需要顯示的Toast,如果有的話,繼續(xù)顯示下一條。

TN調(diào)用WMS刪除Toast

到這里已經(jīng)差不多了,TN的hide被客戶端調(diào)用,發(fā)生的情況和show()差不多,也是在請(qǐng)求線程中通過(guò)WindowManager,remove掉剛才添加的Toast。

@Override
        public void hide() {
            if (localLOGV) Log.v(TAG, "HIDE: " + this);
            mHandler.post(mHide);
        }
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;
            }
        };
 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;
            }
        }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容