Android startActivity流程分析(二) onCreate,onStart,onResume Android 10 [API 29]

接着Android startActivity流程剖析(一) Android 10 [API 29] 中的Activity#attach完结后。

startActivity还包括onCreate、onStart、onResume,逐一剖析。

Android startActivity<span class=线程和进程的区别是什么流程剖析(二) onCWindowsreate,ogooglenStart,onResume Android 10 [API 29]” src=”https://www.6hu.cc/wp-content/uploads/2022/07/4c0b9a295570213fe3approach307b7fa7d86271.png”>

onC初始化sdk什么意思reate()

Activity#onCreate中主要是进行Create事情的回调,包括Fragmen线程和进程的区别是什么tManager初始化磁盘及ActivityL线程池的七个参数ifecycleCallbacks

protected void onCreate(@Nullable Bundle savedInstanceState) {
     ....
    mFragments.dispatchCreate();
    dispatchActivityCreated(savedInstanceState);
     ...
    mCalled = true;
   }

Activity#setContentViewindows7旗舰版w

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

这儿getapproveWindow()回approve来的是PhoneWindow目标,进入PhoneWindow的setContentView其间主要为以下2项

  1. installDecor(),初始化DecorVie公司让员工下班发手机电量截图w,同时mContentParent也被赋值
  2. mLayoutInfl线程的几种状态ater.inflate(layoutResID, mContentParent);构建View

注:使用appcompat下的AppCompatActivitwindows系统y后流程会有差异,但全体逻辑不同不大

PhoneWindow.java
 
public void setContentView(int layoutResID) {
  if (mContentParent == null) {
    installDecor();
   } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
    mContentParent.removeAllViews();
   }
   ....
    mLayoutInflater.inflate(layoutResID, mContentParent);
    ....
  mContentParent.requestApplyInsets();
 // Activity#attach时,mWindow.setCallback(this),所以此处调用的为Activity#onContentChanged
  final Callback cb = getCallback();
  if (cb != null && !isDestroyed()) {
    cb.onContentChanged();
   }
  mContentParentExplicitlySet = true;
}
PhoneWinwindows是什么意思dow#ingooglestallDecor

构建了DecorView,并初始化mContentParent,mContentParent的id为ID_ANDROID_CONTENT

ViewGroup cont初始化电脑时出现问题entParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);

查看是否有title,有的话是否要躲藏。

private void installDecor() {
  mForceDecorInstall = false;
  if (mDecor == null) {
    mDecor = generateDecor(-1);
    mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
    mDecor.setIsRootNamespace(true);
    if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
      mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
     }
   } else {
    mDecor.setWindow(this);
   }
  if (mContentParent == null) {
    mContentParent = generateLayout(mDecor);
    // Set up decor part of UI to ignore fitsSystemWindows if appropriate.
    mDecor.makeOptionalFitsSystemWindows();
     ....
     //初始化title
      mTitleView = findViewById(R.id.title);
      if (mTitleView != null) {
       // 查看mLocalFeatures的第FEATURE_NO_TITLE位是否为1,为0的话躲藏titleContainer
        if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
          final View titleContainer = findViewById(R.id.title_container);
          if (titleContainer != null) {
            titleContainer.setVisibility(View.GONE);
           } else {
            mTitleView.setVisibility(View.GONE);
           }
          mContentParent.setForeground(null);
         } else {
          mTitleView.setText(mTitle);
         }
       }
     }
     ....
   }
}
L初始化磁盘ayout线程数是什么Inflater.inflate线程是什么意思()

mLayoutInflater.inflate(layoutResID, mCont工资超过5000怎么扣税entParent); 这儿用到了两个参数的重载,即Inflate指定的layout线程撕裂者并增加到mConten初始化磁盘tParent中。

onStart()

第二步:performLifecycleSequence,其间计算start、finish之间的状态,并调用ActivityThread的handleStartActivity

TransactionExecutor.java
 
private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
      ClientTransaction transaction) {
    final int start = r.getLifecycleState();
     ....
     //这儿start为1:ON_CREATE,finish为3:ON_RESUME计算后path中包括2:ON_START
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    performLifecycleSequence(r, path, transaction);
   }
