// frameworks/base/services/core/java/com/android/server/am/ClientLifecycleManager.java voidscheduleTransaction(ClientTransaction transaction)throws RemoteException {final IApplicationThread client = transaction.getClient();
transaction.schedule();if(!(client instanceofBinder)){// If client is not an instance of Binder - it's a remote call and at this point it is// safe to recycle the object. All objects used for local calls will be recycled after// the transaction is executed on client in ActivityThread.
transaction.recycle();}}
// // frameworks/base/core/java/android/app/ActivityThread.java publicvoidhandleMessage(Message msg){if(DEBUG_MESSAGES) Slog.v(TAG,">>> handling: "+codeToString(msg.what));switch(msg.what){....case EXECUTE_TRANSACTION:final ClientTransaction transaction =(ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);if(isSystem()){// Client transactions inside system process are recycled on the client side// instead of ClientLifecycleManager to avoid being cleared before this// message is handled.
transaction.recycle();}// TODO(lifecycler): Recycle locally scheduled transactions.break;....}}
// frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.javaprivatevoidexecuteLifecycleState(ClientTransaction transaction){final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();if(lifecycleItem == null){// No lifecycle request, return early.return;}log("Resolving lifecycle state: "+ lifecycleItem);final IBinder token = transaction.getActivityToken();// 创建ActivityClientRecord记录Activity,App进程的ActivityClientRecord和AMS中的ActivityRecord是一一对应的,他们之间通过token关联final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);if(r == null){// Ignore requests for non-existent client records for now.return;}// lifecycleItem.getTargetState()返回的是ON_RESUME// Cycle to the state right before the final requested state.cycleToPath(r, lifecycleItem.getTargetState(),true/* excludeLastState */);// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);}
// frameworks/base/core/java/android/app/ActivityThread.java public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent){// If we are getting ready to gc after going to the background, well// we are back active so skip it.unscheduleGcIdler();
mSomeActivitiesChanged =true;// 性能相关if(r.profilerInfo != null){
mProfiler.setProfiler(r.profilerInfo);
mProfiler.startProfiling();}// Make sure we are running with the most recent config.handleConfigurationChanged(null, null);if(localLOGV) Slog.v(
TAG,"Handling launch of "+ r);// Initialize before creating the activityif(!ThreadedRenderer.sRendererDisabled){
GraphicsEnvironment.earlyInitEGL();}// initialize函数主要是在WindowManagerGlobal中获取WindowManagerService的代理
WindowManagerGlobal.initialize();final Activity a =performLaunchActivity(r, customIntent);// Configuration相关if(a != null){
r.createdConfig =newConfiguration(mConfiguration);reportSizeConfigurations(r);if(!r.activity.mFinished && pendingActions != null){
pendingActions.setOldState(r.state);
pendingActions.setRestoreInstanceState(true);
pendingActions.setCallOnPostCreate(true);}}else{// If there was an error, for any reason, tell the activity manager to stop us.try{
ActivityManager.getService().finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);}catch(RemoteException ex){throw ex.rethrowFromSystemServer();}}return a;}
// frameworks/base/core/java/com/android/internal/policy/PhoneWindow.javapublicvoidsetContentView(int layoutResID){// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window// decor, when theme attributes and the like are crystalized. Do not check the feature// before this happens.if(mContentParent == null){installDecor();}elseif(!hasFeature(FEATURE_CONTENT_TRANSITIONS)){
mContentParent.removeAllViews();}if(hasFeature(FEATURE_CONTENT_TRANSITIONS)){final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,getContext());transitionTo(newScene);}else{// 调用LayoutInflater的inflate方法解析布局文件,并生成View树,mContentParent为View树的根节点
mLayoutInflater.inflate(layoutResID, mContentParent);}
mContentParent.requestApplyInsets();final Callback cb =getCallback();if(cb != null &&!isDestroyed()){
cb.onContentChanged();}
mContentParentExplicitlySet =true;}
// frameworks/base/core/java/com/android/internal/policy/PhoneWindow.javaprotected DecorView generateDecor(int featureId){// System process doesn't have application context and in that case we need to directly use// the context we have. Otherwise we want the application context, so we don't cling to the// activity.
Context context;if(mUseDecorContext){
Context applicationContext =getContext().getApplicationContext();if(applicationContext == null){
context =getContext();}else{
context =newDecorContext(applicationContext,getContext());if(mTheme !=-1){
context.setTheme(mTheme);}}}else{
context =getContext();}returnnewDecorView(context, featureId,this,getAttributes());}
// frameworks/base/core/java/android/app/ActivityThread.java publicvoidhandleResumeActivity(IBinder token,boolean finalStateRequest,boolean isForward,
String reason){// If we are getting ready to gc after going to the background, well// we are back active so skip it.unscheduleGcIdler();
mSomeActivitiesChanged =true;// 调用performResumeActivity执行Activity的onResume,并根据token获取前面创建的ActivityClientRecord// TODO Push resumeArgs into the activity for considerationfinal ActivityClientRecord r =performResumeActivity(token, finalStateRequest, reason);if(r == null){// We didn't actually resume the activity, so skipping any follow-up actions.return;}final Activity a = r.activity;if(localLOGV){
Slog.v(TAG,"Resume "+ r +" started activity: "+ a.mStartedActivity
+", hideForNow: "+ r.hideForNow +", finished: "+ a.mFinished);}finalint forwardBit = isForward
? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION :0;// If the window hasn't yet been added to the window manager,// and this guy didn't finish itself or start another activity,// then go ahead and add the window.boolean willBeVisible =!a.mStartedActivity;if(!willBeVisible){try{
willBeVisible = ActivityManager.getService().willActivityBeVisible(
a.getActivityToken());}catch(RemoteException e){throw e.rethrowFromSystemServer();}}if(r.window == null &&!a.mFinished && willBeVisible){// 获取window
r.window = r.activity.getWindow();// 获取DecorView
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);// 获取WindowManager对象
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;if(r.mPreserveWindow){
a.mWindowAdded =true;
r.mPreserveWindow =false;// Normally the ViewRoot sets up callbacks with the Activity// in addView->ViewRootImpl#setView. If we are instead reusing// the decor view we have to notify the view root that the// callbacks may have changed.
ViewRootImpl impl = decor.getViewRootImpl();if(impl != null){
impl.notifyChildRebuilt();}}if(a.mVisibleFromClient){if(!a.mWindowAdded){
a.mWindowAdded =true;// 调用WindowManager的addView方法
wm.addView(decor, l);}else{// The activity will get a callback for this {@link LayoutParams} change// earlier. However, at that time the decor will not be set (this is set// in this method), so no action will be taken. This call ensures the// callback occurs with the decor set.
a.onWindowAttributesChanged(l);}}....}
// frameworks/base/core/java/android/view/ViewRootImpl.java privateintrelayoutWindow(WindowManager.LayoutParams params,int viewVisibility,boolean insetsPending)throws RemoteException {float appScale = mAttachInfo.mApplicationScale;boolean restore =false;if(params != null && mTranslator != null){
restore =true;
params.backup();
mTranslator.translateWindowLayout(params);}if(params != null){if(DBG) Log.d(mTag,"WindowLayout in layoutWindow:"+ params);if(mOrigWindowType != params.type){// For compatibility with old apps, don't crash here.if(mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH){
Slog.w(mTag,"Window type can not be changed after "+"the window is added; ignoring change of "+ mView);
params.type = mOrigWindowType;}}}long frameNumber =-1;if(mSurface.isValid()){
frameNumber = mSurface.getNextFrameNumber();}int relayoutResult = mWindowSession.relayout(mWindow, mSeq, params,(int)(mView.getMeasuredWidth()* appScale +0.5f),(int)(mView.getMeasuredHeight()* appScale +0.5f), viewVisibility,
insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING :0, frameNumber,
mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
mPendingStableInsets, mPendingOutsets, mPendingBackDropFrame, mPendingDisplayCutout,
mPendingMergedConfiguration, mSurface);
mPendingAlwaysConsumeNavBar =(relayoutResult & WindowManagerGlobal.RELAYOUT_RES_CONSUME_ALWAYS_NAV_BAR)!=0;if(restore){
params.restore();}if(mTranslator != null){
mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);}return relayoutResult;}
调用了WindowSession.relayout函数
// frameworks/base/services/core/java/com/android/server/wm/Session.javapublicintrelayout(IWindow window,int seq, WindowManager.LayoutParams attrs,int requestedWidth,int requestedHeight,int viewFlags,int flags,long frameNumber,
Rect outFrame, Rect outOverscanInsets, Rect outContentInsets, Rect outVisibleInsets,
Rect outStableInsets, Rect outsets, Rect outBackdropFrame,
DisplayCutout.ParcelableWrapper cutout, MergedConfiguration mergedConfiguration,
Surface outSurface){if(false) Slog.d(TAG_WM,">>>>>> ENTERED relayout from "+ Binder.getCallingPid());
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, mRelayoutTag);int res = mService.relayoutWindow(this, window, seq, attrs,
requestedWidth, requestedHeight, viewFlags, flags, frameNumber,
outFrame, outOverscanInsets, outContentInsets, outVisibleInsets,
outStableInsets, outsets, outBackdropFrame, cutout,
mergedConfiguration, outSurface);
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);if(false) Slog.d(TAG_WM,"<<<<<< EXITING relayout to "+ Binder.getCallingPid());return res;}
调用了WindowManagerService的relayoutWindow函数
// frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.javapublicintrelayoutWindow(Session session, IWindow client,int seq, LayoutParams attrs,int requestedWidth,int requestedHeight,int viewVisibility,int flags,long frameNumber, Rect outFrame, Rect outOverscanInsets, Rect outContentInsets,
Rect outVisibleInsets, Rect outStableInsets, Rect outOutsets, Rect outBackdropFrame,
DisplayCutout.ParcelableWrapper outCutout, MergedConfiguration mergedConfiguration,// 这里的Surface用outSurface命名,那猜测outSurface应该是一个输出型参数,后面会有说明
Surface outSurface){int result =0;boolean configChanged;finalboolean hasStatusBarPermission =
mContext.checkCallingOrSelfPermission(permission.STATUS_BAR)== PackageManager.PERMISSION_GRANTED;finalboolean hasStatusBarServicePermission =
mContext.checkCallingOrSelfPermission(permission.STATUS_BAR_SERVICE)== PackageManager.PERMISSION_GRANTED;long origId = Binder.clearCallingIdentity();finalint displayId;synchronized(mWindowMap){// 根据IWindow对象查找对应的WindowState
WindowState win =windowForClientLocked(session, client,false);if(win == null){return0;}
displayId = win.getDisplayId();
WindowStateAnimator winAnimator = win.mWinAnimator;if(viewVisibility != View.GONE){
win.setRequestedSize(requestedWidth, requestedHeight);}....try{
result =createSurfaceControl(outSurface, result, win, winAnimator);}catch(Exception e){
mInputMonitor.updateInputWindowsLw(true/*force*/);
Slog.w(TAG_WM,"Exception thrown when creating surface for client "+ client +" ("+ win.mAttrs.getTitle()+")",
e);
Binder.restoreCallingIdentity(origId);return0;}....return result;}
我们只关注createSurfaceControl这个函数
// frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.javaprivateintcreateSurfaceControl(Surface outSurface,int result, WindowState win,
WindowStateAnimator winAnimator){if(!win.mHasSurface){
result |= RELAYOUT_RES_SURFACE_CHANGED;}
WindowSurfaceController surfaceController;try{
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER,"createSurfaceControl");// 创建surfaceController
surfaceController = winAnimator.createSurfaceLocked(win.mAttrs.type, win.mOwnerUid);}finally{
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);}if(surfaceController != null){
surfaceController.getSurface(outSurface);if(SHOW_TRANSACTIONS) Slog.i(TAG_WM," OUT SURFACE "+ outSurface +": copied");}else{// For some reason there isn't a surface. Clear the// caller's object so they see the same state.
Slog.w(TAG_WM,"Failed to create surface control for "+ win);
outSurface.release();}return result;}
// frameworks/base/core/java/android/view/SurfaceControl.javapublic SurfaceControl build(){if(mWidth <=0|| mHeight <=0){thrownewIllegalArgumentException("width and height must be set");}returnnewSurfaceControl(mSession, mName, mWidth, mHeight, mFormat,
mFlags, mParent, mWindowType, mOwnerUid);}--------------------------------------------------------------------------------------------------------------------------------------privateSurfaceControl(SurfaceSession session, String name,int w,int h,int format,int flags,
SurfaceControl parent,int windowType,int ownerUid)throws OutOfResourcesException, IllegalArgumentException {if(session == null){thrownewIllegalArgumentException("session must not be null");}if(name == null){thrownewIllegalArgumentException("name must not be null");}if((flags & SurfaceControl.HIDDEN)==0){
Log.w(TAG,"Surfaces should always be created with the HIDDEN flag set "+"to ensure that they are not made visible prematurely before "+"all of the surface's properties have been configured. "+"Set the other properties and make the surface visible within "+"a transaction. New surface name: "+ name,newThrowable());}
mName = name;
mWidth = w;
mHeight = h;// session就是SurfaceComposerClient在java层的Binder代理// mNativeObject是native层SurfaceControl的指针
mNativeObject =nativeCreate(session, name, w, h, format, flags,
parent != null ? parent.mNativeObject :0, windowType, ownerUid);if(mNativeObject ==0){thrownewOutOfResourcesException("Couldn't allocate SurfaceControl native object");}
mCloseGuard.open("release");}
// frameworks/base/core/java/android/view/Surface.javapublicvoidcopyFrom(SurfaceControl other){if(other == null){thrownewIllegalArgumentException("other must not be null");}// 获取native层的surfaceControl的指针long surfaceControlPtr = other.mNativeObject;if(surfaceControlPtr ==0){thrownewNullPointerException("null SurfaceControl native object. Are you using a released SurfaceControl?");}long newNativeObject =nativeGetFromSurfaceControl(surfaceControlPtr);synchronized(mLock){if(mNativeObject !=0){nativeRelease(mNativeObject);}setNativeObjectLocked(newNativeObject);}}