Toast源码分析

Toast源码分析

1、概述

Toast是android中经常使用的提示框,系统通过WindowManager.addView()方法在顶层window窗口添加的视图,所以Toast显示时可以不依赖Activity界面和应用程序当我们把Toast添加到WindowManager进程时,用户应用程序退出时toast依然可以显示并打印,WindowManager和应用程序是不同进程级别的应用所以不会出现子线程更新UI问题(子线程更新UI实质是创建视图线程和更新视图线程不一致导致系统抛出的异常)。

2、原理分析

Toast通过Toast.makeText()方法创建,调用makeText方法时,系统创建Toast实例,并且填充Toast视图布局

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

Toast创建后通过Toast.show()方法显示,在show方法中通过getSerice()方法获取到INotificationManager的代理对象,获取当前Toast创建应用的包名,组装TN对象,通过远程代理调用INotificationManager中的enqueueToast方法,把Toast加入到Toast队列中,并传递包名,TN对象,和显示时长。

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

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

在INotificationManager的实现类中NotificationManagerService.enqueueToast方法中,判断NotificationManager中Toast队列中是否存在当前Toast对象,存在当前对象时更新toast显示时长,第一次添加toast时不存在,,获取Toast显示应用程序是否是系统程序,不是系统程序时限制toast显示数量最多不超过50,不超过50时创建ToastRecord对象,添加到mToastQueue队列中,第一次创建Toast时在ToastRecord中不存在返回-1,创建Toast加入到ToastRecord后赋值为0,通过调用showNextToastLocked方法显示toast视图。

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

在showNextToastLocked中,调用record.callback.show方法显示toast视图,record.callback是调用enqueueToast中传递的TN对象,调用tn.show方法发现是通过Handler发送数据给Handler对象处理,在Handler.handleMessage方法中调用handleShow方法,handleShow方法中调用handleHide()方法隐藏以前Toast的视图,通过WindowManager.addView()添加toast视图到顶层的window窗口。

      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;
            }
        }
    }
}
 public void show(IBinder windowToken) {
        if (localLOGV) Log.v(TAG, "SHOW: " + this);
        mHandler.obtainMessage(0, windowToken).sendToTarget();
   }

     final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            IBinder token = (IBinder) msg.obj;
            handleShow(token);
        }
    };

     public void  (IBinder windowToken) {
        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;
            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);
            mWM.addView(mView, mParams);
            trySendAccessibilityEvent();
        }
    }

在NotificationManagerService中调用record.callback.show()方法后,通过scheduleTimeoutLocked()方法通过Handler延时发送隐藏toast视图后,重新遍历toastRecord队列显示下个toast。

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

     mHandler = new WorkerHandler();

    private final class WorkerHandler extends Handler
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case MESSAGE_TIMEOUT:
                    handleTimeout((ToastRecord)msg.obj);
                    break;
                case MESSAGE_SAVE_POLICY_FILE:
                    handleSavePolicyFile();
                    break;
                case MESSAGE_SEND_RANKING_UPDATE:
                    handleSendRankingUpdate();
                    break;
                case MESSAGE_LISTENER_HINTS_CHANGED:
                    handleListenerHintsChanged(msg.arg1);
                    break;
                case MESSAGE_LISTENER_NOTIFICATION_FILTER_CHANGED:
                    handleListenerInterruptionFilterChanged(msg.arg1);
                    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);
            }
        }
    }

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

3、总结

Toast是通过WindowManager.addView()添加到window窗口的,当把toast添加到NotificationManager中的ToastRecord队列时,应用程序退出后依然显示toast视图,Toast视图是WindowManager进程中显示的,所以调用Toast.show时,可以不考虑线程问题(子线程更新UI实质是创建视图线程和更新视图线程不一致导致系统抛出的异常),但是Toast依赖于Handler消息机制,在子线程中Looper.perpase()没有调用,在子线程中直接使用Toast.show时会抛Can’t create handler inside thread that has not called Looper.prepare()异常,在子线程中打印toast时 可以使用一下方法,在子线程Looper.loop()时子线程会堵塞。

     new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            Toast.makeText(MainActivity.this,"dfadf",Toast.LENGTH_SHORT).show();
            Looper.loop();
            Log.e(TAG, "run: " );
        }
    }).start();

你可能感兴趣的:(android源码分析)