主頁 > 移動端開發 > 【Android開發藝術探索】理解Window和WindowManager

【Android開發藝術探索】理解Window和WindowManager

2020-09-14 22:31:50 移動端開發

個人博客:
http://www.milovetingting.cn

理解Window和WindowManager

window_windowmanager_mind.png

Window表示一個視窗的概念,是一個抽象類,具體實作是PhoneWindow,可以通過WindowManager創建一個Window,WindowManager是外界訪問Window的入口,Window具體實作位于WindowManagerService中,WindowManager和WindowManagerService的互動是一個IPC程序,

Window和WindowManager

WindowManager.LayoutParams

關注flags和type兩個引數:

Flags引數表示Window的屬性,可以控制Window的顯示特性,

** FLAG_NOT_FOCUSABLE **

表示Window不需要獲取焦點,也不需要接收各種輸入事件,此標記會同時啟用FLAG_NOT_TOUCH_MODAL,最終事件會直接傳遞給下層的具有焦點的Window,

** FLAG_NOT_TOUCH_MODAL **

系統會將當前Window區域以外的單擊事件傳遞給底層的Window,當前Window區域以內的單擊事件自己處理,

** FLAG_SHOW_WHEN_LOCKED **

讓Window顯示在鎖屏的界面上,

Type引數表示Window型別

Window有三種型別:應用Window、子Window、系統Window,應用Window對應一個Activity,子Window不能單獨存在,需要附屬在特定的父Window中,如Dialog就是子Window,系統Window需要宣告權限才能創建,如Toast和系統狀態欄就是系統Window,

Window是分層的,每個Window都有對應的z-ordered,層級大的覆寫在層級小的Window上,應用Window的層級范圍是1-99,子Window的層級范圍是1000-1999,系統Window層級范圍是2000-2999,

WindowManager常用的三個方法:添加View、更新View和洗掉View,這是從ViewManager實作過來的,

public interface ViewManager
{
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}

Window的內部機制

Window是一個抽象概念,每一個Window都對應一個View和一個ViewRootImpl,Window和View通過ViewRootImpl來建立聯系,

Window的添加程序

Window的添加程序需要通過WindowManager的addView來實作,WindowManager是一個介面,它的實作類是WindowManagerImpl,

public void addView(View view, LayoutParams params) {
        this.applyDefaultToken(params);
        this.mGlobal.addView(view, params, this.mContext.getDisplay(), this.mParentWindow);
    }

WindowManagerImpl并沒有直接實作addView,而是通過內部的WindowManagerGlobal實作的,

public void addView(View view, android.view.ViewGroup.LayoutParams params, Display display, Window parentWindow) {
        if (view == null) {
            //檢查view
            throw new IllegalArgumentException("view must not be null");
        } else if (display == null) {
            //檢查display
            throw new IllegalArgumentException("display must not be null");
        } else if (!(params instanceof LayoutParams)) {
            //檢查params
            throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
        } else {
            LayoutParams wparams = (LayoutParams)params;
            if (parentWindow != null) {
                //調整子視窗的布局引數
                parentWindow.adjustLayoutParamsForSubWindow(wparams);
            } else {
                Context context = view.getContext();
                if (context != null && (context.getApplicationInfo().flags & 536870912) != 0) {
                    wparams.flags |= 16777216;
                }
            }

            View panelParentView = null;
            int index;
            ViewRootImpl root;
            synchronized(this.mLock) {
                if (this.mSystemPropertyUpdater == null) {
                    this.mSystemPropertyUpdater = new Runnable() {
                        public void run() {
                            synchronized(WindowManagerGlobal.this.mLock) {
                                for(int i = WindowManagerGlobal.this.mRoots.size() - 1; i >= 0; --i) {
                                    ((ViewRootImpl)WindowManagerGlobal.this.mRoots.get(i)).loadSystemProperties();
                                }

                            }
                        }
                    };
                    SystemProperties.addChangeCallback(this.mSystemPropertyUpdater);
                }

                int index = this.findViewLocked(view, false);
                if (index >= 0) {
                    if (!this.mDyingViews.contains(view)) {
                        //不允許重復添加視窗
                        throw new IllegalStateException("View " + view + " has already been added to the window manager.");
                    }

                    ((ViewRootImpl)this.mRoots.get(index)).doDie();
                }

                if (wparams.type >= 1000 && wparams.type <= 1999) {
                    index = this.mViews.size();

                    for(int i = 0; i < index; ++i) {
                        if (((ViewRootImpl)this.mRoots.get(i)).mWindow.asBinder() == wparams.token) {
                            panelParentView = (View)this.mViews.get(i);
                        }
                    }
                }

                //創建ViewRootImpl
                root = new ViewRootImpl(view.getContext(), display);
                //設定LayoutParams
                view.setLayoutParams(wparams);
                this.mViews.add(view);
                this.mRoots.add(root);
                this.mParams.add(wparams);
            }

            try {
                //ViewRootImpl添加view
                root.setView(view, wparams, panelParentView);
            } catch (RuntimeException var15) {
                synchronized(this.mLock) {
                    index = this.findViewLocked(view, false);
                    if (index >= 0) {
                        this.removeViewLocked(index, true);
                    }
                }

                throw var15;
            }
        }
    }

