继System进程的启动流程第一部分,我们接着分析com.android.server.SystemServer的main函数。如下:
public class SystemServer
{
......
native public static void init1(String[] args);
......
public static void main(String[] args) {
......
init1(args);
......
}
public static final void init2() {
Slog.i(TAG, "Entered the Android system server!");
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
}
......
}
SystemServer类的静态成员函数main主要是调用静态成员函数init1来启动一些使用C++语言开发的系统服务。SystemServer类的静态成员函数init1是一个JNI方法,它是由C++层中的函数android_server_SystemServer_init1来实现的,如下:
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
system_init();
}
调用了system_init来启动一些使用C++语言开发的系统服务,它的实现如下:
extern "C" status_t system_init()
{
LOGI("Entered system_init()");
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm = defaultServiceManager();
LOGI("ServiceManager: %p\n", sm.get());
sp<GrimReaper> grim = new GrimReaper();
sm->asBinder()->linkToDeath(grim, grim.get(), 0);
char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsurfaceflinger", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// Start the SurfaceFlinger
SurfaceFlinger::instantiate();
}
// Start the sensor service
SensorService::instantiate();
// On the simulator, audioflinger et al don't get started the
// same way as on the device, and we need to start them here
if (!proc->supportsProcesses()) {
// Start the AudioFlinger
AudioFlinger::instantiate();
// Start the media playback service
MediaPlayerService::instantiate();
// Start the camera service
CameraService::instantiate();
// Start the audio policy service
AudioPolicyService::instantiate();
}
// And now start the Android runtime. We have to do this bit
// of nastiness because the Android runtime initialization requires
// some of the core system services to already be started.
// All other servers should just start the Android runtime at
// the beginning of their processes's main(), before calling
// the init function.
LOGI("System server: starting Android runtime.\n");
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
LOGI("System server: starting Android services.\n");
runtime->callStatic("com/android/server/SystemServer", "init2");
// If running in our own process, just go into the thread
// pool. Otherwise, call the initialization finished
// func to let this process continue its initilization.
if (proc->supportsProcesses()) {
LOGI("System server: entering thread pool.\n");
ProcessState::self()->startThreadPool();//已经启动过线程池了
IPCThreadState::self()->joinThreadPool();//当前主线程加入线程池
LOGI("System server: exiting thread pool.\n");
}
return NO_ERROR;
}
我们先说代码的最后,ProcessState::self()->startThreadPool(),在System进程的启动流程第一部分已经启动过了线程池;不用再启动了,因为mThreadPoolStarted已经至为true了。
接着joinThreadPool把当前主线程加入了线程池,至此SystemServer进程用于Binder线程间通信的线程池有两个了。
虚拟机环境JNIENV,请参考Dalvik虚拟机总结。AndroidRuntime类的静态方法callStatic如下:
status_t AndroidRuntime::callStatic(const char* className, const char* methodName)
{
JNIEnv* env;
jclass clazz;
jmethodID methodId;
env = getJNIEnv();
if (env == NULL)
return UNKNOWN_ERROR;
clazz = findClass(env, className);
if (clazz == NULL) {
LOGE("ERROR: could not find class '%s'\n", className);
return UNKNOWN_ERROR;
}
methodId = env->GetStaticMethodID(clazz, methodName, "()V");
if (methodId == NULL) {
LOGE("ERROR: could not find method %s.%s\n", className, methodName);
return UNKNOWN_ERROR;
}
env->CallStaticVoidMethod(clazz, methodId);//必须得有虚拟机环境JNIENV,才能解释执行java代码
return NO_ERROR;
}
执行SystemServer的init2方法,如下:
public static final void init2() {
Slog.i(TAG, "Entered the Android system server!");
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
}
thr.start()创建了一个Dalvik虚拟机线程,详细请参考Dalvik虚拟机进程和线程的创建过程分析。
class ServerThread extends Thread {
@Override
public void run() {
......
Looper.prepare();
......
try {
......
Slog.i(TAG, "Activity Manager");
context = ActivityManagerService.main(factoryTest);
......
Slog.i(TAG, "Package Manager");
pm = PackageManagerService.main(context,
factoryTest != SystemServer.FACTORY_TEST_OFF);//以后分析
ActivityManagerService.setSystemProcess();
......
((ActivityManagerService)ActivityManagerNative.getDefault())
.systemReady(new Runnable() {
public void run() {
}
});
......
} catch (RuntimeException e) {
Slog.e("System", "Failure starting core service", e);
}
......
Looper.loop();
Slog.d(TAG, "System ServerThread is exiting!");
}
}
Looper.prepare来为当前线程创建一个消息队列。Looper.loop循环等待消息的到来,如果没有消息当前线程就睡眠等待,除非线程退出,否则不会执行Looper.loop以后的代码。详细请参考Android系统源代码情景分析的第十三章,关于Android底层的书看这本就够了,我的博客绝大部分来源于此书。
我们主要分析ActivityMangerService的静态函数main,如下:
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
public static final Context main(int factoryTest) {
AThread thr = new AThread();
thr.start();
synchronized (thr) {
while (thr.mService == null) {
try {
thr.wait();
} catch (InterruptedException e) {
}
}
}
ActivityManagerService m = thr.mService;
mSelf = m;
ActivityThread at = ActivityThread.systemMain();
mSystemThread = at;
Context context = at.getSystemContext();
m.mContext = context;
m.mFactoryTest = factoryTest;
m.mMainStack = new ActivityStack(m, context, true);
m.mBatteryStatsService.publish(context);
m.mUsageStatsService.publish(context);
synchronized (thr) {
thr.mReady = true;
thr.notifyAll();
}
m.startRunning(null, null, null, null);
return context;
}
......
}
这个函数首先通过AThread线程对象来内部创建了一个ActivityManagerService实例,然后将这个实例保存其成员变量mService中,接着又把这个ActivityManagerService实例保存在ActivityManagerService类的静态成员变量mSelf中,最后初始化其它成员变量,就结束了。
ActivityManagerService.setSystemProcess,如下:
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
public static void setSystemProcess() {
try {
ActivityManagerService m = mSelf;
ServiceManager.addService("activity", m);
.....,
ApplicationInfo info =
mSelf.mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS);
mSystemThread.installSystemApplicationInfo(info);
synchronized (mSelf) {
......
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
}
......
}
这个函数首先是将这个ActivityManagerService实例添加到ServiceManager中去托管,这样其它地方就可以通过ServiceManager.getService接口来访问这个全局唯一的ActivityManagerService实例了,接着又通过调用mSystemThread.installSystemApplicationInfo函数来把应用程序框架层下面的android包加载进来 ,这里的mSystemThread是一个ActivityThread类型的实例变量,它是在上面的Step 7中创建的,后面就是一些其它的初始化工作了。
ServerThread.run函数在将系统中的一系列服务都初始化完毕之后,开始调用如下代码,启动Home Activity。
((ActivityManagerService)ActivityManagerNative.getDefault())
.systemReady(new Runnable() {
public void run() {
}
});
static public IActivityManager getDefault()
{
if (gDefault != null) {
//if (Config.LOGV) Log.v(
// "ActivityManager", "returning cur default = " + gDefault);
return gDefault;
}
IBinder b = ServiceManager.getService("activity");
if (Config.LOGV) Log.v(
"ActivityManager", "default service binder = " + b);
gDefault = asInterface(b);
if (Config.LOGV) Log.v(
"ActivityManager", "default service = " + gDefault);
return gDefault;
}
获取的其实就是本进程中的ActivityManagerService。
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
public void systemReady(final Runnable goingCallback) {
......
synchronized (this) {
......
mMainStack.resumeTopActivityLocked(null);
}
}
......
}
mMainStack已经在
ActivityMangerService的静态函数main设置了,调用如下:
public class ActivityStack {
......
final boolean resumeTopActivityLocked(ActivityRecord prev) {
// Find the first activity that is not finishing.
ActivityRecord next = topRunningActivityLocked(null);
......
if (next == null) {
// There are no more activities! Let's just start up the
// Launcher...
if (mMainStack) {
return mService.startHomeActivityLocked();
}
}
......
}
......
}
调用了ActivityManagerService的成员函数startHomeActivityLocked,启动Home界面,也就是HomeActivity,如下:
boolean startHomeActivityLocked() {
if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
&& mTopAction == null) {
// We are running in factory test mode, but unable to find
// the factory test app, so just sit around displaying the
// error message and don't try to start anything.
return false;
}
Intent intent = new Intent(
mTopAction,
mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
intent.addCategory(Intent.CATEGORY_HOME);
}
ActivityInfo aInfo =
intent.resolveActivityInfo(mContext.getPackageManager(),
STOCK_PM_FLAGS);
if (aInfo != null) {
intent.setComponent(new ComponentName(
aInfo.applicationInfo.packageName, aInfo.name));
// Don't do this if the home app is currently being
// instrumented.
ProcessRecord app = getProcessRecordLocked(aInfo.processName,
aInfo.applicationInfo.uid);
if (app == null || app.instrumentationClass == null) {
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
null, null, 0, 0, 0, false, false);
}
}
return true;
}
接下去就调用startActivityLocked进一步处理了。
public class ActivityStack {
......
final int startActivityLocked(IApplicationThread caller,
Intent intent, String resolvedType,
Uri[] grantedUriPermissions,
int grantedMode, ActivityInfo aInfo, IBinder resultTo,
String resultWho, int requestCode,
int callingPid, int callingUid, boolean onlyIfNeeded,
boolean componentSpecified) {
int err = START_SUCCESS;
ProcessRecord callerApp = null;
if (caller != null) {//为空
callerApp = mService.getRecordForAppLocked(caller);
if (callerApp != null) {
callingPid = callerApp.pid;
callingUid = callerApp.info.uid;
} else {
......
}
}
......
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {//为空
int index = indexOfTokenLocked(resultTo);
......
if (index >= 0) {
sourceRecord = (ActivityRecord)mHistory.get(index);
if (requestCode >= 0 && !sourceRecord.finishing) {
......
}
}
}
int launchFlags = intent.getFlags();
if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
&& sourceRecord != null) {
......
}
if (err == START_SUCCESS && intent.getComponent() == null) {
......
}
if (err == START_SUCCESS && aInfo == null) {
......
}
if (err != START_SUCCESS) {
......
}
......
ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
intent, resolvedType, aInfo, mService.mConfiguration,
resultRecord, resultWho, requestCode, componentSpecified);//注意这里面的mService,inte
......
return startActivityUncheckedLocked(r, sourceRecord,
grantedUriPermissions, grantedMode, onlyIfNeeded, true);//soucerRecord为NULL
}
......
}
接着调用startActivityUncheckedLocked函数进行下一步操作,如下:
public class ActivityStack {
......
final int startActivityUncheckedLocked(ActivityRecord r,
ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
int grantedMode, boolean onlyIfNeeded, boolean doResume) {
final Intent intent = r.intent;
final int callingUid = r.launchedFromUid;
int launchFlags = intent.getFlags();
// We'll invoke onUserLeaving before onPause only if the launching
// activity did not explicitly state that this is an automated launch.
mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
......
ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
!= 0 ? r : null;
// If the onlyIfNeeded flag is set, then we can do this if the activity
// being launched is the same as the one making the call... or, as
// a special case, if we do not know the caller then we count the
// current top activity as the caller.
if (onlyIfNeeded) {
......
}
if (sourceRecord == null) {
......
} else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
......
} else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
......
}
if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
......
}
boolean addingToTask = false;
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
// If bring to front is requested, and no result is requested, and
// we can find a task that was started with this same
// component, then instead of launching bring that one to the front.
if (r.resultTo == null) {
// See if there is a task to bring to the front. If this is
// a SINGLE_INSTANCE activity, there can be one and only one
// instance of it in the history, and it is always in its own
// unique task, so we do a special search.
ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
? findTaskLocked(intent, r.info)
: findActivityLocked(intent, r.info);
if (taskTop != null) {
......
}
}
}
......
if (r.packageName != null) {
// If the activity being launched is the same as the one currently
// at the top, then we need to check if it should only be launched
// once.
ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
if (top != null && r.resultTo == null) {
if (top.realActivity.equals(r.realActivity)) {
......
}
}
} else {
......
}
boolean newTask = false;
// Should this be considered a new task?
if (r.resultTo == null && !addingToTask
&& (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { //由于lauchFlags等于FLAG_ACTIVITY_NEW_TASK
// todo: should do better management of integers.
mService.mCurTask++;
if (mService.mCurTask <= 0) {
mService.mCurTask = 1;
}
r.task = new TaskRecord(mService.mCurTask, r.info, intent,
(r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);//新建了一个Task,新建的Task保存在r.task域中
......
newTask = true;
if (mMainStack) {
mService.addRecentTaskLocked(r.task);//同时,添加到mService中去,这里的mService就是ActivityManagerService了
}
} else if (sourceRecord != null) {
......
} else {
......
}
......
startActivityLocked(r, newTask, doResume);
return START_SUCCESS;
}
......
}
最后就进入startActivityLocked(r, newTask, doResume)进一步处理了。
public class ActivityStack {
......
private final void startActivityLocked(ActivityRecord r, boolean newTask,
boolean doResume) {
final int NH = mHistory.size();//NH为0
int addPos = -1;
if (!newTask) {
......
}
// Place a new activity at top of stack, so it is next to interact
// with the user.
if (addPos < 0) {
addPos = NH;//addPos为0
}
// If we are not placing the new activity frontmost, we do not want
// to deliver the onUserLeaving callback to the actual frontmost
// activity
if (addPos < NH) {
......
}
// Slot the activity into the history stack and proceed
mHistory.add(addPos, r);//加入Launcher的ActivityRecord
r.inHistory = true;
r.frontOfTask = newTask;
r.task.numActivities++;
if (NH > 0) {
// We want to show the starting preview window if we are
// switching to a new task, or the next activity's process is
// not currently running.
......
} else {
// If this is the first activity, don't do any fancy animations,
// because there is nothing for it to animate on top of.
......
}
......
if (doResume) {
resumeTopActivityLocked(null);
}
}
......
}
这里传进来的参数doResume为true,于是调用resumeTopActivityLocked进一步操作。
public class ActivityStack {
......
final boolean resumeTopActivityLocked(ActivityRecord prev) {
......
// Find the first activity that is not finishing.
ActivityRecord next = topRunningActivityLocked(null);
// Remember how we'll process this pause/resume situation, and ensure
// that the state is reset however we wind up proceeding.
final boolean userLeaving = mUserLeaving;
mUserLeaving = false;
......
next.delayedResume = false;
// If the top activity is the resumed one, nothing to do.
if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
......
return false;
}
// If we are sleeping, and there is no resumed activity, and the top
// activity is paused, well that is the state we want.
if ((mService.mSleeping || mService.mShuttingDown)
&& mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
......
return false;
}
.......
// We need to start pausing the current activity so the top one
// can be resumed...
if (mResumedActivity != null) {//Launcher是第一个Activity,所以mResumeActivity为null
......
return true;
}
......
if (next.app != null && next.app.thread != null) {
......
} else {
......
startSpecificActivityLocked(next, true, true);
}
return true;
}
......
}
由于刚创建了Launcher的ActivityRecord,其app为null。所以执行startSpecificActivityLocked。
public class ActivityStack {
......
private final void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid);//根据进程名和进程uid就可以为每一个应用程序创建一个ProcessRecord
......
if (app != null && app.thread != null) {//由于是第一次启动应用程序的Activity,取回来的app为NULL
try {
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
......
}
}
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false);
}
......
}
函数最终执行ActivityManagerService.startProcessLocked函数进行下一步操作。
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
ProcessRecord app = getProcessRecordLocked(processName, info.uid);
......
String hostingNameStr = hostingName != null
? hostingName.flattenToShortString() : null;
......
if (app == null) {
app = new ProcessRecordLocked(null, info, processName);
mProcessNames.put(processName, info.uid, app);
} else {
// If this is a new package in the process, add the package to the list
app.addPackage(info.packageName);
}
......
startProcessLocked(app, hostingType, hostingNameStr);
return (app.pid != 0) ? app : null;
}
......
}
这里再次检查是否已经有以process + uid命名的进程存在,在我们这个情景中,返回值app为null,因此,后面会创建一个ProcessRecord,并存保存在成员变量mProcessNames中,最后,调用另一个startProcessLocked函数进一步操作:
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
private final void startProcessLocked(ProcessRecord app,
String hostingType, String hostingNameStr) {
......
try {
int uid = app.info.uid;
int[] gids = null;
try {
gids = mContext.getPackageManager().getPackageGids(
app.info.packageName);
} catch (PackageManager.NameNotFoundException e) {
......
}
......
int debugFlags = 0;
......
int pid = Process.start("android.app.ActivityThread",
mSimpleProcessManagement ? app.processName : null, uid, uid,//新进程的uid,gid
gids, debugFlags, null);
......
if (pid == 0 || pid == MY_PID) {
......
} else if (pid > 0) {
app.pid = pid;
app.removed = false;
synchronized (mPidsSelfLocked) {
this.mPidsSelfLocked.put(pid, app);//以变量pid为关键字将参数app所指向的一个ProcessRecord对象保存在mPidSelfLocked中
Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
msg.obj = app;
mHandler.sendMessageDelayed(msg, PROC_START_TIMEOUT);
}
} else {
......
}
......
} catch (RuntimeException e) {
......
}
}
......
}
这里主要是调用Process.start接口来创建一个新的进程,新的进程会导入android.app.ActivityThread类,并且执行它的main函数,这就是为什么我们前面说每一个应用程序都有一个ActivityThread实例来对应的原因。
我们下篇文章再分析Launcher进程的创建。
在Launcher进程的启动一文中,Zygote进程会向System进程发送pid,如下:
try {
mSocketOutStream.writeInt(pid);//向System进程写回pid
} catch (IOException ex) {
Log.e(TAG, "Error reading from command socket", ex);
return true;
}
此时Process.start返回后,会继续运行,此时pid大于0。
继续运行,会向ActivityManagerService所运行的线程的消息队列发送一个类型为PROC_START_TIMEOUT_MSG的消息,并且指定这个消息在PROC_START_TIMEOUT毫秒之后处理,也就是新的应用程序进程必须在PROC_START_TIMEOUT毫秒之内完成启动工作。
这个线程其实就是下面的线程:
class ServerThread extends Thread {
@Override
public void run() {
......
Looper.prepare();//准备
......
try {
......
Slog.i(TAG, "Activity Manager");
context = ActivityManagerService.main(factoryTest);
......
Slog.i(TAG, "Package Manager");
pm = PackageManagerService.main(context,
factoryTest != SystemServer.FACTORY_TEST_OFF);//以后分析
ActivityManagerService.setSystemProcess();
......
((ActivityManagerService)ActivityManagerNative.getDefault())
.systemReady(new Runnable() {
public void run() {
}
});
......
} catch (RuntimeException e) {
Slog.e("System", "Failure starting core service", e);
}
......
Looper.loop();//循环处理
Slog.d(TAG, "System ServerThread is exiting!");
}
}
这个消息会在以后的代码中移除,表示没有超时。