​
private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
      ClientTransaction transaction) {
    final int size = path.size();
    for (int i = 0, state; i < size; i++) {
      state = path.get(i);
       ......
      switch (state) {
        case ON_CREATE:
          mTransactionHandler.handleLaunchActivity(r, mPendingActions,
              null /* customIntent */);
          break;
        case ON_START:
        //调用ActivityThread的handleStartActivity
          mTransactionHandler.handleStartActivity(r, mPendingActions);
          break;
        case ON_RESUME:
          mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
              r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
          break;
         .......
   }

Ac初始化英文tivityThread#handleStartActiwindows许可证即将过期怎么办vity中开始Act初始化电脑的后果ivity的start

ActivityThread.java
 
public void handleStartActivity(ActivityClientRecord r,
      PendingTransactionActions pendingActions) {
    final Activity activity = r.activity;
     .....
    // Start
    activity.performStart("handleStartActivity");
    r.setState(ON_START);
     .....
   }

后续履行Activity#performStart并经过Instrumentation调用activity的onStart完结start流程。

onResume()

在TransactionExecutor的第三步,也便是lifecycleItem.execute,即履行ResumeActiv宫颈癌ityIte线程池面试题m的execute。进入了ActivityThread的handleResumeActivity

public void execute(ClientTransactionHandler client, IBinder token,
      PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
    client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
        "RESUME_ACTIVITY");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
   }

handleResumeActivity线程池

1.调用了Activity的performResume经过Instr宫颈癌umentation#callActivityOnResume回调Activity的onResume。并更新ActivityClientRecord的state为ON_RESUME

2.将Window中的DecorView赋值给Acti初始化游戏启动器失败vity的成员变量mDecor,经过WindowManagerGlobal#addView将DecorView加入到WMS中。

ActivityThread.java
 
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
      String reason) {
     ....
    // TODO Push resumeArgs into the activity for consideration
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
     ......
    final Activity a = r.activity;
     ......
    if (r.window == null && !a.mFinished && willBeVisible) {
      r.window = r.activity.getWindow();
      View decor = r.window.getDecorView();
      decor.setVisibility(View.INVISIBLE);
      ViewManager wm = a.getWindowManager();
      WindowManager.LayoutParams l = r.window.getAttributes();
      a.mDecor = decor;
       ......
      if (a.mVisibleFromClient) {
        if (!a.mWindowAdded) {
          a.mWindowAdded = true;
          wm.addView(decor, l);
         } else {
       .....
     }
     .....
   }

WindowManagerappetiteImpl#addView流程

其间较为重要的有Go三点:

  1. 创立ViewRootImpl

    其间有个细节是会对成员变量mThreadwindows更新有必要吗赋值为当前线程,也便是主线程,后续其间的方法调用大多都会调用checkThread查appearance看从哪个线程来的,若不是主线程则会抛出反常。

    ViewRootImpl.java
    public ViewRootImpl(Context context, Display display) {
      mThread = Thread.currentThread();
    }
    ​
    void checkThread() {
        if (mThread != Thread.currentThread()) {
          throw new CalledFromWrongThreadException(
              "Only the original thread that created a view hierarchy can touch its views.");
         }
       }
    
  2. 构建DecorView、ViewRootImpl、WindowManager初始化是什么意思.LayoutParams的对应关系

  3. 增加到WMS并显现

ViewManager目标wm是经过a.getWindowManager()得到的,其初始化参阅attach流程。wm.addView(decor, l);调用的为

WindowManagerImpl#addView() -&g线程撕裂者t; WindowManagerGloba初始化sdk什么意思l.addView()

WindowManagerGwindows系统lobal是App侧的单例,其间mViews、mRoots、mParams分别保存着App内的一切DecorView及与之对应的ViewRootImp线程池的七个参数l、WindowMan工商银行ager.LayoutParams。

WindowManagerGlobal.java
 
public void addView(View view, ViewGroup.LayoutParams params,
    Display display, Window parentWindow) {
   ......
  ViewRootImpl root;
  View panelParentView = null;
​
  synchronized (mLock) {
     ....
    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);
     .......
   }
}

增加完后进入ViewRootImpl#setView

ViewRootImpl.java
 
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
  synchronized (this) {
    if (mView == null) {
      mView = view;
       .....
      // Schedule the first layout -before- adding to the window
      // manager, to make sure we do the relayout before receiving
      // any other events from the system.
      requestLayout();
       ....
        res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
            getHostVisibility(), mDisplay.getDisplayId(), mTmpFrame,
            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
            mAttachInfo.mOutsets, mAttachInfo.mDisplayCutout, mInputChannel,
            mTempInsets);
        setFrame(mTmpFrame);
       .....
   }
}

