a亚洲精品_精品国产91乱码一区二区三区_亚洲精品在线免费观看视频_欧美日韩亚洲国产综合_久久久久久久久久久成人_在线区

首頁(yè) > 系統(tǒng) > Android > 正文

Android中WindowManager與WMS的解析

2019-10-21 21:30:21
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

最近在改bug的時(shí)候發(fā)現(xiàn)在windowManager.addView的時(shí)候會(huì)發(fā)生莫名其妙的崩潰,那個(gè)崩潰真的是讓你心態(tài)爆炸,潛心研究了兩天window相關(guān)的東西,雖然不是很深?yuàn)W的東西,本人也只是弄清楚了window的添加邏輯,在此分享給大家:

一、懸浮窗的概念

在android中,無(wú)論我們的app界面,還是系統(tǒng)桌面,再或者是手機(jī)下方的幾個(gè)虛擬按鍵和最上方的狀態(tài)欄,又或者是一個(gè)吐司。。。我們所看到的所有界面,都是由一個(gè)個(gè)懸浮窗口組成的。

但是這些窗口有不同的級(jí)別:

  1. 系統(tǒng)的是老大,是最高級(jí)別,你沒(méi)見(jiàn)過(guò)你下載的什么app把你的下拉菜單蓋住了吧-。=
  2. 其次是每一個(gè)應(yīng)用,都有自己的一個(gè)應(yīng)用級(jí)別窗口。
  3. 在應(yīng)用之內(nèi)能創(chuàng)建好多的界面,所以還有一種是應(yīng)用內(nèi)的窗口。

基于上述三種,android把懸浮窗劃分成三個(gè)級(jí)別,并通過(guò)靜態(tài)int型變量來(lái)表示:

    /**     * Start of system-specific window types. These are not normally     * created by applications.     **/    public static final int FIRST_SYSTEM_WINDOW   = 2000;    /**     * End of types of system windows.     **/    public static final int LAST_SYSTEM_WINDOW   = 2999;

2000~2999:在系統(tǒng)級(jí)別的懸浮窗范圍內(nèi),一般我們要想創(chuàng)建是需要申請(qǐng)權(quán)限。

    public static final int FIRST_SUB_WINDOW = 1000;    /**     * End of types of sub-windows.     **/    public static final int LAST_SUB_WINDOW = 1999;

1000~1999:子窗口級(jí)別的懸浮窗,他如果想要?jiǎng)?chuàng)建必須在一個(gè)父窗口下。

public static final int TYPE_BASE_APPLICATION  = 1;public static final int LAST_APPLICATION_WINDOW = 99;

1~99:應(yīng)用程序級(jí)別的懸浮窗,作為每個(gè)應(yīng)用程序的基窗口。

在每段的范圍內(nèi)都有眾多個(gè)窗口類型,這個(gè)具體就不說(shuō)了,因?yàn)樘嗔烁菊f(shuō)不完。。

但是說(shuō)了這么半天,懸浮窗到底是個(gè)啥東西,可能這個(gè)名詞聽(tīng)得很多,但是仔細(xì)想想android中用到的哪個(gè)控件還是哪個(gè)類叫懸浮窗?沒(méi)有吧,那么View總該知道吧(不知道別說(shuō)你是做android的)

其實(shí)說(shuō)白了懸浮窗就是一個(gè)被包裹的view。因?yàn)槌艘粋€(gè)view他還有很多的屬性:長(zhǎng)寬深度,類型,證書等等東西,只是屬性很多而且屬性之間的依賴關(guān)系有一些復(fù)雜而已。簡(jiǎn)單的來(lái)說(shuō)可以這么理解。

二、WindowManager介紹

上面簡(jiǎn)單介紹了懸浮窗的概念,而WindowManager是對(duì)懸浮窗進(jìn)行操作的一個(gè)媒介。

WindowManager是一個(gè)接口,他是繼承了ViewManager接口中的三個(gè)方法:

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

windowManage暴露給我們的只是這個(gè)三個(gè)方法,真的是簡(jiǎn)單粗暴,但是很實(shí)用。

