当前位置:网站首页>Activity creation process details
Activity creation process details
2022-06-23 22:22:00 【Great inventor】
Create a process
ActivityThread As the main thread management class of the main application , We all come from main Method analysis .main The main function of the method is to create ActivityThread And related , establish Looper The loop does not let the program exit .
public static void main(String[] args) {...
// Create... For the main thread loop object , We use... In the main thread Handler It can be used without initialization , Because initialization is done here .
Looper.prepareMainLooper();
...
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {sMainThreadHandler = thread.getHandler();
}
// Start an endless loop to get messages
Looper.loop();
}
Next let's analyze ActivityThread Of attach Method , Calling attach The first parameter passed is false, We can see that it passes through AMS Cross process call attachApplication Method .
private void attach(boolean system, long startSeq) { if (!system) {...
final IActivityManager mgr = ActivityManager.getService();
try {mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {throw ex.rethrowFromSystemServer();
}
}
...
}
Next we need to go framework see AMS Only the source code can know what has been done inside ,
Finally called. attachApplicationLocked Method , Then call back to the main process ApplicationThread Of bindApplication Go inside the way .
//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {...
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.isPersistent(),
new Configuration(app.getWindowProcessController().getConfiguration()),
app.compat, getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions);
...
didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
...
}
We continue to analyze the main process ActivityThread,AMS Tell it to create Application, And data synchronization between the two processes .
public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial, AutofillOptions autofillOptions,
ContentCaptureOptions contentCaptureOptions) {...
AppBindData data = new AppBindData();
data.processName = processName;
data.appInfo = appInfo;
data.providers = providers;
data.instrumentationName = instrumentationName;
data.instrumentationArgs = instrumentationArgs;
data.instrumentationWatcher = instrumentationWatcher;
data.instrumentationUiAutomationConnection = instrumentationUiConnection;
data.debugMode = debugMode;
data.enableBinderTracking = enableBinderTracking;
data.trackAllocation = trackAllocation;
data.restrictedBackupMode = isRestrictedBackupMode;
data.persistent = persistent;
data.config = config;
data.compatInfo = compatInfo;
data.initProfilerInfo = profilerInfo;
data.buildSerial = buildSerial;
data.autofillOptions = autofillOptions;
data.contentCaptureOptions = contentCaptureOptions;
sendMessage(H.BIND_APPLICATION, data);//1
}
We can see the first point from the above code , stay ApplicationThread adopt H Class is inheritance Handler, By sending a message to the main thread management class ActivityThread Perform binding Application, call handleBindApplication Method . establish LoadedApk Object and used to create Application.
private void handleBindApplication(AppBindData data) {// Set the process name
Process.setArgV0(data.processName);
// establish LoadedApk example
data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
app = data.info.makeApplication(data.restrictedBackupMode, null);
}
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {//1
if (mApplication != null) {return mApplication;
}
Application app = null;
try {ClassLoader cl = getClassLoader();
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
//2
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {}
mApplication = app;
if (instrumentation != null) {//3
instrumentation.callApplicationOnCreate(app);
}
return app;
}
From the above code, we can see that ,
1: If any have been created Applicaiton Object and return .
2: establish Application object , And with appContext Establish relational relationships , And call attach Method
3: adopt instrumentation Calls to perform onCreate Method
And then we're going back to AMS Code inside and method attachApplicationLocked, See how the jump is performed Activity Of .
//frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
public boolean attachApplication(WindowProcessController wpc) throws RemoteException { synchronized (mGlobalLockWithoutBoost) {return mRootActivityContainer.attachApplication(wpc);
}
We can see the following code realStartActivityLocked, This is what we really initiated Activity Methods , Then we continue to analyze the code .
//frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
boolean attachApplication(WindowProcessController app) throws RemoteException {final String processName = app.mName;
boolean didSomething = false;
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {final ActivityDisplay display = mActivityDisplays.get(displayNdx);
final ActivityStack stack = display.getFocusedStack();
if (stack != null) {stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
final ActivityRecord top = stack.topRunningActivityLocked();
final int size = mTmpActivityList.size();
for (int i = 0; i < size; i++) {final ActivityRecord activity = mTmpActivityList.get(i);
if (activity.app == null && app.mUid == activity.info.applicationInfo.uid
&& processName.equals(activity.processName)) { try {// Perform jump
if (mStackSupervisor.realStartActivityLocked(activity, app,
top == activity /* andResume */, true /* checkConfig */)) {didSomething = true;
}
} catch (RemoteException e) {}
}
}
}
}
return didSomething;
}
The main function of the following code is , Send instructions to the application process to create Activity,LaunchActivityItem Represents a creation task .
//frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {// Start command
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
r.icicle, r.persistentState, results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction. Cross process calls to application processes
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
return true;
}
So he began to execute the order until ,
//ClientLifecycleManager.java
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {transaction.recycle();
}
}
//ClientTransaction.java
public void schedule() throws RemoteException {mClient.scheduleTransaction(this);
}
The above code mClient It's all ApplicationThread, So we know , Real... Will be created soon Activity 了 , Let's continue to analyze , We are here ApplicationThread This in this class scheduleTransaction Method .
//ClientTransactionHandler.java
void scheduleTransaction(ClientTransaction transaction) {transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
The above code shows , Finally, the execution of the agency has come to ActivityThread, Then, by sending a message to the main thread management to execute the creation Activity,ActivityThread Inherited ClientTransactionHandler.
//TransactionExecutor.java
public void execute(ClientTransaction transaction) {executeCallbacks(transaction);
// Before the execution pauses, this method is called
executeLifecycleState(transaction);
}
public void executeCallbacks(ClientTransaction transaction) { for (int i = 0; i < size; ++i) {final ClientTransactionItem item = callbacks.get(i);
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
}
}
After the above code performance , We are here LaunchActivityItem This class .
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
// And ActivityRecord Information synchronization token Information communication
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
Here we start to create ActivityClientRecord To record Activity Information about , And through token And AMS Of ActivityRecord Corresponding Association . Continue to look at handleLaunchActivity Source code , as follows .
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {final Activity a = performLaunchActivity(r, customIntent);
return a;
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
} catch (Exception e) {}
try {Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {appContext.setOuterContext(activity);
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);
if (r.isPersistable()) {mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {mInstrumentation.callActivityOnCreate(activity, r.state);
}
r.activity = activity;
}
} catch (SuperNotCalledException e) {throw e;
} catch (Exception e) {}
return activity;
}
边栏推荐
- WordPress plugin smart product review 1.0.4 - upload of any file
- SAP mm ml81n creates a service receipt for a purchase order and reports an error - no matching Po items selected-
- [tutorial] build a personal email system using Tencent lightweight cloud
- What is stock online account opening? Is it safe to open a mobile account?
- MySQL de duplication query only keeps one latest record
- EDI mandatory manual
- Bi SQL constraints
- 為什麼你的數據圖譜分析圖上只顯示一個值?
- API gateway verification token the role of adding a new authentication token in API gateway
- How to build an API gateway and how to maintain an API gateway?
猜你喜欢

