Activity启动总结
2022-07-02 本文已影响0人
中路杀神ai
Activity:
startActivity(Intent intent) ->startActivity(Intent intent, @Nullable Bundle options)
——>startActivityForResult(intent, -1); ->startActivityForResult(intent, requestCode, null);
——> mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
IPC 跨进程调用
——>ActivityTaskManager.getService().startActivity(
——>ActivityTaskManagerService.startActivity()
ActivityStartController->ActivityStarter.execute
——>getActivityStartController().obtainStarter(intent, "startActivityAsUser")
——>ActivityStarter.execute
//创建出ActivityRecord r = new ActivityRecord.Builder(mService)
->executeRequest(mRequest);
——>startActivityUnchecked( ——>startActivityInner( -> mRootWindowContainer.resumeFocusedTasksTopActivities(
——>focusedRoot.resumeTopActivityUncheckedLocked ->resumeTopActivityInnerLocked->
//系统ActivityRecord 系统进程是否创建 //冷启动 还没有创建主线程
```
if (next.attachedToProcess()) {
//Activity已经存在,topRunningActivity 执行onPause -> nextActivity执行
//onResume
}else{
//ActivityTaskSupervisor
mTaskSupervisor.startSpecificActivity(
}
```
ActivityTaskSuperVisor
——> mTaskSupervisor.startSpecificActivity(
这个活动的应用程序已经运行了吗?
if (wpc != null && wpc.hasThread()) {
//启动Activity
//ActivityTaskSupervisor
realStartActivityLocked();
return;
}
//创建进程
mService.startProcessAsync(
1.冷启动 创建ActivityThread
——>ActivityTaskManagerService.startProcessAsync(
Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
isTop, hostingType, activity.intent.getComponent());
mH.sendMessage(m);
通过ActivityManagerInternal::startProcess
ActivityManagerInternal 的实现类 ActivityManagerService #LocalService
——>LocalService.startProcess( -> startProcessLocked(,,,,,false
ProcessList //创建进程
——>mProcessList.startProcessLocked -> app = newProcessRecordLocked(
//启动
——>final boolean success = startProcessLocked(
String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi;
//后续会传递到Zygote启动ActivityThread.main
##final String entryPoint = "android.app.ActivityThread";
——>startProcessLocked
final Process.ProcessStartResult startResult = startProcess(hostingRecord,
entryPoint, app,
uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo,
requiredAbi, instructionSet, invokeWith, startTime);
handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
startSeq, false);
——> startProcess(
Process向Zygote进程发送创建应用进程请求
——>Process.start( -> ZYGOTE_PROCESS.start(
ZygoteProcess
->startViaZygote(
zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
zygotePolicyFlags,
argsForZygote);
// 尝试使用兼容的ABI打开到Zygote进程的会话套接字(如果没有兼容的ABI)
// *已经打开。如果兼容的会话套接字已经打开,则返回该会话套接字。
// *该函数可能会阻塞,可能需要尝试连接多个受精卵来找到
// 合适的一个。
//与Zygote建立Socket连接
——> openZygoteSocketIfNeeded(abi);
//尝试连接主到Zygote
attemptConnectionToPrimaryZygote();
//Socket进行连接成功并匹配abi后会返回ZygoteState类型对象
if (primaryZygoteState.matches(abi)) {
return primaryZygoteState;
}
if (mZygoteSecondarySocketAddress != null) {
//主Abi不适配,尝试连接次Zygote
// The primary zygote didn't match. Try the secondary.
attemptConnectionToSecondaryZygote();
if (secondaryZygoteState.matches(abi)) {
return secondaryZygoteState;
}
}
attemptConnectionToPrimaryZygote();
->
64进程中 与 名zygote的建立连接
primaryZygoteState =
ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress);
attemptConnectionToSecondaryZygote();
->
32位进程中与 名 zygote_secondary的建立连接
//发送请求
//将传入的应用进程的启动参数argsForZygote写入到ZygoteState
——> zygoteSendArgsAndGetResult
##Zygote进程接受请求并孵化应用进程
AMS已经与Zygote进程建立Socket连接并发送了创建应用进程的请求,那么Zygote进程是会收到请求
Zygote进程是在ZygoteInit的main方法中接受请求的。所以现在的入口就是ZygoteInit的main方法。
//文件
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
——> ZygoteInit.main
```
@UnsupportedAppUsage
public static void main(String argv[]) {
ZygoteServer zygoteServer = new ZygoteServer();
Runnable caller;
try {
...
//创建名为zygote的Socket
zygoteServer.createZygoteSocket(socketName);
....
//由于在init.rc中设置了start-system-server参数,因此
//这里将启动SystemServer,可见SystemServer由Zygote创建的第一个进程
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
if (r != null) {
r.run();
return;
}
}
caller = Zygote.initBlastulaPool();
if (caller == null) {
//等待AMS的请求
caller = zygoteServer.runSelectLoop(abiList);
}
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with exception", ex);
throw ex;
} finally {
zygoteServer.closeServerSocket();
}
// We're in the child process and have exited the select loop. Proceed to execute the
// command.
//执行runnable
if (caller != null) {
caller.run();
}
```
通过main方法,我们可以知道在这个main方法首先要创建一个Server端的Socket,
这个name为”zygote”的Socket用来等待ActivityManagerService来请求Zygote来创建新的应用程序进程,
在上面AMS请求的分析中我们也知道客户端将根据这个name来与Zygote的Socket建立连接。
接下去会启动SystemServer进程,这个进程会启动各种系统服务,比如与Activity启动息息相关的AMS。
最后会调用ZygoteServer.runSelectLoop(abiList)
来使创建的Socket进入无限循环,等待AMS请求
```frameworks/base/core/java/com/android/internal/os/ZygoteServer.java```
——>runSelectLoop
```
Runnable runSelectLoop(String abiList) {
ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
peers.add(null);
while (true) {
while (--pollIndex >= 0) {
if ((pollFDs[pollIndex].revents & POLLIN) == 0) {
continue;
}
if (pollIndex == 0) {
//监听Socket连接,充当服务端Socket
ZygoteConnection newPeer = acceptCommandPeer(abiList);
peers.add(newPeer);
socketFDs.add(newPeer.getFileDescriptor());
} else if (pollIndex < blastulaPoolEventFDIndex) {
try {
//不断处理客户端的AMS的请求,然后交给processOneCommand
ZygoteConnection connection = peers.get(pollIndex);
final Runnable command = connection.processOneCommand(this);
}
....
}
}
}
}
```
可以发现这个方法是死循环表示不停的监听着Socket连接。
acceptCommandPeer方法就是监听是否收到了请求,
如果收到了请求就交给processOneCommand来实现
``` frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java```
——>processOneCommand
```
Runnable processOneCommand(ZygoteServer zygoteServer) {
String args[];
ZygoteArguments parsedArgs = null;
FileDescriptor[] descriptors;
try {
//获取应用程序进程的启动参数
args = Zygote.readArgumentList(mSocketReader);
// TODO (chriswailes): Remove this and add an assert.
descriptors = mSocket.getAncillaryFileDescriptors();
} catch (IOException ex) {
throw new IllegalStateException("IOException on command socket", ex);
}
....
parsedArgs = new ZygoteArguments(args);
....
//fork当前进程创建一个子进程
pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion);
try {
//pid为0则代表这个进程为子进程,即新创建的应用程序进程
if (pid == 0) {
zygoteServer.setForkChild();
zygoteServer.closeServerSocket();
IoUtils.closeQuietly(serverPipeFd);
serverPipeFd = null;
return handleChildProc(parsedArgs, descriptors, childPipeFd,
parsedArgs.mStartChildZygote);
} else {
// In the parent. A pid < 0 indicates a failure and will be handled in
// handleParentProc.
IoUtils.closeQuietly(childPipeFd);
childPipeFd = null;
handleParentProc(pid, descriptors, serverPipeFd);
return null;
}
} finally {
IoUtils.closeQuietly(childPipeFd);
IoUtils.closeQuietly(serverPipeFd);
}
}
```
在这个方法中将对请求进行处理,首先获取到将要启动的应用进程的启动参数,然后调用forkAndSpecialize来创建应用进程。
```frameworks/base/core/java/com/android/internal/os/Zygote.java```
```
public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
int targetSdkVersion) {
ZygoteHooks.preFork();
// Resets nice priority for zygote process.
resetNicePriority();
int pid = nativeForkAndSpecialize(
uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
fdsToIgnore, startChildZygote, instructionSet, appDataDir);
// Enable tracing as soon as possible for the child process.
if (pid == 0) {
Zygote.disableExecuteOnly(targetSdkVersion);
Trace.setTracingEnabled(true, runtimeFlags);
// Note that this event ends at the end of handleChildProc,
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
}
ZygoteHooks.postForkCommon();
return pid;
}
```
在forkAndSpecialize中,最终将创建应用进程的任务交给nativeForkAndSpecialize,
而这个方法可以看出来应该是本地方法,所以具体如何创建的我们就不深究了,
在这里我们这需要知道nativeForkAndSpecialize最终是通过fork当前进程来创建一个子进程,
而fork后会有返回值给pid:
父进程中,fork返回新创建的子进程pid;
子进程中,fork返回0;
出现错误时,fork返回负数
##应用进程启动ActivityThread
//ZygoteConnection.processOneCommand()
——> handleChildProc(
```
if (!isZygote) {
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mRemainingArgs, null /* classLoader */);
} else {
....
}
```
```frameworks/base/core/java/com/android/internal/os/ZygoteInit.java```
```
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
RuntimeInit.redirectLogStreams();
//为当前的VM设置未捕获异常器
RuntimeInit.commonInit();
//Binder驱动初始化,该方法完成后,可通过Binder进行进程通信
ZygoteInit.nativeZygoteInit();
//主要调用SystemServer的main方法
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
```
在这个方法里会创建当前进程的Binder线程池,便于后续与其它进程通信,
然后调用了RuntimeInit的applicationInit方法,如下:
```frameworks/base/core/java/com/android/internal/os/RuntimeInit.java```
```
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
...
final Arguments args = new Arguments(argv);
// Remaining arguments are passed to the start class's static main
//args.startClass, args.startArgs,
// == ActivityThread.main
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
```
——> findStaticMain(
```
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);//1
} catch (ClassNotFoundException ex) {
....
}
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });//2
} catch (NoSuchMethodException ex) {
...
} catch (SecurityException ex) {
...
}
return new MethodAndArgsCaller(m, argv);
}
```
在这个方法中首先在注释1通过反射获取到android.app.ActivityThread类,
然后在注释2获取到ActivityThread的main方法,
最后通过main方法来构造MethodAndArgsCaller。
```frameworks/base/core/java/com/android/internal/os/RuntimeInit.java```
```
static class MethodAndArgsCaller implements Runnable {
/** method to call */
private final Method mMethod;
/** argument array */
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
public void run() {
try {
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException(ex);
}
}
}
```
MethodAndArgsCaller其实是RuntimeInit的一个内部类并且继承了Runnable,
然后在run方法中会通过反射调用了mMethod方法,
此时mMethod是ActivityThread的main方法,
即run方法中将会执行ActivityThread的main方法,
在这里你可能会有疑问了,那这个run方法什么时候执行呢?
让我们来看看最开始的ZygoteInit的main方法。
```
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
@UnsupportedAppUsage
public static void main(String argv[]) {
Runnable caller;
try {
....
caller = Zygote.initBlastulaPool();
if (caller == null) {
Log.i(TAG, "Accepting command socket connections");
//等待AMS的请求
caller = zygoteServer.runSelectLoop(abiList);
}
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with exception", ex);
throw ex;
} finally {
zygoteServer.closeServerSocket();
}
//执行 ActivityThread.main
if (caller != null) {
caller.run();
}
}
```
从分析Zygote进程接受请求并孵化应用进程的一开始,
我们就是分析zygoteServer.runSelectLoop(abiList)这个方法,
而分析到最后findStaticMain方法将返回MethodAndArgsCaller对象(继承Runnable)
,所以这时候在ZygoteInit的main方法caller会等于这个MethodAndArgsCaller对象,
显然caller不等于null,故最后会执行caller.run方法,
即执行ActivityThread的main方法。
于是应用进程成功启动ActivityThread。
##ActivityThread的启动
应用进程绑定到AMS
AMS发送启动Activity的请求
ActivityThread的Handler处理启动Activity的请求
ActivityThread
```
public static void main(String[] args) {
....
//创建主线程的Looper以及MessageQueue
Looper.prepareMainLooper();
...
//AMS绑定ApplicationThread对象,即应用进程绑定到AMS
thread.attach(false, startSeq);
//开启主线程的消息循环
Looper.loop();
...
}
```
——>thread.attach(false, startSeq);
```
final IActivityManager mgr = ActivityManager.getService();
//AMS 绑定 ApplicationThread对象
mgr.attachApplication(mAppThread, startSeq);
```
ActivityManagerService
——> mgr.attachApplication(
——>attachApplicationLocked(@NonNull IApplicationThread thread,
int pid, int callingUid, long startSeq) {
```
//将应用进程的ApplicationThread对象绑定到AMS,即AMS获得ApplicationThread的代理对象
thread.bindApplication(
//启动Activity
mAtmInternal.attachApplication(app.getWindowProcessController());
```
——>thread.bindApplication(
//
//向H发送绑定ApplicationThread对象的消息
//sendMessage(H.BIND_APPLICATION, data);
->handleBindApplication(AppBindData data)
//调用Application.onCreate
->mInstrumentation.callApplicationOnCreate(app);
//ActivityTaskManagerService 内部类 LocalService extends ActivityTaskManagerInternal
——>mAtmInternal.attachApplication(
//RootWindowContainer
——>mRootWindowContainer.attachApplication(wpc);
//ActivityTaskSupervisor
——>mTaskSupervisor.realStartActivityLocked(
```
//添加一个 LaunchActivityItem 的callback
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);
final boolean isTransitionForward = r.isTransitionForward();
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
//判断生命周期的状态
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(isTransitionForward);
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
//AMS 获取ClientLifecycleManager 发送状态
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
```
//ClientLifecycleManager.
——> scheduleTransaction(
ClientTransaction
-> transaction.schedule();
//1.mClient是IApplicationThread类型,
//2.ActivityThread的内部类ApplicationThread派生这个接口类并实现了对应的方法
//3.ActivityThread实际调用的是他父类ClientTransactionHandler的scheduleTransaction方法。
->mClient.scheduleTransaction(this);
##ActivityThread的Handler处理启动Activity的请求
——>sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
//H:
——> mTransactionExecutor.execute(transaction);
```
//先执行callbacks,当根活动首次启动时会有callback,callback会执行onCreate方法
//其它活动切换状态时没有callback
executeCallbacks(transaction);
//改变活动的生命周期状态
executeLifecycleState(transaction);
```
——>executeCallbacks(transaction);
```
for (int i = 0; i < size; ++i) {
//Activity启动 LaunchActivityItem
final ClientTransactionItem item = callbacks.get(i);
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
```
-> LaunchActivityItem.execute
-> client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
//ActivityThread
-> handleLaunchActivity(
——>performLaunchActivity(r, customIntent);
```
//创建启动Activity的上下文
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
//类加载器创建 Activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
//(Activity) cl.loadClass(className).newInstance()
//---------
//创建Application 调用onCreate
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
//初始化Activity,创建Window对象(PhoneWindow)并实现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,
r.assistToken, r.shareableActivityToken);
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
//设置生命周期为onCreate
r.setState(ON_CREATE);
```
//onCreate
——>executeLifecycleState(transaction);
```
//执行onCreate和onResume之前的生命周期 即onStart
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
// Execute the final transition with proper parameters.
//此时的lifecycleItem 为 ResumeActivityItem
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
```
在executeLifecycleState方法中,会先执行cycleToPath,
从上面的分析我们已经知道当根Activity启动时,
此时的lifecycleItem为ResumeActivityItem,
故调用lifecycleItem.getTargetState时将得到ON_RESUME状态,
让我们来瞧瞧cycleToPath方法。
```
private void cycleToPath(ActivityClientRecord r, int finish,
boolean excludeLastState) {
final int start = r.getLifecycleState();
log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
performLifecycleSequence(r, path);
}
```
由于onCreate方法已经执行,所以start为ON_CREATE,
而finish为上面传递的ON_RESUME,
excludeLastState是否移除最后的状态为true。
让我们来看看getLifecyclePath这个方法
```
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
...
if (finish >= start) {
// 添加start到finish之间的周期状态
for (int i = start + 1; i <= finish; i++) {
mLifecycleSequence.add(i);
}
}
...
// 根据需求移除最后的状态
if (excludeLastState && mLifecycleSequence.size() != 0) {
mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
}
return mLifecycleSequence;
}
public abstract class ActivityLifecycleItem extends ClientTransactionItem {
.....
public static final int UNDEFINED = -1;
public static final int PRE_ON_CREATE = 0;
public static final int ON_CREATE = 1;
public static final int ON_START = 2;
public static final int ON_RESUME = 3;
public static final int ON_PAUSE = 4;
public static final int ON_STOP = 5;
public static final int ON_DESTROY = 6;
public static final int ON_RESTART = 7;
...
}
```
在getLifecyclePath这个方法我们知道
start为ON_CREATE, finish为ON_RESUME,
所以mLifecycleSequence将添加ON_START和ON_RESUME状态,
但是又因为excludeLastState为true,所以最后会移除掉ON_RESUME状态,
故返回的类型只包含ON_START状态。
故cycleToPath方法中的path中将只包含ON_START状态,
然后继续执行 performLifecycleSequence 方法。
//
——>performLifecycleSequence(
```
//执行onStart
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:
mTransactionHandler.handleStartActivity(r.token, mPendingActions);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
false /* userLeaving */, 0 /* configChanges */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r.token, 0 /* configChanges */,
mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r.token, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
}
```
//cycleToPath执行完onCreate方法 执行
///ResumeActivityItem
——>lifecycleItem.execute
——>client.handleResumeActivity(r, true /* finalStateRequest */, mIsForward,
"RESUME_ACTIVITY");
//ActivityThread
——>handleResumeActivity
```
//设置Activity的生命周期为onResume
if (!performResumeActivity(r, finalStateRequest, reason)) {
return;
}
//
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;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
wm.addView(decor, l);
```
## UI原理 :
布局层级
Activity->PhoneWindow—>DecorView(parent->ViewRootImpl)->setContentView()
前文
———> performLaunchActivity 里
->activity.attach(
```
////1、回调 attachBaseContext
attachBaseContext(context);
////2、创建PhoneWindow
mWindow = new PhoneWindow(this, window, activityConfigCallback);
mWindow.setWindowControllerCallback(mWindowControllerCallback);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
```
##Activity#onCreate
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
——> PhoneWindow.setContentView
```
public void setContentView(int layoutResID) {
if (mContentParent == null) {
//1、 创建DecorView
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
//2、mContentParent是DecorView中的FrameLayout,将我们的布局添加到这个FrameLayout里
mLayoutInflater.inflate(layoutResID, mContentParent);
}
...
}
```
——> installDecor();
```
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
//1.创建DecorView
mDecor = generateDecor(-1);
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
} else {
// 2. mDecor 不为空,就是创建过,只需设置window
mDecor.setWindow(this);
}
if (mContentParent == null) {
//3.找到DecorView 内容部分,findViewById(ID_ANDROID_CONTENT)
mContentParent = generateLayout(mDecor);
// Set up decor part of UI to ignore fitsSystemWindows if appropriate.
mDecor.makeOptionalFitsSystemWindows();
//4.找到DecorView的根View,给标题栏部分,设置图标和标题啥的
final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
R.id.decor_content_parent);
}
}
```
——>generateDecor(
```
protected DecorView generateDecor(int featureId) {
...
return new DecorView(context, featureId, this, getAttributes());
}
```
——>generateLayout(
```
protected ViewGroup generateLayout(DecorView decor) {
// 1.窗口各种属性设置,例如 requestFeature(FEATURE_NO_TITLE);
...
if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
requestFeature(FEATURE_NO_TITLE);
}
...
if (a.getBoolean(R.styleable.Window_windowFullscreen, false)) {
setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags()));
}
...
//2.获取 windowBackground 属性,默认窗口背景
if (mBackgroundDrawable == null) {
if (mBackgroundResource == 0) {
mBackgroundResource = a.getResourceId(
R.styleable.Window_windowBackground, 0);
}
...
}
...
// 3.获取DecorView里面id为 R.id.content的布局
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
...
if (getContainer() == null) {
//4.在注释2的时候已经获取了窗口背景属性id,这里转换成drawable,并且设置给DecorView
final Drawable background;
if (mBackgroundResource != 0) {
background = getContext().getDrawable(mBackgroundResource);
} else {
background = mBackgroundDrawable;
}
mDecor.setWindowBackground(background);
}
return contentParent;
}
```
##ActivityThread #handleResumeActivity
```
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
ActivityClientRecord r = mActivities.get(token);
...
//1、先回调Activity的onResume方法
r = performResumeActivity(token, clearHide, reason);
if (r != null) {
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);
//2、wm是当前Activity的WindowManager
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
...
if (a.mVisibleFromClient && !a.mWindowAdded) {
a.mWindowAdded = true;
// 3.添加decor到WindowManager
wm.addView(decor, l);
}
```
performResumeActivity,主要是回调Activity的onResume方法。
注释2: 从Activity开始跟踪这个wm,其实是WindowManagerImpl,
注释3: 调用WindowManagerImpl的addView方法,
最终调用的是WindowManagerGlobal的addView方法,
DecorView添加到 WindowManagerGlobal
wm.addView(decor, l);
```
WindowManagerGlobal
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
```
```
// view = DecorView
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow, int userId) {
//创建 ViewRootImpl
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
//2、添加到ArrayList进行管理
mViews.add(view);
//3.mRoots 存放ViewRootImpl对象
mRoots.add(root);
mParams.add(wparams);
root.setView(view, wparams, panelParentView, userId);
}
```
——>ViewRootImpl
构造方法
```
public ViewRootImpl(Context context, Display display,boolean useSfChoreographer) {
mContext = context;
//1、WindowSession 是IWindowSession,binder对象,可跨进程跟WMS通信
mWindowSession = WindowManagerGlobal.getWindowSession();
mDisplay = display;
...
// 2、创建window,是一个binder对象
mWindow = new W(this);
...
//3、mAttachInfo View.post跟这个息息相关
mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
...
//4、Choreographer在这里初始化
mChoreographer = Choreographer.getInstance();
mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
}
```
——>.setView
```
// 1.DecorView赋值给mView
mView = view;
...
//2.会调用requestLayout
requestLayout();
//3.WindowSession,将window添加到屏幕,有返回值
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
//4.设置decorView的父parent
view.assignParent(this);
```
//注释参考https://juejin.cn/post/6844903974294781965#heading-6
## Choreographer
requestLayout,会请求vsync信号,然后下一次vsync信号来的时候,
会调用 performTraversals 方法,
performTraversals 主要是执行View的measure、layout、draw。
——>
requestLayout()
```
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
```
——>scheduleTraversals()
```
if (!mTraversalScheduled) {
mTraversalScheduled = true;
//设置同步屏障
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
//
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
```
```
TraversalRunnable mTraversalRunnable = new TraversalRunnable();
void doTraversal() {
if (mTraversalScheduled) {
mTraversalScheduled = false;
//移除同步屏障
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
if (mProfile) {
Debug.startMethodTracing("ViewAncestor");
}
//执行绘制
performTraversals();
if (mProfile) {
Debug.stopMethodTracing();
mProfile = false;
}
}
}
```