ViewRootImpl呼叫setView方法

public void setView(View view, LayoutParams attrs, View panelParentView) {
        synchronized(this) {
            if (this.mView == null) {
                //...

                this.mAdded = true;
                //1、呼叫requestLayout方法
                this.requestLayout();
                
                //...

                int res;
                try {
                    this.mOrigWindowType = this.mWindowAttributes.type;
                    this.mAttachInfo.mRecomputeGlobalAttributes = true;
                    this.collectViewAttributes();
                    //2、通過Session添加Window
                    res = this.mWindowSession.addToDisplay(this.mWindow, this.mSeq, this.mWindowAttributes, this.getHostVisibility(), this.mDisplay.getDisplayId(), this.mAttachInfo.mContentInsets, this.mAttachInfo.mStableInsets, this.mAttachInfo.mOutsets, this.mInputChannel);
                } catch (RemoteException var20) {
                    this.mAdded = false;
                    this.mView = null;
                    this.mAttachInfo.mRootView = null;
                    this.mInputChannel = null;
                    this.mFallbackEventHandler.setView((View)null);
                    this.unscheduleTraversals();
                    this.setAccessibilityFocus((View)null, (AccessibilityNodeInfo)null);
                    throw new RuntimeException("Adding window failed", var20);
                } finally {
                    if (restore) {
                        attrs.restore();
                    }

                }

                //...
                if (res < 0) {
                    //添加Window失敗
                    this.mAttachInfo.mRootView = null;
                    this.mAdded = false;
                    this.mFallbackEventHandler.setView((View)null);
                    this.unscheduleTraversals();
                    this.setAccessibilityFocus((View)null, (AccessibilityNodeInfo)null);
                    switch(res) {
                    case -10:
                        throw new InvalidDisplayException("Unable to add window " + this.mWindow + " -- the specified window type " + this.mWindowAttributes.type + " is not valid");
                    case -9:
                        throw new InvalidDisplayException("Unable to add window " + this.mWindow + " -- the specified display can not be found");
                    case -8:
                        throw new BadTokenException("Unable to add window " + this.mWindow + " -- permission denied for window type " + this.mWindowAttributes.type);
                    case -7:
                        throw new BadTokenException("Unable to add window " + this.mWindow + " -- another window of type " + this.mWindowAttributes.type + " already exists");
                    case -6:
                        return;
                    case -5:
                        throw new BadTokenException("Unable to add window -- window " + this.mWindow + " has already been added");
                    case -4:
                        throw new BadTokenException("Unable to add window -- app for token " + attrs.token + " is exiting");
                    case -3:
                        throw new BadTokenException("Unable to add window -- token " + attrs.token + " is not for an application");
                    case -2:
                    case -1:
                        if (view.getContext().getPackageName().startsWith("com.google.android.gms")) {
                            try {
                                if (AppGlobals.getPackageManager().isFirstBoot()) {
                                    Log.d(this.mTag, "firstboot crash return");
                                    return;
                                }
                            } catch (RemoteException var22) {
                                var22.printStackTrace();
                                return;
                            }
                        }

                        throw new BadTokenException("Unable to add window -- token " + attrs.token + " is not valid; is your activity running?");
                    default:
                        throw new RuntimeException("Unable to add window -- unknown error code " + res);
                    }
                }

                //...

                //將view和ViewRootImpl關聯起來
                view.assignParent(this);
                
                //...
            }

        }
    }

