你不會覺得Android Toast就只是簡單的吐司吧?

今天看了一下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的相關內容

我本身新建了一個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,有彩蛋哦!)

相關文章
相關標籤/搜索