這三個(gè)方法看名字就知道含義了,增刪改嘛,就不多說(shuō)啦。

而在上面提到的對(duì)于懸浮窗的三種分類,也是WindowManager的內(nèi)部類:WindowManager.LayoutParams,關(guān)于LayoutParams是什么在這里就不多說(shuō)了。這不是我們的重點(diǎn)。

我們平時(shí)想要添加一個(gè)懸浮窗,就會(huì)使用第一個(gè)方法:

  WindowManager windowManager = getWindowManager();  windowManager.addView(.....);

我們?cè)趃etWindowManager獲取的類,實(shí)際上是WindowManager的是WindowManager的實(shí)現(xiàn)類:WindowManagerImpl。接下來(lái)我們走一下添加懸浮窗的流程。

三、懸浮窗添加流程

入口肯定是從自己的addView中,上面說(shuō)到了WindowManager的實(shí)現(xiàn)類是WindowManagerImpl,來(lái)看一下:

    @Override    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {    applyDefaultToken(params);    mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);  }

這里有兩步:第一步是給layoutparams設(shè)置一個(gè)默認(rèn)的令牌(就是token這個(gè)屬性,至于這個(gè)干什么的等會(huì)再說(shuō))

  private void applyDefaultToken(@NonNull ViewGroup.LayoutParams params) {    // 設(shè)置條件:有默認(rèn)令牌,而且不是子窗口級(jí)別的懸浮窗    if (mDefaultToken != null && mParentWindow == null) {      if (!(params instanceof WindowManager.LayoutParams)) {        throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");      }      // 如果沒(méi)有令牌就設(shè)置默認(rèn)令牌      final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;      if (wparams.token == null) {        wparams.token = mDefaultToken;      }    }  }

然后調(diào)用了mGlobal的addView:

  public void addView(View view, ViewGroup.LayoutParams params,      Display display, Window parentWindow) {    /**進(jìn)行一系列判空操作。。。**/    if (parentWindow != null) {      parentWindow.adjustLayoutParamsForSubWindow(wparams);    } else {      // If there's no parent, then hardware acceleration for this view is      // set from the application's hardware acceleration setting.      final Context context = view.getContext();      if (context != null          && (context.getApplicationInfo().flags              & ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {        wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;      }    }    ViewRootImpl root;      root = new ViewRootImpl(view.getContext(), display);      view.setLayoutParams(wparams);      mViews.add(view);      mRoots.add(root);      mParams.add(wparams);      // do this last because it fires off messages to start doing things      try {        root.setView(view, wparams, panelParentView);      } catch (RuntimeException e) {        // BadTokenException or InvalidDisplayException, clean up.        if (index >= 0) {          removeViewLocked(index, true);        }        throw e;      }    }  }

看到WindowManagerGLobal中有三個(gè)屬性: mViews、mRoots、mParams,可以大膽猜測(cè)這個(gè)類中保存了我們進(jìn)程中的所有視圖以及相關(guān)屬性。在這里主要關(guān)注一下ViewRootImpl的這個(gè)實(shí)例對(duì)象root,接下來(lái)的會(huì)走進(jìn)root的setView中。

ViewRootImpl的setView方法內(nèi)容有點(diǎn)多,我這里就截取關(guān)鍵的兩部分:

1.

  int res; /** = WindowManagerImpl.ADD_OKAY; **/  try {    mOrigWindowType = mWindowAttributes.type;    mAttachInfo.mRecomputeGlobalAttributes = true;    collectViewAttributes();    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,        getHostVisibility(), mDisplay.getDisplayId(), mWinFrame,        mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,        mAttachInfo.mOutsets, mAttachInfo.mDisplayCutout, mInputChannel);

創(chuàng)建了一個(gè)名為res的int類型變量,他要獲取到的是懸浮窗添加的結(jié)果:成功或者失敗。

2.

    if (res < WindowManagerGlobal.ADD_OKAY) {        mAttachInfo.mRootView = null;        mAdded = false;        mFallbackEventHandler.setView(null);        unscheduleTraversals();        setAccessibilityFocus(null, null);        switch (res) {          case WindowManagerGlobal.ADD_BAD_APP_TOKEN:          case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:            throw new WindowManager.BadTokenException(                "Unable to add window -- token " + attrs.token                + " is not valid; is your activity running?");          case WindowManagerGlobal.ADD_NOT_APP_TOKEN:            throw new WindowManager.BadTokenException(                "Unable to add window -- token " + attrs.token                + " is not for an application");          case WindowManagerGlobal.ADD_APP_EXITING:            throw new WindowManager.BadTokenException(                "Unable to add window -- app for token " + attrs.token                + " is exiting");          case WindowManagerGlobal.ADD_DUPLICATE_ADD:            throw new WindowManager.BadTokenException(                "Unable to add window -- window " + mWindow                + " has already been added");          case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:            // Silently ignore -- we would have just removed it            // right away, anyway.            return;          case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:            throw new WindowManager.BadTokenException("Unable to add window "                + mWindow + " -- another window of type "                + mWindowAttributes.type + " already exists");          case WindowManagerGlobal.ADD_PERMISSION_DENIED:            throw new WindowManager.BadTokenException("Unable to add window "                + mWindow + " -- permission denied for window typ                  + mWindowAttributes.type);          case WindowManagerGlobal.ADD_INVALID_DISPLAY:              throw new WindowManager.InvalidDisplayException("Unable to add window "                  + mWindow + " -- the specified display can not be found");          case WindowManagerGlobal.ADD_INVALID_TYPE:              throw new WindowManager.InvalidDisplayException("Unable to add window "                  + mWindow + " -- the specified window type "                  + mWindowAttributes.type + " is not valid");        }        throw new RuntimeException(              "Unable to add window -- unknown error code " + res);      }

第二部分是res返回失敗的所有情況,在添加成功的時(shí)候res為OKAY,而非OKAY的情況就是上述情況。

接下來(lái)來(lái)看一下添加懸浮窗的操作,就是1中mWindowSession.addToDisplay。mWindowSession類型如下:

  final IWindowSession mWindowSession;

在這里其實(shí)用到了aidl跨進(jìn)程通信,最終執(zhí)行該方法的類是Session:

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

這個(gè)mService就是一個(gè)關(guān)鍵了系統(tǒng)類——WindowMamagerService(WMS)。到了這里我們簡(jiǎn)單過(guò)一下思路:在addView之后,通過(guò)WindowManagerGlobal進(jìn)行一些相關(guān)配置,傳入ViewRootImpl,再通過(guò)aidl方式發(fā)送給WMS系統(tǒng)服務(wù)。

可能有小伙伴會(huì)疑惑。好端端的為什么要用aidl實(shí)現(xiàn)?最開(kāi)始本人也有這個(gè)疑惑,但是后來(lái)想了想所有的窗口無(wú)論系統(tǒng)窗口還是第三方app,窗口都是要通過(guò)一個(gè)類去進(jìn)行添加允許判斷,這里使用aidl是在合適不過(guò)的了。我們接著看一下WMS的addWindow方法:

這個(gè)addWindow方法又是一段超長(zhǎng)的代碼,所以也就不全粘,說(shuō)一下他的簡(jiǎn)單流程吧,主要是分為三步:權(quán)限判斷、條件篩選、添加窗口

WMS的addWindow方法:

  int res = mPolicy.checkAddPermission(attrs, appOp);  if (res != WindowManagerGlobal.ADD_OKAY) {    return res;  }

首先進(jìn)行一個(gè)權(quán)限判斷,

final WindowManagerPolicy mPolicy;

WindowManagerPolicy的實(shí)現(xiàn)類是PhoneWindowManagerPolicy,看一下他的實(shí)現(xiàn):

又是小一百行的代碼,我們拆開(kāi)來(lái)看:

  //排除不屬于三種類型懸浮窗范圍內(nèi)的type  //很明顯的三段排除。  if (!((type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW)      || (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW)      || (type >= FIRST_SYSTEM_WINDOW && type <= LAST_SYSTEM_WINDOW))) {    return WindowManagerGlobal.ADD_INVALID_TYPE;  }  //不是系統(tǒng)級(jí)別的懸浮窗直接滿足條件  if (type < FIRST_SYSTEM_WINDOW || type > LAST_SYSTEM_WINDOW) {    return ADD_OKAY;  }    //以下幾種不是系統(tǒng)警告類型的系統(tǒng)彈窗,會(huì)滿足條件,除此之外的使用默認(rèn)判斷的方式    if (!isSystemAlertWindowType(type)) {      switch (type) {        case TYPE_TOAST:          outAppOp[0] = OP_TOAST_WINDOW;          return ADD_OKAY;        case TYPE_DREAM:        case TYPE_INPUT_METHOD:        case TYPE_WALLPAPER:        case TYPE_PRESENTATION:        case TYPE_PRIVATE_PRESENTATION:        case TYPE_VOICE_INTERACTION:        case TYPE_ACCESSIBILITY_OVERLAY:        case TYPE_QS_DIALOG:          // The window manager will check these.          return ADD_OKAY;      }      return mContext.checkCallingOrSelfPermission(INTERNAL_SYSTEM_WINDOW)          == PERMISSION_GRANTED ? ADD_OKAY : ADD_PERMISSION_DENIED;    }

后面的幾段代碼會(huì)頻繁出現(xiàn)最后的這段代碼:mContext.checkCallingOrSelfPermission,具體實(shí)現(xiàn)的類是ContextFixture:

    @Override    public int checkCallingOrSelfPermission(String permission) {      if (mPermissionTable.contains(permission)          || mPermissionTable.contains(PERMISSION_ENABLE_ALL)) {        logd("checkCallingOrSelfPermission: " + permission + " return GRANTED");        return PackageManager.PERMISSION_GRANTED;      } else {        logd("checkCallingOrSelfPermission: " + permission + " return DENIED");        return PackageManager.PERMISSION_DENIED;      }    }

這里會(huì)使用默認(rèn)權(quán)限判斷的方式,要么允許對(duì)應(yīng)權(quán)限,要么就是擁有全部權(quán)限,否則就會(huì)返回DENIED。

這個(gè)說(shuō)完接著回到checkPermission方法。

    //對(duì)于系統(tǒng)進(jìn)程直接滿足允許    final int callingUid = Binder.getCallingUid();    if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {      return ADD_OKAY;    }

說(shuō)實(shí)話下面這一段代碼我看的不是很明白,只是看到了這里對(duì)8.0之后做了版本限制,直接使用默認(rèn)檢查方式。

    ApplicationInfo appInfo;    try {      appInfo = mContext.getPackageManager().getApplicationInfoAsUser(              attrs.packageName,              0 /* flags */,              UserHandle.getUserId(callingUid));    } catch (PackageManager.NameNotFoundException e) {      appInfo = null;    }    if (appInfo == null || (type != TYPE_APPLICATION_OVERLAY && appInfo.targetSdkVersion >= O)) {            return (mContext.checkCallingOrSelfPermission(INTERNAL_SYSTEM_WINDOW)          == PERMISSION_GRANTED) ? ADD_OKAY : ADD_PERMISSION_DENIED;    }

這段是要從PackageManager中獲取ApplicationInfo,如果獲取失敗會(huì)拋出NameNotFound異常。所以下面的判斷是在異常的時(shí)候使用默認(rèn)權(quán)限處理方式。

最后還以一步檢查操作,關(guān)系不大就不看了。到這里checkPermission方法就結(jié)束了。

權(quán)限檢查的步驟已經(jīng)結(jié)束,接著就是根據(jù)上述獲取到的結(jié)果進(jìn)行條件篩選。

  if (res != WindowManagerGlobal.ADD_OKAY) {    return res;  }

首先在權(quán)限檢查的步驟獲取權(quán)限失敗,那么會(huì)直接返回,不會(huì)執(zhí)行條件篩選的步驟。而真正的條件篩選步驟代碼也是很多,我這里直接粘過(guò)來(lái)然后說(shuō)了。

      //111111111111111      if (!mDisplayReady) {        throw new IllegalStateException("Display has not been initialialized");      }      final DisplayContent displayContent = getDisplayContentOrCreate(displayId);      if (displayContent == null) {        Slog.w(TAG_WM, "Attempted to add window to a display that does not exist: "            + displayId + ". Aborting.");        return WindowManagerGlobal.ADD_INVALID_DISPLAY;      }      if (!displayContent.hasAccess(session.mUid)          && !mDisplayManagerInternal.isUidPresentOnDisplay(session.mUid, displayId)) {        Slog.w(TAG_WM, "Attempted to add window to a display for which the application "            + "does not have access: " + displayId + ". Aborting.");        return WindowManagerGlobal.ADD_INVALID_DISPLAY;      }      if (mWindowMap.containsKey(client.asBinder())) {        Slog.w(TAG_WM, "Window " + client + " is already added");        return WindowManagerGlobal.ADD_DUPLICATE_ADD;      }      //22222222222222      if (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW) {        parentWindow = windowForClientLocked(null, attrs.token, false);        if (parentWindow == null) {          Slog.w(TAG_WM, "Attempted to add window with token that is not a window: "             + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN;        }        if (parentWindow.mAttrs.type >= FIRST_SUB_WINDOW            && parentWindow.mAttrs.type <= LAST_SUB_WINDOW) {          Slog.w(TAG_WM, "Attempted to add window with token that is a sub-window: "              + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN;        }      }      //333333333333333      if (type == TYPE_PRIVATE_PRESENTATION && !displayContent.isPrivate()) {        Slog.w(TAG_WM, "Attempted to add private presentation window to a non-private display. Aborting.");        return WindowManagerGlobal.ADD_PERMISSION_DENIED;      }      //444444444444444      AppWindowToken atoken = null;      final boolean hasParent = parentWindow != null;      // Use existing parent window token for child windows since they go in the same token      // as there parent window so we can apply the same policy on them.      WindowToken token = displayContent.getWindowToken(          hasParent ? parentWindow.mAttrs.token : attrs.token);      // If this is a child window, we want to apply the same type checking rules as the      // parent window type.      final int rootType = hasParent ? parentWindow.mAttrs.type : type;      boolean addToastWindowRequiresToken = false;      if (token == null) {        if (rootType >= FIRST_APPLICATION_WINDOW && rootType <= LAST_APPLICATION_WINDOW) {          Slog.w(TAG_WM, "Attempted to add application window with unknown token "             + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }        if (rootType == TYPE_INPUT_METHOD) {          Slog.w(TAG_WM, "Attempted to add input method window with unknown token "             + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }        if (rootType == TYPE_VOICE_INTERACTION) {          Slog.w(TAG_WM, "Attempted to add voice interaction window with unknown token "             + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }        if (rootType == TYPE_WALLPAPER) {          Slog.w(TAG_WM, "Attempted to add wallpaper window with unknown token "             + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }        if (rootType == TYPE_DREAM) {          Slog.w(TAG_WM, "Attempted to add Dream window with unknown token "             + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }        if (rootType == TYPE_QS_DIALOG) {          Slog.w(TAG_WM, "Attempted to add QS dialog window with unknown token "             + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }        if (rootType == TYPE_ACCESSIBILITY_OVERLAY) {          Slog.w(TAG_WM, "Attempted to add Accessibility overlay window with unknown token "              + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }        if (type == TYPE_TOAST) {          // Apps targeting SDK above N MR1 cannot arbitrary add toast windows.          if (doesAddToastWindowRequireToken(attrs.packageName, callingUid,              parentWindow)) {            Slog.w(TAG_WM, "Attempted to add a toast window with unknown token "                + attrs.token + ". Aborting.");            return WindowManagerGlobal.ADD_BAD_APP_TOKEN;          }        }        final IBinder binder = attrs.token != null ? attrs.token : client.asBinder();        final boolean isRoundedCornerOverlay =            (attrs.privateFlags & PRIVATE_FLAG_IS_ROUNDED_CORNERS_OVERLAY) != 0;        token = new WindowToken(this, binder, type, false, displayContent,            session.mCanAddInternalSystemWindow, isRoundedCornerOverlay);      } else if (rootType >= FIRST_APPLICATION_WINDOW && rootType <= LAST_APPLICATION_WINDOW) {        atoken = token.asAppWindowToken();        if (atoken == null) {          Slog.w(TAG_WM, "Attempted to add window with non-application token "             + token + ". Aborting.");          return WindowManagerGlobal.ADD_NOT_APP_TOKEN;        } else if (atoken.removed) {          Slog.w(TAG_WM, "Attempted to add window with exiting application token "             + token + ". Aborting.");          return WindowManagerGlobal.ADD_APP_EXITING;        } else if (type == TYPE_APPLICATION_STARTING && atoken.startingWindow != null) {          Slog.w(TAG_WM, "Attempted to add starting window to token with already existing"              + " starting window");          return WindowManagerGlobal.ADD_DUPLICATE_ADD;        }      } else if (rootType == TYPE_INPUT_METHOD) {        if (token.windowType != TYPE_INPUT_METHOD) {          Slog.w(TAG_WM, "Attempted to add input method window with bad token "              + attrs.token + ". Aborting.");           return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }      } else if (rootType == TYPE_VOICE_INTERACTION) {        if (token.windowType != TYPE_VOICE_INTERACTION) {          Slog.w(TAG_WM, "Attempted to add voice interaction window with bad token "              + attrs.token + ". Aborting.");           return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }      } else if (rootType == TYPE_WALLPAPER) {        if (token.windowType != TYPE_WALLPAPER) {          Slog.w(TAG_WM, "Attempted to add wallpaper window with bad token "              + attrs.token + ". Aborting.");           return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }      } else if (rootType == TYPE_DREAM) {        if (token.windowType != TYPE_DREAM) {          Slog.w(TAG_WM, "Attempted to add Dream window with bad token "              + attrs.token + ". Aborting.");           return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }      } else if (rootType == TYPE_ACCESSIBILITY_OVERLAY) {        if (token.windowType != TYPE_ACCESSIBILITY_OVERLAY) {          Slog.w(TAG_WM, "Attempted to add Accessibility overlay window with bad token "              + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }      } else if (type == TYPE_TOAST) {        // Apps targeting SDK above N MR1 cannot arbitrary add toast windows.        addToastWindowRequiresToken = doesAddToastWindowRequireToken(attrs.packageName,            callingUid, parentWindow);        if (addToastWindowRequiresToken && token.windowType != TYPE_TOAST) {          Slog.w(TAG_WM, "Attempted to add a toast window with bad token "              + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }      } else if (type == TYPE_QS_DIALOG) {        if (token.windowType != TYPE_QS_DIALOG) {          Slog.w(TAG_WM, "Attempted to add QS dialog window with bad token "              + attrs.token + ". Aborting.");          return WindowManagerGlobal.ADD_BAD_APP_TOKEN;        }      } else if (token.asAppWindowToken() != null) {        Slog.w(TAG_WM, "Non-null appWindowToken for system window of rootType=" + rootType);        // It is not valid to use an app token with other system types; we will        // instead make a new token for it (as if null had been passed in for the token).        attrs.token = null;        token = new WindowToken(this, client.asBinder(), type, false, displayContent,            session.mCanAddInternalSystemWindow);      }      //5555555555555      final WindowState win = new WindowState(this, session, client, token, parentWindow,          appOp[0], seq, attrs, viewVisibility, session.mUid,          session.mCanAddInternalSystemWindow);      if (win.mDeathRecipient == null) {        // Client has apparently died, so there is no reason to        // continue.        Slog.w(TAG_WM, "Adding window client " + client.asBinder()            + " that is dead, aborting.");        return WindowManagerGlobal.ADD_APP_EXITING;      }      if (win.getDisplayContent() == null) {        Slog.w(TAG_WM, "Adding window to Display that has been removed.");        return WindowManagerGlobal.ADD_INVALID_DISPLAY;      }      final boolean hasStatusBarServicePermission =          mContext.checkCallingOrSelfPermission(permission.STATUS_BAR_SERVICE)              == PackageManager.PERMISSION_GRANTED;      mPolicy.adjustWindowParamsLw(win, win.mAttrs, hasStatusBarServicePermission);      win.setShowToOwnerOnlyLocked(mPolicy.checkShowToOwnerOnly(attrs));      res = mPolicy.prepareAddWindowLw(win, attrs);      if (res != WindowManagerGlobal.ADD_OKAY) {        return res;      }      final boolean openInputChannels = (outInputChannel != null          && (attrs.inputFeatures & INPUT_FEATURE_NO_INPUT_CHANNEL) == 0);      if (openInputChannels) {        win.openInputChannel(outInputChannel);      }      //666666666666666      if (type == TYPE_TOAST) {        if (!getDefaultDisplayContentLocked().canAddToastWindowForUid(callingUid)) {          Slog.w(TAG_WM, "Adding more than one toast window for UID at a time.");          return WindowManagerGlobal.ADD_DUPLICATE_ADD;        }                if (addToastWindowRequiresToken            || (attrs.flags & LayoutParams.FLAG_NOT_FOCUSABLE) == 0            || mCurrentFocus == null            || mCurrentFocus.mOwnerUid != callingUid) {          mH.sendMessageDelayed(              mH.obtainMessage(H.WINDOW_HIDE_TIMEOUT, win),              win.mAttrs.hideTimeoutMilliseconds);        }      }

這里講篩選部分大體分成這么幾個(gè)步驟:

  1. 系統(tǒng)以及初始化的一些判斷:就像最開(kāi)始的四個(gè)判斷。
  2. 子窗口類型時(shí)候的對(duì)父窗口的相關(guān)篩選(父是否為空,以及父親的類型判斷)
  3. 一種特殊的私有類型條件篩選,該類型屬于系統(tǒng)類型
  4. 涉及證書(token)的窗口類型條件篩選。
  5. 狀態(tài)欄權(quán)限條件篩選
  6. 吐司類型的條件篩選

在代碼中對(duì)應(yīng)的步驟有明確的標(biāo)注,而具體的代碼大多只是一些判斷,所以在感覺(jué)沒(méi)有細(xì)說(shuō)的必要了。

在條件篩選完成之后,剩下的類型都是符合添加的類型,從現(xiàn)在開(kāi)始就開(kāi)始對(duì)不同的type進(jìn)行不同的添加。經(jīng)過(guò)多到加工后,將OKAY返回。

如果能從添加窗口的步驟返回,就說(shuō)明一定是OKAY的。那么我們可以一步步跳回層層調(diào)用的代碼,最終在ViewRootImpl中,對(duì)沒(méi)有添加成功的拋出異常。

      if (res < WindowManagerGlobal.ADD_OKAY) {          mAttachInfo.mRootView = null;          mAdded = false;          mFallbackEventHandler.setView(null);          unscheduleTraversals();          setAccessibilityFocus(null, null);          switch (res) {            case WindowManagerGlobal.ADD_BAD_APP_TOKEN:            case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:              throw new WindowManager.BadTokenException(                  "Unable to add window -- token " + attrs.token                  + " is not valid; is your activity running?");            case WindowManagerGlobal.ADD_NOT_APP_TOKEN:              throw new WindowManager.BadTokenException(                  "Unable to add window -- token " + attrs.token                  + " is not for an application");            case WindowManagerGlobal.ADD_APP_EXITING:              throw new WindowManager.BadTokenException(                  "Unable to add window -- app for token " + attrs.token                  + " is exiting");            case WindowManagerGlobal.ADD_DUPLICATE_ADD:              throw new WindowManager.BadTokenException(                  "Unable to add window -- window " + mWindow                  + " has already been added");            case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:              // Silently ignore -- we would have just removed it              // right away, anyway.              return;            case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:              throw new WindowManager.BadTokenException("Unable to add window "                  + mWindow + " -- another window of type "                  + mWindowAttributes.type + " already exists");            case WindowManagerGlobal.ADD_PERMISSION_DENIED:              throw new WindowManager.BadTokenException("Unable to add window "                  + mWindow + " -- permission denied for window type "                  + mWindowAttributes.type);            case WindowManagerGlobal.ADD_INVALID_DISPLAY:              throw new WindowManager.InvalidDisplayException("Unable to add window "                  + mWindow + " -- the specified display can not be found");            case WindowManagerGlobal.ADD_INVALID_TYPE:              throw new WindowManager.InvalidDisplayException("Unable to add window "                  + mWindow + " -- the specified window type "                  + mWindowAttributes.type + " is not valid");          }          throw new RuntimeException(              "Unable to add window -- unknown error code " + res);        }

對(duì)于OKAY的,在ViewRootImpl中會(huì)做一些其他的操作,反正我是沒(méi)看懂-。=、

四、小結(jié)

到這里WMS的添加懸浮窗口的流程差不多就過(guò)了一遍了。可能有些地方說(shuō)的不是很細(xì),大家下來(lái)可以關(guān)注一下個(gè)別幾個(gè)點(diǎn)。整個(gè)過(guò)程有這么幾個(gè)需要強(qiáng)調(diào)的地方。

  • 函數(shù)循環(huán)嵌套,共同消費(fèi)返回值。
  • 異常循環(huán)嵌套
  • 個(gè)別地方對(duì)M和O以上的系統(tǒng)進(jìn)行了限制

如果在添加懸浮窗的時(shí)候使用了不同的type,可能會(huì)發(fā)生異常:本人拿了一個(gè)8.0的手機(jī),分別對(duì)窗口type設(shè)置為OVERLAY和ERROR。因?yàn)镋RROR類型是被棄用的,我發(fā)現(xiàn)使用ERROR會(huì)拋出異常,而OVERLAY不會(huì)。同樣的拿了一個(gè)6.0的手機(jī)添加ERROR類型就沒(méi)有異常拋出,肯定是上述的問(wèn)題導(dǎo)致的,但是具體在哪一塊我還沒(méi)有找到,因?yàn)檎麄€(gè)流程的出口太多了-。=。

此外在WindowManagerGlobal.addView方法中,有一個(gè)地方:

  if (parentWindow != null) {    parentWindow.adjustLayoutParamsForSubWindow(wparams);  } else {

這個(gè)方法是對(duì)于有子窗口類型的證書處理,網(wǎng)上查了一下該方法在四點(diǎn)幾、六點(diǎn)幾和8.0是不同的,也就是說(shuō)對(duì)證書的處理方式變化了,這里本人還沒(méi)有細(xì)看,有興趣的盆友可以研究一下然后評(píng)論交流一番。

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)VEVB武林網(wǎng)的支持。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到Android開(kāi)發(fā)頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 中文字幕av亚洲精品一部二部 | 日视频 | 中文字幕在线观看www | 日本在线观看一区二区 | 色婷婷免费 | 中文字幕一区二区三区四区五区 | 久草毛片 | 国产一级免费 | 欧美日韩成人影院 | 日本久久久 | 91在线电影 | 国产精品久久国产精品 | 黄色片在线免费看 | 视频精品一区 | 国产精品亚洲成在人线 | 狠狠综合久久 | www夜夜操com| 中文字幕一区二区三区日韩精品 | 黄网站免费在线观看 | 亚洲一区成人在线观看 | 在线视频97 | 久久国产婷婷国产香蕉 | 一区二区影视 | 久久久久久久久久久网站 | 色婷婷av一区二区三区软件 | 91资源在线 | 精品视频在线观看 | 日韩国产一区 | 欧美乱码精品一区二区三 | 看a网站 | 亚洲精品国产第一综合99久久 | 国产一区二区三区视频在线观看 | www婷婷av久久久影片 | 欧美a级成人淫片免费看 | 国产成人久久精品麻豆二区 | 久久性| 亚洲一区免费 | 91在线视频在线观看 | 精品无码久久久久久国产 | 91一区| 国产a一三三四区电影 |