1、requestLayout方法

public void requestLayout() {
        if (!this.mHandlingLayoutInLayoutRequest) {
            //A檢測執行緒
            this.checkThread();
            this.mLayoutRequested = true;
            //B開始View的繪制
            this.scheduleTraversals();
        }

    }

A:檢測執行緒,如果不是主執行緒,則報錯,

 void checkThread() {
        if (this.mThread != Thread.currentThread()) {
            throw new ViewRootImpl.CalledFromWrongThreadException("Only the original thread that created a view hierarchy can touch its views.");
        }
    }

B:開始View的繪制

void scheduleTraversals() {
        if (!this.mTraversalScheduled) {
            this.mTraversalScheduled = true;
            this.mTraversalBarrier = this.mHandler.getLooper().getQueue().postSyncBarrier();
            //回呼mTraversalRunnable
            this.mChoreographer.postCallback(2, this.mTraversalRunnable, (Object)null);
            if (!this.mUnbufferedInputDispatch) {
                this.scheduleConsumeBatchedInput();
            }

            this.notifyRendererOfFramePending();
            this.pokeDrawLockIfNeeded();
        }

    }

回呼mTraversalRunnable

final class TraversalRunnable implements Runnable {
        TraversalRunnable() {
        }

        public void run() {
            //呼叫doTraversal
            ViewRootImpl.this.doTraversal();
        }
    }

呼叫doTraversal

void doTraversal() {
        if (this.mTraversalScheduled) {
            this.mTraversalScheduled = false;
            this.mHandler.getLooper().getQueue().removeSyncBarrier(this.mTraversalBarrier);
            if (this.mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }

            //呼叫performTraversals
            this.performTraversals();
            if (this.mProfile) {
                Debug.stopMethodTracing();
                this.mProfile = false;
            }
        }

    }

呼叫performTraversals方法,在performTraversals方法內會呼叫performMeasure()、PerformLayout()、PerformDraw(),并最侄訓呼叫view的measure()、layout()、draw()方法

回到ViewRootImpl的setView方法,在2處通過WindowSession呼叫addToDisplay()方法,WindowSession是一個Binder物件,最終的實作為Session類,Session中的addToDisplay方法:

@Override
    public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
            int viewVisibility, int displayId, Rect outContentInsets, Rect outStableInsets,
            Rect outOutsets, InputChannel outInputChannel) {
        return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId,
                outContentInsets, outStableInsets, outOutsets, outInputChannel);
    }

addToDisplay方法通過呼叫WindowManagerService的addWindow方法,具體的addWindow方法,此處不再分析,

Window的洗掉程序

Window的洗掉程序和添加程序基本一樣,都是先通過WindowManagerImpl,再通過WindowManagerGlobal來實作的,

public void removeView(View view, boolean immediate) {
        if (view == null) {
            throw new IllegalArgumentException("view must not be null");
        } else {
            synchronized(this.mLock) {
                int index = this.findViewLocked(view, true);
                View curView = ((ViewRootImpl)this.mRoots.get(index)).getView();
                this.removeViewLocked(index, immediate);
                if (curView != view) {
                    throw new IllegalStateException("Calling with view " + view + " but the ViewAncestor is attached to " + curView);
                }
            }
        }
    }

