Android是基于linux系统的,手机开机之后,linux内核进行加载。加载完成之后会启动init进程。
init进程会启动ServiceManager,孵化一些守护进程,并解析init.rc孵化Zygote进程。
所有的App进程都是由Zygote进程fork生成的,包括SystemServer进程。
Zygote初始化后,会注册一个等待接受消息的socket,OS层会采用socket进行IPC通信。
每个应用程序都是运行在各自的Dalvik虚拟机中,应用程序每次运行都要重新初始化和启动虚拟机,这个过程会耗费很长时间。Zygote会把已经运行的虚拟机的代码和内存信息共享。起到一个预加载资源和类的作用,从而缩短启动时间。
ActivityRecord是Activity在system_server进程中的镜像,Activity实例与ActivityRecord实例一一对应。ActivityRecord用来存储Activity的信息,如所在的进程名称,应用的包名,所在的任务栈的taskAffinity等。
/**
* An entry in the history stack, representing an activity.
*/
final class ActivityRecord {
final ComponentName realActivity; // the intent component, or target of an alias.
final String shortComponentName; // the short component name of the intent
final String packageName; // the package implementing intent's component
final String processName; // process where this component wants to run
final String taskAffinity; // as per ActivityInfo.taskAffinity
boolean fullscreen; // covers the full screen?
}
TaskRecord表示任务栈,是真正的一个先进后出的栈结构,用于记录activity开启的先后顺序。其所存放的Activity是不支持重新排序的,只能根据压栈和出栈操作更改Activity的顺序。有了TaskRecord,Android系统才能知道当一个Activity退出时,接下来该显示哪一个Activity。
final class TaskRecord {
/** List of all activities in the task arranged in history order */
final ArrayList<ActivityRecord> mActivities;
}
ActivityStack 是TaskRecord的一个分组,用于管理TaskRecord列表,列表中的TaskRecord可以重排顺序。
final class ActivityStack {
/**
* The back history of all previous (and possibly still
* running) activities. It contains #TaskRecord objects.
*/
private ArrayList<TaskRecord> mTaskHistory = new ArrayList<>();
}
通常情况下,一个App对应一个ActivityStack,ActivityStatck中会有一个TaskRecord列表,通常列表中仅有一个TaskRecord,维护Activity栈。
image
一个Activity启动时,归属的TaskRecord,通常是启动它的Activity 对应的TaskRecord。
如ActivtiyA启动ActivityB,那么ActivityB会被保存在ActivityA所属的TaskRecord中。
image
当一个Activity的launchmode 设置了SingleIntance,那么它启动的时候就会新建一个TaskRecord,这时ActvityStack中就会存在多个TaskRecord 栈结构。
image
当设置了Intent.FLAG_ACTIVITY_NEW_TASK和taskAffinity时,可能会出现多个app共享同一个ActivityStack的情况。
taskAffinity 可以指定Activity需要宿主TaskRecord的名字,当ActivityManagerService发现启动了一个带有 FLAG_ACTIVITY_NEW_TASK 标签的 Activity 时,会先去查找当前AMS中是否存在activity需要的ActivityStack和TaskRecord,如果存在则直接将ActivityRecord添加到对应ActivityStack的TaskRecord中去,否则会先新建一个TaskRecord,然后将ActvityRecord添加到新建的TaskRecord中。
adb shell dumpsys activity 查看activity栈的请款
ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)
Display #0 (activities from top to bottom):
Stack #1:
TaskRecord{4212758 #173 A=com.sogou.iot.testtouch1 U=0 StackId=1 sz=2}
Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.sogou.iot.testtouch1/.MainActivity }
Hist #1: ActivityRecord{4c91dda u0 com.sogou.iot.testtouch1/.SecondActivity t173}
Intent { cmp=com.sogou.iot.testtouch1/.SecondActivity }
ProcessRecord{3fd8bbc 23189:com.sogou.iot.testtouch1/u0a79}
Hist #0: ActivityRecord{93a3d53 u0 com.sogou.iot.testtouch1/.MainActivity t173}
Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.sogou.iot.testtouch1/.MainActivity bnds=[433,77][644,372] }
ProcessRecord{3fd8bbc 23189:com.sogou.iot.testtouch1/u0a79}
Running activities (most recent first):
TaskRecord{4212758 #173 A=com.sogou.iot.testtouch1 U=0 StackId=1 sz=2}
Run #1: ActivityRecord{4c91dda u0 com.sogou.iot.testtouch1/.SecondActivity t173}
Run #0: ActivityRecord{93a3d53 u0 com.sogou.iot.testtouch1/.MainActivity t173}
mResumedActivity: ActivityRecord{4c91dda u0 com.sogou.iot.testtouch1/.SecondActivity t173}
Stack #0:
TaskRecord{db2272c #1 A=com.huawei.android.launcher U=0 StackId=0 sz=1}
Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000300 cmp=com.huawei.android.launcher/.unihome.UniHomeLauncher }
Hist #0: ActivityRecord{60dec4e u0 com.huawei.android.launcher/.unihome.UniHomeLauncher t1}
Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000300 cmp=com.huawei.android.launcher/.unihome.UniHomeLauncher }
ProcessRecord{c03fa2 1781:com.huawei.android.launcher/u0a50}
Running activities (most recent first):
TaskRecord{db2272c #1 A=com.huawei.android.launcher U=0 StackId=0 sz=1}
Run #0: ActivityRecord{60dec4e u0 com.huawei.android.launcher/.unihome.UniHomeLauncher t1}
Stack #0: 代表一个ActivityStack, id = 0 说明是Launcher相关的ActivitStack。
Stack #1: ActivityStack id = 1
,代表常规App的ActvityStack,其中存在一个TaskRecord栈,栈中有两个ActivityRecord
(MainActivity和SecondActivity),SecondeActivity在栈顶,处于Resume状态
ActivityStackSupervisor是ActivityStack的管理者。
内部管理了mHomeStack、mFocusedStack和mLastFocusedStack三个ActivityStack。
其中,mHomeStack管理的是Launcher相关的Activity栈,stackId为0;
mFocusedStack管理的是当前显示在前台Activity的Activity栈;
mLastFocusedStack管理的是上一次显示在前台Activity的Activity栈。
image
ActivityDisplay表示一个屏幕,Android支持三种屏幕:主屏幕,外接屏幕(HDMI等),虚拟屏幕(投屏)。一般情况下,即只有主屏幕时,ActivityStackSupervisor与ActivityDisplay都是系统唯一;
ActivityDisplay是ActivityStackSupervisor的内部类,它相当于一个工具类,封装了移除和添加ActivityStack的方法。
ActivityThread 运行在UI线程(主线程),App的真正入口。
ApplicationThread是一个Binder类,即可实现跨进程通信。主要用于接受从AMS传递过来的IPC消息,继而做相应处理。
private class ApplicationThread extends IApplicationThread.Stub{
}
继承与IInterface接口,用于app进程向ActivityManagerService 单向IPC通信
仪表盘,负责调用Activity和Application生命周期,测试用到这个类比较多。
Activity(在AMS所在进程执行)
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options){
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
pausing |= startPausingLocked(userLeaving, false, next, false);
}
}
if (prev.app != null && prev.app.thread != null) {
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately)
);
}
PauseActivityItem 为暂停Activity的一个ClientTransactionItem
事务,AMS对Activity的操作都封装成了事务来完成。
public class PauseActivityItem extends ActivityLifecycleItem {
private static final String TAG = "PauseActivityItem";
private boolean mFinished;
private boolean mUserLeaving;
private int mConfigChanges;
private boolean mDontReport;
@Override
public void execute(ClientTransactionHandler client, IBinder token,
client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
"PAUSE_ACTIVITY_ITEM");
}
}
public abstract class ActivityLifecycleItem extends ClientTransactionItem {
@Retention(RetentionPolicy.SOURCE)
public @interface LifecycleState{}
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;
}
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/** Target client. */
private IApplicationThread mClient;
}
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
mService.getLifecycleManager().scheduleTransaction,最终调用了IApplciationThread.scheduleTransaction()
此时完成 ActivityManagerService->ApplicationThread发消息,暂停Activity的过程。
上文知ActivityManagerService向ApplicationThread发送了一个PauseActivity的Transaction事务,相应的调用
ApplicationThread的scheduleTransaction()方法,最终调用了ActivityThread的父类ClientTransactionHandler中的方法,发送了一个H.EXECUTE_TRANSACTION消息到主线程Handler
public abstract class ClientTransactionHandler {
// Schedule phase related logic and handlers.
/** Prepare and schedule transaction for execution. */
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
handleMessage 处理EXECUTE_TRANSACTION消息时 会调用TransactionExecutor.execuate()
public void handleMessage(Message msg) {
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
break;
}
public class TransactionExecutor {
public void execute(ClientTransaction transaction) {
executeCallbacks(transaction);
executeLifecycleState(transaction);
}
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
}
最终会调用ActivityThread的handlePauseActivity()方法
阶段四:检查activity所在进程是否存在,如果存在,就直接通知这个进程,在该进程中启动Activity;不存在的话,会调用Process.start创建一个新进程(执行在AMS进程)
@Override
public final void activityPaused(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized(this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
stack.activityPausedLocked(token, false);
}
}
Binder.restoreCallingIdentity(origId);
}
final void activityPausedLocked(IBinder token, boolean timeout) {
completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
}
经过一系列调用,最终代码又回到了 ActivityStackSupervisor 中的 startSpecificActivityLocked 方法。
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
//注释一:根据进程名和uuid判断Activity所属的进程是否创建
// Is this activity's application already running?
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
if (app != null && app.thread != null) {
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
// Don't add this if it is a platform component that is marked
// to run in multiple processes, because this is actually
// part of the framework so doesn't make sense to track as a
// separate apk in the process.
app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
mService.mProcessStats);
}
//注释二
realStartActivityLocked(r, app, 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.
}
//注释三 调用ActivityManagerService 启动activity所在进程
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
首次启动App,app进程为空,会尝试创建app进程,不会执行realStartActivityLocked
创建ActivityThread实例,执行ActivityThread.attach(),创建Application。IPC向ActivityManagerService发送
attachApplication消息,之后进入Loop循环。(执行在新创建的app进程)
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
// See if the top visible activity is waiting to run in this process...
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
}
boolean attachApplicationLocked(ProcessRecord app){
realStartActivityLocked(activity, app,top == activity /* andResume */, true /* checkConfig */)) {
}
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
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, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
realStartActivityLocked 创建了一个LaunchActivityItem的事务,通过ApplicationThread
IPC发送给了新创建的app进程。
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
//(1)为Activity创建Context
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
//(2) 通过Instrumentation 创建Activity实例
activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent);
//获取Applciation实例
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
//(3)调用activity.attach()
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);
if (customIntent != null) {
activity.mIntent = customIntent;
}
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
//(4) 调用Instrumentation.callActivityOnCreate() 触发Activity生命周期
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
return activity;
}
至此Activity已经被启动起来了
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。