}
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
int result = START_CANCELED;
final ActivityStack startedActivityStack;
try {
mService.mWindowManager.deferSurfaceLayout();
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
}
// …
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
// …
mRootActivityContainer.resumeFocusedStacksTopActivities();
}
}
接下里继续到RootActivityContainer;
/**
- Root node for activity containers.
- TODO: This class is mostly temporary to separate things out of ActivityStackSupervisor.java. The
- intention is to have this merged with RootWindowContainer.java as part of unifying the hierarchy.
- 看样子这个类后面可能会被合入到RootWindowContainer里,不重点分析;
*/
class RootActivityContainer {
boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && (targetStack.isTopStackOnDisplay() || getTopDisplayFocusedStack() == targetStack)) {
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
}
}
7. ActivityStack源码分析
ActivityStack负责管理activity栈和activity的状态,包括根据activity栈的状态决定如何管理activity等,当然activity的启动也是由它来继续完成;
/**
- State and management of a single stack of activities.
*/
class ActivityStack extends ConfigurationContainer {
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mInResumeTopActivity) {
// Don’t even start recursing.
return false;
}
boolean result = false;
try {
// Protect against recursion.
mInResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
}
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
// …
if (next.attachedToProcess()) {
if (nextNext != next) {
// Do over!
mStackSupervisor.scheduleResumeTopActivities();
}
} else {
// Whoops, need to restart this activity!
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
}
}
8. StackSupervisor源码分析
// TODO: This class has become a dumping ground. Let’s
// - Move things relating to the hierarchy to RootWindowContainer
// - Move things relating to activity life cycles to maybe a new class called ActivityLifeCycler
// - Move interface things to ActivityTaskManagerService.
// - All other little things to other files.
// 看样子这部分代码后面也会被RootWindowContainer里面,后面Android源码分析可能要重点分析这个类了 😢
public class ActivityStackSupervisor implements RecentTasks.Callbacks {
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
// Is this activity’s application already running?
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
try {
// 重点分析
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
- r.intent.getComponent().flattenToShortString(), e);
}
// If a dead object exception was thrown – fall through to
// restart the application.
knownToBeDead = true;
}
}
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) {
// …
// Create activity launch transaction
final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken);
// 重点,这里先记住它的callback是LaunchActivityItem
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode®, 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));
// Schedule transaction. mService就是ActivityTaskManagerService
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
}
以上代码分析出,启动activity被封装成transaction由ActivityTaskManagerService中的ClientLifecycleManager进程处理;
9. ClientLifecycleManager源码分析
class ClientLifecycleManager {
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
// the transaction is executed on client in ActivityThread.
transaction.recycle();
}
}
代码比较明确,就是执行ClientTransaction的内容;接着分析ClientTransaction的代码:
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/** Target client. */
private IApplicationThread mClient;
public void schedule() throws RemoteException {
// 重点
mClient.scheduleTransaction(this);
}
}
以上代码可以看出,最终执行到了mCient的scheduleTransaction()方法;而mClient就是传过来的IApplicationThread,这样就完成了从ActivityTaskManagerService进程到App2进程的调用;
10. ActivityThread源码分析
前面说过ApplicationThread可以代表app所在进程,其他进程访问ApplicationThread是通过IApplicationThread形式的binder代理实现的;ApplicationThread是ActivityThread的内部类,scheduleTransaction()方法最终是由ActivityThread实现;
/**
- This manages the execution of the main thread in an
- application process, scheduling and executing activities,
- broadcasts, and other operations on it as the activity
- manager requests.
- 继承了ClientTransactionHandler,后面也用分析到
*/
public final class ActivityThread extends ClientTransactionHandler {
// 重点
final H mH = new H();
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
}
class H extends Handler {
// …
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
// …
break;
case EXIT_APPLICATION:
// …
break;
case RECEIVER:
// …
case CREATE_SERVICE:
// …
case BIND_SERVICE:
// …
case UNBIND_SERVICE:
// …
case STOP_SERVICE:
// …
case CONFIGURATION_CHANGED:
// …
case DUMP_SERVICE:
// …
// 省略…
case EXECUTE_TRANSACTION:
// 重点
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
break;
case RELAUNCH_ACTIVITY:
handleRelaunchActivityLocally((IBinder) msg.obj);
break;
case PURGE_RESOURCES:
schedulePurgeIdler();
break;
}
}
}
}
可见,最终是继承了Handler的内部类H来发送message,并最终由mH完成处理;可以看到H的handleMessage()里面有许多熟悉的消息都是在这里处理的;后面继续分析EXECUTE_TRANSACTION的情况,即mTransactionExecutor.execute(transaction);
11.TransactionExecutor源码分析
/**
- Class that manages transaction execution in the correct order.
- 事务特性:保证按正确的顺序执行
*/
public class TransactionExecutor {
public void execute(ClientTransaction transaction) {
// 省略部分…
final IBinder token = transaction.getActivityToken();
executeCallbacks(transaction);
executeLifecycleState(transaction);
}
public void executeCallbacks(ClientTransaction transaction) {
// 还记得StackSupervisor中说到的transaction的callback是LaunchActivityItem吗,那后续执行就到了LaunchActivityItem里面
item.execute(mTransactionHandler, token, mPendingActions);
}
LaunchActivityItem源码如下:
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, “activityStart”);
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
可见,最后又由client执行了handleLaunchActivity,这里的client就是前面的ActivityThread;
那为啥不一开始就直接在ActivityThread执行完,还非要兜这么一大圈子嘞? 😢
因为启动的过程是作为一个事务进程的,除了创建activity还有生命周期的回调等都需要保证原子性,所以这个部分被封装成了一个事务进行;这里其实是我猜的,下次还骗你~
12. 又见ActivityThread
那么接下来,继续分析ActivityThread的handleLaunchActivity()吧!
public final class ActivityThread extends ClientTransactionHandler {
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
// …
final Activity a = performLaunchActivity(r, customIntent);
return a;
}
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// 省略部分代码…
ActivityInfo aInfo = r.activityInfo;
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
// 重点代码,可以看到实际上又是Instrumentation新建了activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
// …
}
try {
if (activity != null) {
// …
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);
// 又是Instrumentation,下面分析
mInstrumentation.callActivityOnCreate(activity, r.state);
r.activity = activity;
}
r.setState(ON_CREATE);
}
return activity;
}
}
里面比较重要的代码是Instrumentation的newActivity()和callActivityOnCreate()方法,下面接着分析;
13. 又见Instrumentation
public class Instrumentation {
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
String pkg = intent != null && intent.getComponent() != null
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级安卓工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年最新Android移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
d移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。**
[外链图片转存中…(img-s1Oak3y4-1710913725631)]
[外链图片转存中…(img-Bz7QLViY-1710913725632)]
[外链图片转存中…(img-VPtVoizR-1710913725632)]
[外链图片转存中…(img-KhuLW9U0-1710913725633)]
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
[外链图片转存中…(img-RhSnQifF-1710913725633)]