removeView方法中又呼叫removeViewLocked方法

private void removeViewLocked(int index, boolean immediate) {
        ViewRootImpl root = (ViewRootImpl)this.mRoots.get(index);
        View view = root.getView();
        if (view != null) {
            InputMethodManager imm = InputMethodManager.getInstance();
            if (imm != null) {
                imm.windowDismissed(((View)this.mViews.get(index)).getWindowToken());
            }
        }

        boolean deferred = root.die(immediate);
        if (view != null) {
            view.assignParent((ViewParent)null);
            if (deferred) {
                this.mDyingViews.add(view);
            }
        }

    }

在removeViewLocked方法里呼叫ViewRootImpl的die方法

boolean die(boolean immediate) {
        if (immediate && !this.mIsInTraversal) {
            this.doDie();
            return false;
        } else {
            if (!this.mIsDrawing) {
                this.destroyHardwareRenderer();
            } else {
                Log.e(this.mTag, "Attempting to destroy the window while drawing!\n  window=" + this + ", title=" + this.mWindowAttributes.getTitle());
            }

            this.mHandler.sendEmptyMessage(3);
            return true;
        }
    }

die方法中,如果不是立即移除,則通過Handler發送一個移除訊息,如果是立即移除,則呼叫doDie方法

void doDie() {
    //檢查執行緒
        this.checkThread();
        synchronized(this) {
            if (this.mRemoved) {
                return;
            }

            this.mRemoved = true;
            if (this.mAdded) {
                this.dispatchDetachedFromWindow();
            }

            if (this.mAdded && !this.mFirst) {
                this.destroyHardwareRenderer();
                if (this.mView != null) {
                    int viewVisibility = this.mView.getVisibility();
                    boolean viewVisibilityChanged = this.mViewVisibility != viewVisibility;
                    if (this.mWindowAttributesChanged || viewVisibilityChanged) {
                        try {
                            if ((this.relayoutWindow(this.mWindowAttributes, viewVisibility, false) & 2) != 0) {
                                this.mWindowSession.finishDrawing(this.mWindow);
                            }
                        } catch (RemoteException var6) {
                        }
                    }

                    this.mSurface.release();
                }
            }

            this.mAdded = false;
        }

        WindowManagerGlobal.getInstance().doRemoveView(this);
    }

真正移除Window是在dispatchDetachedFromWindow方法中實作的

void dispatchDetachedFromWindow() {
        if (this.mView != null && this.mView.mAttachInfo != null) {
            this.mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
            this.mView.dispatchDetachedFromWindow();
        }

        this.mAccessibilityInteractionConnectionManager.ensureNoConnection();
        this.mAccessibilityManager.removeAccessibilityStateChangeListener(this.mAccessibilityInteractionConnectionManager);
        this.mAccessibilityManager.removeHighTextContrastStateChangeListener(this.mHighContrastTextManager);
        this.removeSendWindowContentChangedCallback();
        this.destroyHardwareRenderer();
        this.setAccessibilityFocus((View)null, (AccessibilityNodeInfo)null);
        this.mView.assignParent((ViewParent)null);
        this.mView = null;
        this.mAttachInfo.mRootView = null;
        this.mSurface.release();
        if (this.mInputQueueCallback != null && this.mInputQueue != null) {
            this.mInputQueueCallback.onInputQueueDestroyed(this.mInputQueue);
            this.mInputQueue.dispose();
            this.mInputQueueCallback = null;
            this.mInputQueue = null;
        }

        if (this.mInputEventReceiver != null) {
            this.mInputEventReceiver.dispose();
            this.mInputEventReceiver = null;
        }

        try {
            this.mWindowSession.remove(this.mWindow);
        } catch (RemoteException var2) {
        }

        if (this.mInputChannel != null) {
            this.mInputChannel.dispose();
            this.mInputChannel = null;
        }

        this.mDisplayManager.unregisterDisplayListener(this.mDisplayListener);
        this.unscheduleTraversals();
    }