其间主要做了两件事

  1. requestLayout()

    appstore看线程,标记状态后进入scheduleTraversals()

    public void requestLayout() {
      if (!mHandlingLayoutInLayoutRequest) {
        checkThread();
        mLayoutRequested = true;
        scheduleTraversals();
       }
    }
    

    scheduleTraversals()

    1. 增加同步屏障
    2. mChoreograpproveapher.postCallback,将mTraversalRunnable加入到Choreograph宫颈癌er类的mCallbackQueues中
    void scheduleTraversals() {
      if (!mTraversalScheduled) {
        mTraversalScheduled = true;
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
        mChoreographer.postCallback(
            Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
         .......
       }
    }
    

    下一个VSync脉冲到来回调FrameDisplayEventReceiver#onVsync后进入Cwindows11有必要升级吗horeographer的doFrame,在其间调用doCallbacks履行一线程数是什么切类型为Choreographer.CALLBACK_TRAVERSAL的callback,即ViewRootImpl中的TraversalRunnable

    void doFrame(long frameTimeNanos, int frame) {
       .....
      try {
         .....
        mFrameInfo.markPerformTraversalsStart();
        doCallbacks(Choreographer.CALLBACK_TRAVERSAL, frameTimeNanos);
        doCallbacks(Choreographer.CALLBACK_COMMIT, frameTimeNanos);
       } finally {
        AnimationUtils.unlockAnimationClock();
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
       }
       ....
    }
    

    ViewRoo公积金tImpl.TraversalRunnaapproachble

    final class TraversalRunnable implements Runnable {
      @Override
      public void run() {
        doTraversal();
       }
    }
    

    ViewRootImpl#doTraversal()

    其间包括两步

    1.removeSyn工商银行cBarriappearer铲除内存屏障让一切消息都得以履行

    2.performTraversals

    void doTraversal() {
      if (mTraversalScheduled) {
        mTraversalScheduled = false;
        mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
        ......
        performTraversals();
        ......
       }
    }
    

    ViewRootImpl#perform工龄越长退休金越多吗Traversals

    perapproveformTraversals中包括了对View及其子View的Measure、Layout、Draw操作,View完结展现。

    private void performTraversals() {
       .....
        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
        ....
        performLayout(lp, mWidth, mHeight);
       .....
        performDraw();
       .....
    ​
      mIsInTraversal = false;
    }
    
  2. mWindowSession.addToDisplay 这儿的mWindowSession是经过WindowManagerGlobal.getWindowSession()赋值的,其实现为server下的Session类

    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,
        InsetsState outInsetsState) {
      return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId, outFrame,
          outContentInsets, outStableInsets, outOutsets, outDisplayCutout, outInputChannel,
          outInsetsState);
    }
    

    最终调用的是WMS的addWin初始化英文dow进行增加

总结

onCreate过程中创立了DecorView并解析传入的布局文件增加到DecorView。

o初始化nStarAPPt回调在Activity对用户可见时,前后台切换场景的逻辑较多在此处理。

onResume中包括

  1. 将Activity中的mDecor与Window中decor关联
  2. WindowManagerGlobal中建立ViewRootImpl、DecorView、WindowManager.LayoutParams的关联
  3. 调用ViewRootImpl#segoogletView,将ViewRootImpl包装线程为IWindow增加到WMS中,并调用requestLayout显现UI

发表评论

提供最优质的资源集合

立即查看 了解详情