为什么你的数据图谱分析图上只显示一个值?

Code implementation of CAD drawing online web measurement tool (measuring distance, area, angle, etc.)

SLSA: 成功SBOM的促进剂

Icml2022 | robust task representation for off-line meta reinforcement learning based on contrastive learning

Intel openvino tool suite advanced course & experiment operation record and learning summary

為什麼你的數據圖譜分析圖上只顯示一個值?

游戏安全丨喊话CALL分析-写代码

脚本之美│VBS 入门交互实战

北大、加州伯克利大学等联合| Domain-Adaptive Text Classification with Structured Knowledge from Unlabeled Data(基于未标记数据的结构化知识的领域自适应文本分类)

Ten thousand words! Understand the inheritedwidget local refresh mechanism
随机推荐
Kubecon2021 video collection
Use bcryptjs to encrypt the password
Statistics of clinical trials - Calculation of tumor trial endpoint
WordPress plug-in recommendation
How does H5 communicate with native apps?
How do API gateways set up dynamic routing? What are the benefits of dynamic routing?
How do I install the API gateway? What should I pay attention to?
使用 Provider 改造屎一样的代码,代码量降低了2/3!
How to deploy the API gateway? Is it OK not to use the API gateway?
Overall solution for digital transformation of medical supply chain management
How to control the quality of omics research—— Mosein
Detailed explanation of redisson distribution lock
2022年性价比高的商业养老保险产品排名
Interpretation of opentelemetry project
How the API gateway obtains the URI path and how the API handles local access failure
How does the national standard gb28181 security video platform easygbs download device video through the interface?
How does the fortress remote login server operate? What is the application value of Fortress machine?
Hugegraph: hugegraph Hubble web based visual graph management
DM sub database and sub table DDL "pessimistic coordination" mode introduction - tidb tool sharing
How to improve the high concurrency of the server