在dispatchDetachedFromWindow中,最終通過Session來移除Window,

移除Window后,呼叫WindowManagerGlobal的doRemoveView方法將之前串列中的記錄清除

void doRemoveView(ViewRootImpl root) {
        synchronized(this.mLock) {
            int index = this.mRoots.indexOf(root);
            if (index >= 0) {
                this.mRoots.remove(index);
                this.mParams.remove(index);
                View view = (View)this.mViews.remove(index);
                this.mDyingViews.remove(view);
            }
        }

        if (ThreadedRenderer.sTrimForeground && ThreadedRenderer.isAvailable()) {
            this.doTrimForeground();
        }

    }

Window的更新程序

Window的更新是通過WindowManagerGlobal的updateViewLayout方法來實作的

public void updateViewLayout(View view, android.view.ViewGroup.LayoutParams params) {
        if (view == null) {
            throw new IllegalArgumentException("view must not be null");
        } else if (!(params instanceof LayoutParams)) {
            throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
        } else {
            LayoutParams wparams = (LayoutParams)params;
            view.setLayoutParams(wparams);
            synchronized(this.mLock) {
                int index = this.findViewLocked(view, true);
                ViewRootImpl root = (ViewRootImpl)this.mRoots.get(index);
                this.mParams.remove(index);
                this.mParams.add(index, wparams);
                root.setLayoutParams(wparams, false);
            }
        }
    }

Window創建程序

Activity的Window創建程序

先說明Activity的創建程序,Activity是在ActivityThread的performLaunchActivity方法中創建的,

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        //...

        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            //創建activity
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());

            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (r.overrideConfig != null) {
                    config.updateFrom(r.overrideConfig);
                }
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                Window window = null;
                //創建window
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = null;
                }
                appContext.setOuterContext(activity);
                //將activity和window關聯起來
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);

                //...

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to start activity " + component
                    + ": " + e.toString(), e);
            }
        }

        return activity;
    }

Activity的attach方法

final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor,
            Window window, ActivityConfigCallback activityConfigCallback) {
        attachBaseContext(context);

        mFragments.attachHost(null /*parent*/);

        //創建window
        mWindow = new PhoneWindow(this, window, activityConfigCallback);
        mWindow.setWindowControllerCallback(this);
        mWindow.setCallback(this);
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        //...

        //設定WindowManager
        mWindow.setWindowManager(
                (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                mToken, mComponent.flattenToString(),
                (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
        if (mParent != null) {
            mWindow.setContainer(mParent.getWindow());
        }
        mWindowManager = mWindow.getWindowManager();
        mCurrentConfig = config;

        mWindow.setColorMode(info.colorMode);

        setAutofillCompatibilityEnabled(application.isAutofillCompatibilityEnabled());
        enableAutofillCompatibilityIfNeeded();
    }

window創建完成后,在Activity的setContentView方法中,將View附加到Window中的DecorView上,

public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

window的唯一實作類為PhoneWindow,因此查看PhoneWindow的setContentView方法

public void setContentView(int layoutResID) {
        if (this.mContentParent == null) {
            //如果沒有DecorView,則創建
            this.installDecor();
        } else if (!this.hasFeature(12)) {
            this.mContentParent.removeAllViews();
        }

        if (this.hasFeature(12)) {
            Scene newScene = Scene.getSceneForLayout(this.mContentParent, layoutResID, this.getContext());
            this.transitionTo(newScene);
        } else {
            this.mLayoutInflater.inflate(layoutResID, this.mContentParent);
        }

        this.mContentParent.requestApplyInsets();
        android.view.Window.Callback cb = this.getCallback();
        if (cb != null && !this.isDestroyed()) {
            cb.onContentChanged();
        }

        this.mContentParentExplicitlySet = true;
    }

View被添加到Window中的DecorView后,Window并沒有馬上被添加,在Activity的onResume方法中,通過呼叫makeVisible方法才被添加,

void makeVisible() {
        if (!mWindowAdded) {
            ViewManager wm = getWindowManager();
            wm.addView(mDecor, getWindow().getAttributes());
            mWindowAdded = true;
        }
        mDecor.setVisibility(View.VISIBLE);
    }

Dialog的Window創建程序

1、創建Window

Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
        if (createContextThemeWrapper) {
            if (themeResId == ResourceId.ID_NULL) {
                final TypedValue outValue = https://www.cnblogs.com/milovetingting/p/new TypedValue();
                context.getTheme().resolveAttribute(R.attr.dialogTheme, outValue, true);
                themeResId = outValue.resourceId;
            }
            mContext = new ContextThemeWrapper(context, themeResId);
        } else {
            mContext = context;
        }

        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        //創建window
        final Window w = new PhoneWindow(mContext);
        mWindow = w;
        w.setCallback(this);
        w.setOnWindowDismissedCallback(this);
        w.setOnWindowSwipeDismissedCallback(() -> {
            if (mCancelable) {
                cancel();
            }
        });
        w.setWindowManager(mWindowManager, null, null);
        w.setGravity(Gravity.CENTER);

        mListenersHandler = new ListenersHandler(this);
    }

2、初始化DecorView并將Dialog的視圖添加到DecorView中

public void setContentView(@LayoutRes int layoutResID) {
        mWindow.setContentView(layoutResID);
    }

3、將DecorView添加到Window

public void show() {
        //...

        mWindowManager.addView(mDecor, l);
        mShowing = true;

        sendShowMessage();
    }

普通Dialog必須采用Activity的Context,

Toast的Window創建程序

Toast也是基于Window來實作,但由于Toast具有定時取消功能,所以系統采用了Handler,

Toast的顯示

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

在show方法中,通過IPC呼叫NotificationManager的enqueueToast方法

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

            if (ENABLE_BLOCKED_TOASTS && !isSystemToast &&
                    (!areNotificationsEnabledForPackage(pkg, Binder.getCallingUid())
                            || isPackageSuspended)) {
                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;
                    // All packages aside from the android package can enqueue one toast at a time
                    if (!isSystemToast) {
                        index = indexOfToastPackageLocked(pkg);
                    } else {
                        index = indexOfToastLocked(pkg, callback);
                    }

                    // If the package already has a toast, we update its toast
                    // in the queue, we don't move it to the end of the queue.
                    if (index >= 0) {
                        record = mToastQueue.get(index);
                        record.update(duration);
                        record.update(callback);
                    } else {
                        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);
                }
            }
        }

showNextToastLocked方法

    @GuardedBy("mToastQueue")
    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,即Toast中的TN物件,呼叫show方法

        @Override
        public void show(IBinder windowToken) {
            if (localLOGV) Log.v(TAG, "SHOW: " + this);
            mHandler.obtainMessage(SHOW, windowToken).sendToTarget();
        }

通過Handler發送訊息,然后在處理訊息的邏輯中呼叫了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 */
                }
            }
        }

在handleShow方法中,將View添加到了window,

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/39292.html

標籤:Android

上一篇:Android中通過Java代碼實作ScrollView滾動視圖-以歌詞滾動為例

下一篇:Android中使用Intent的Action和Data屬性實作點擊按鈕跳轉到撥打電話和發送短信

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【從零開始擼一個App】Dagger2

    Dagger2是一個IOC框架,一般用于Android平臺,第一次接觸的朋友,一定會被搞得暈頭轉向。它延續了Java平臺Spring框架代碼碎片化,注解滿天飛的傳統。嘗試將各處代碼片段串聯起來,理清思緒,真不是件容易的事。更不用說還有各版本細微的差別。 與Spring不同的是,Spring是通過反射 ......

    uj5u.com 2020-09-10 06:57:59 more
  • Flutter Weekly Issue 66

    新聞 Flutter 季度調研結果分享 教程 Flutter+FaaS一體化任務編排的思考與設計 詳解Dart中如何通過注解生成代碼 GitHub 用對了嗎?Flutter 團隊分享如何管理大型開源專案 插件 flutter-bubble-tab-indicator A Flutter librar ......

    uj5u.com 2020-09-10 06:58:52 more
  • Proguard 常用規則

    介紹 Proguard 入口,如何查看輸出,如何使用 keep 設定入口以及使用實體,如何配置壓縮,混淆,校驗等規則。

    ......

    uj5u.com 2020-09-10 06:59:00 more
  • Android 開發技術周報 Issue#292

    新聞 Android即將獲得類AirDrop功能:可向附近設備快速分享檔案 谷歌為安卓檔案管理應用引入可安全隱藏資料的Safe Folder功能 Android TV新主界面將顯示電影、電視節目和應用推薦內容 泄露的Android檔案暗示了傳說中的谷歌Pixel 5a與折疊屏新機 谷歌發布Andro ......

    uj5u.com 2020-09-10 07:00:37 more
  • AutoFitTextureView Error inflating class

    報錯: Binary XML file line #0: Binary XML file line #0: Error inflating class xxx.AutoFitTextureView 解決: <com.example.testy2.AutoFitTextureView android: ......

    uj5u.com 2020-09-10 07:00:41 more
  • 根據Uri,Cursor沒有獲取到對應的屬性

    Android: 背景:呼叫攝像頭,拍攝視頻,指定保存的地址,但是回傳的Cursor檔案,只有名稱和大小的屬性,沒有其他諸如時長,連ID屬性都沒有 使用 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATIO ......

    uj5u.com 2020-09-10 07:00:44 more
  • Android連載29-持久化技術

    一、持久化技術 我們平時所使用的APP產生的資料,在記憶體中都是瞬時的,會隨著斷電、關機等丟失資料,因此android系統采用了持久化技術,用于存盤這些“瞬時”資料 持久化技術包括:檔案存盤、SharedPreference存盤以及資料庫存盤,還有更復雜的SD卡記憶體儲。 二、檔案存盤 最基本存盤方式, ......

    uj5u.com 2020-09-10 07:00:47 more
  • Android Camera2Video整合到自己專案里

    背景: Android專案里呼叫攝像頭拍攝視頻,原本使用的 MediaStore.ACTION_VIDEO_CAPTURE, 后來因專案需要,改成了camera2 1.Camera2Video 官方demo有點問題,下載后,不能直接整合到專案 問題1.多次拍攝視頻崩潰 問題2.雙擊record按鈕, ......

    uj5u.com 2020-09-10 07:00:50 more
  • Android 開發技術周報 Issue#293

    新聞 谷歌為Android TV開發者提供多種新功能 Android 11將自動填表功能整合到鍵盤輸入建議中 谷歌宣布Android Auto即將支持更多的導航和數字停車應用 谷歌Pixel 5只有XL版本 搭載驍龍765G且將比Pixel 4更便宜 [圖]Wear OS將迎來重磅更新:應用啟動時間 ......

    uj5u.com 2020-09-10 07:01:38 more
  • 海豚星空掃碼投屏 Android 接收端 SDK 集成 六步驟

    掃碼投屏,開放網路,獨占設備,不需要額外下載軟體,微信掃碼,發現設備。支持標準DLNA協議,支持倍速播放。視頻,音頻,圖片投屏。好點意思。還支持自定義基于 DLNA 擴展的操作動作。好像要收費,沒體驗。 這里簡單記錄一下集成程序。 一 跟目錄的build.gradle添加私有mevan倉庫 mave ......

    uj5u.com 2020-09-10 07:01:43 more
最新发布
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:40:31 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:40:11 more
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:39:36 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:39:13 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:16:23 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:16:15 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:15:46 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:14:53 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:14:08 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:08:34 more