在上一篇中已经提到了,分为两步,一步是开始activity,一步是创建进程,在上面的一篇中已经把开启
开启activity的部分讲到了,下面说下应用是怎么创建进程的.其中大量参考了gityuan先生的博客。并
根据博客的指示,来把代码跟了一遍.
/frameworks/base/core/java/com/android/internal/os/
- ZygoteInit.java
- ZygoteConnection.java
- RuntimeInit.java
- Zygote.java
/frameworks/base/core/java/android/os/Process.java
/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
/frameworks/base/core/jni/AndroidRuntime.cpp
/frameworks/base/cmds/app_process/App_main.cpp (内含AppRuntime类)
/bionic/libc/bionic/fork.cpp
/bionic/libc/bionic/pthread_atfork.cpp
/libcore/dalvik/src/main/java/dalvik/system/ZygoteHooks.java
/art/runtime/native/dalvik_system_ZygoteHooks.cc
/art/runtime/Runtime.cc
/art/runtime/Thread.cc
/art/runtime/signal_catcher.cc
在前面说到,启动进程的时候会调用的AMS类里面的startProcessLocked方法,最终还会调用到
Process.start这个方法
public static final ProcessStartResult start(final String processClass,
480 final String niceName,
481 int uid, int gid, int[] gids,
482 int runtimeFlags, int mountExternal,
483 int targetSdkVersion,
484 String seInfo,
485 String abi,
486 String instructionSet,
487 String appDataDir,
488 String invokeWith,
489 String[] zygoteArgs) {
490 return zygoteProcess.start(processClass, niceName, uid, gid, gids,
491 runtimeFlags, mountExternal, targetSdkVersion, seInfo,
492 abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
493 }
接着调用ZygoteProcess.java里面的startViaZygote方法
private Process.ProcessStartResult startViaZygote(final String processClass,
358 final String niceName,
359 final int uid, final int gid,
360 final int[] gids,
361 int runtimeFlags, int mountExternal,
362 int targetSdkVersion,
363 String seInfo,
364 String abi,
365 String instructionSet,
366 String appDataDir,
367 String invokeWith,
368 boolean startChildZygote,
369 String[] extraArgs)
370 throws ZygoteStartFailedEx {
371 .........................................................................
436
437 synchronized(mLock) {
438 return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
439 }
440 }
向在zygote进程里面注册的socket发送消息,在zygote进程里面注册新的进程.
private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
281 ZygoteState zygoteState, ArrayList<String> args)
282 throws ZygoteStartFailedEx {
283 try {
284 // Throw early if any of the arguments are malformed. This means we can
285 // avoid writing a partial response to the zygote.
286 int sz = args.size();
287 for (int i = 0; i < sz; i++) {
288 if (args.get(i).indexOf('\n') >= 0) {
289 throw new ZygoteStartFailedEx("embedded newlines not allowed");
290 }
291 }
292
293 /**
294 * See com.android.internal.os.SystemZygoteInit.readArgumentList()
295 * Presently the wire format to the zygote process is:
296 * a) a count of arguments (argc, in essence)
297 * b) a number of newline-separated argument strings equal to count
298 *
299 * After the zygote process reads these it will write the pid of
300 * the child or -1 on failure, followed by boolean to
301 * indicate whether a wrapper process was used.
302 */
303 final BufferedWriter writer = zygoteState.writer;
//拿到输入流,写入服务器
304 final DataInputStream inputStream = zygoteState.inputStream;
305
306 writer.write(Integer.toString(args.size()));
307 writer.newLine();
308
309 for (int i = 0; i < sz; i++) {
310 String arg = args.get(i);
311 writer.write(arg);
312 writer.newLine();
313 }
314
315 writer.flush();
316
317 // Should there be a timeout on this?
318 Process.ProcessStartResult result = new Process.ProcessStartResult();
319
320 // Always read the entire result from the input stream to avoid leaving
321 // bytes in the stream for future process starts to accidentally stumble
322 // upon.
//等待返回的pid
323 result.pid = inputStream.readInt();
324 result.usingWrapper = inputStream.readBoolean();
325
326 if (result.pid < 0) {
327 throw new ZygoteStartFailedEx("fork() failed");
328 }
329 return result;
330 } catch (IOException ex) {
331 zygoteState.close();
332 throw new ZygoteStartFailedEx(ex);
333 }
334 }
去链接远程的socket
@GuardedBy("mLock")
563 private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
564 Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
565
566 if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
567 try {
568 primaryZygoteState = ZygoteState.connect(mSocket);
569 } catch (IOException ioe) {
570 throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
571 }
572 maybeSetApiBlacklistExemptions(primaryZygoteState, false);
573 maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
574 }
575 if (primaryZygoteState.matches(abi)) {
576 return primaryZygoteState;
577 }
578
579 // The primary zygote didn't match. Try the secondary.
580 if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
581 try {
582 secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
583 } catch (IOException ioe) {
584 throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
585 }
586 maybeSetApiBlacklistExemptions(secondaryZygoteState, false);
587 maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
588 }
589
590 if (secondaryZygoteState.matches(abi)) {
591 return secondaryZygoteState;
592 }
593
594 throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
595 }
596
在前面已经说了, zygot是由init进程创建的,启动起来后会调用ZygoteInit.main方法,创建socket管道
然后runSelectLoop(),的带客户端发消息来创建进程
这些都在前面的章节中讲过,大致的伪代码
public static void main(String argv[]) {
try {
runSelectLoop(abiList); //【见小节5】
....
} catch (MethodAndArgsCaller caller) {
caller.run(); //【见小节16】
} catch (RuntimeException ex) {
closeServerSocket();
throw ex;
}
}
查看runSelectLoop方法
Runnable runSelectLoop(String abiList) {
174 ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
175 ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
176
177 fds.add(mServerSocket.getFileDescriptor());
178 peers.add(null);
179
180 while (true) {
181 StructPollfd[] pollFds = new StructPollfd[fds.size()];
182 for (int i = 0; i < pollFds.length; ++i) {
183 pollFds[i] = new StructPollfd();
184 pollFds[i].fd = fds.get(i);
185 pollFds[i].events = (short) POLLIN;
186 }
187 try {
188 Os.poll(pollFds, -1);
189 } catch (ErrnoException ex) {
190 throw new RuntimeException("poll failed", ex);
191 }
192 for (int i = pollFds.length - 1; i >= 0; --i) {
193 if ((pollFds[i].revents & POLLIN) == 0) {
194 continue;
195 }
196
197 if (i == 0) {
//等待远程命令
198 ZygoteConnection newPeer = acceptCommandPeer(abiList);
199 peers.add(newPeer);
200 fds.add(newPeer.getFileDesciptor());
201 } else {
202 try {
203 ZygoteConnection connection = peers.get(i);
//获取到客户端发来的消息,来创建进程,看下面分析
204 final Runnable command = connection.processOneCommand(this);
205
206 if (mIsForkChild) {
207 // We're in the child. We should always have a command to run at this
208 // stage if processOneCommand hasn't called "exec".
209 if (command == null) {
210 throw new IllegalStateException("command == null");
211 }
212
213 return command;
214 } else {
215 // We're in the server - we should never have any commands to run.
216 if (command != null) {
217 throw new IllegalStateException("command != null");
218 }
219
220 // We don't know whether the remote side of the socket was closed or
221 // not until we attempt to read from it from processOneCommand. This shows up as
222 // a regular POLLIN event in our regular processing loop.
223 if (connection.isClosedByPeer()) {
224 connection.closeSocket();
225 peers.remove(i);
226 fds.remove(i);
227 }
228 }
229 } catch (Exception e) {
230 if (!mIsForkChild) {
231 // We're in the server so any exception here is one that has taken place
232 // pre-fork while processing commands or reading / writing from the
233 // control socket. Make a loud noise about any such exceptions so that
234 // we know exactly what failed and why.
235
236 Slog.e(TAG, "Exception executing zygote command: ", e);
237
238 // Make sure the socket is closed so that the other end knows immediately
239 // that something has gone wrong and doesn't time out waiting for a
240 // response.
241 ZygoteConnection conn = peers.remove(i);
242 conn.closeSocket();
243
244 fds.remove(i);
245 } else {
246 // We're in the child so any exception caught here has happened post
247 // fork and before we execute ActivityThread.main (or any other main()
248 // method). Log the details of the exception and bring down the process.
249 Log.e(TAG, "Caught post-fork exception in child process.", e);
250 throw e;
251 }
252 } finally {
253 // Reset the child flag, in the event that the child process is a child-
254 // zygote. The flag will not be consulted this loop pass after the Runnable
255 // is returned.
256 mIsForkChild = false;
257 }
258 }
259 }
260 }
261 }
调用ZygoteConnection 类里面的函数
Runnable processOneCommand(ZygoteServer zygoteServer) {
124 String args[];
125 .....................................................
233
//fork进程
234 pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
235 parsedArgs.runtimeFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
236 parsedArgs.niceName, fdsToClose, fdsToIgnore, parsedArgs.startChildZygote,
237 parsedArgs.instructionSet, parsedArgs.appDataDir);
238
239 try {
240 if (pid == 0) {
241 // in child
242 zygoteServer.setForkChild();
243
244 zygoteServer.closeServerSocket();
245 IoUtils.closeQuietly(serverPipeFd);
246 serverPipeFd = null;
247
248 return handleChildProc(parsedArgs, descriptors, childPipeFd,
249 parsedArgs.startChildZygote);
250 } else {
251 // In the parent. A pid < 0 indicates a failure and will be handled in
252 // handleParentProc.
253 IoUtils.closeQuietly(childPipeFd);
254 childPipeFd = null;
255 handleParentProc(pid, descriptors, serverPipeFd);
256 return null;
257 }
258 } finally {
259 IoUtils.closeQuietly(childPipeFd);
260 IoUtils.closeQuietly(serverPipeFd);
261 }
262 }
在Zygote.java中
public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
134 int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
135 int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir) {
136 VM_HOOKS.preFork();
137 // Resets nice priority for zygote process.
138 resetNicePriority();
139 int pid = nativeForkAndSpecialize(
140 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
141 fdsToIgnore, startChildZygote, instructionSet, appDataDir);
142 // Enable tracing as soon as possible for the child process.
143 if (pid == 0) {
144 Trace.setTracingEnabled(true, runtimeFlags);
145
146 // Note that this event ends at the end of handleChildProc,
147 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
148 }
149 VM_HOOKS.postForkCommon();
150 return pid;
151 }
查看nativeForkAndSpecialize方法,调用到jni里面的方法com_android_internal_os_Zygote.cpp
public static int nativeForkAndSpecialize() { ………….. ForkAndSpecializeCommon(); ………….. }
从一个App的角度来看,应用启动很简单,只用调用一下Activity中的startActivity方法就行了.但是背后
发生了什么?我想不管是一个App开发者还是FW开发者都应该掌握的.
我把这部分大致分为两个部分.
1. 开启Activity
2. 创建新的进程
ActivityThread : 主要的App入口,一个应用的主线程
ApplicationThread : 代理类,继承了aidl接口, 在ActivityThread成员变量中创建
Instrumentation : 负责发起Activity的启动、并具体负责Activity的创建以及Activity生命周期的回调
一个应用里面只有一个Instrumentation对象,并且这个对象是在ActivityThread中创建的
ActivityManagerService :管理所有Activity, 并且Acivity通过binder跨进程发送信息给
AMS,然后AMS通过Socket来创建进程.
ActivityStack : Activity在AMS的栈管理,用来记录已经启动的Activity的先后关系,状态信息等通
过ActivityStack决定是否需要启动新的进程。
ActivityRecord:ActivityStack的管理对象,每个Activity在AMS对应一个ActivityRecord,
来记录Activity的状态以及其他的管理信息。其实就是服务器端的Activity对象的映像
在Activity中调用startActivity最终会调用到startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
//没有设置父的Activity
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
//开启execStartActivity,mMainThread创建进程的时候的
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
// TODO Consider clearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
接着调用 execStartActivity
public ActivityResult execStartActivity(
1636 Context who, IBinder contextThread, IBinder token, Activity target,
1637 Intent intent, int requestCode, Bundle options) {
1638 .......................
1665 try {
1666 intent.migrateExtraStreamToClipData();
1667 intent.prepareToLeaveProcess(who);
//通过binder获取AMS,实际上是调用的AMS中的startActivity
1668 int result = ActivityManager.getService()
1669 .startActivity(whoThread, who.getBasePackageName(), intent,
1670 intent.resolveTypeIfNeeded(who.getContentResolver()),
1671 token, target != null ? target.mEmbeddedID : null,
1672 requestCode, 0, null, options);
1673 checkStartActivityResult(result, intent);
1674 } catch (RemoteException e) {
1675 throw new RuntimeException("Failure from system", e);
1676 }
1677 return null;
........................
1678 }
1679
可以看下ActivityManager.getService()实现
/**
4123 * @hide
4124 */
4125 public static IActivityManager getService() {
4126 return IActivityManagerSingleton.get();
4127 }
4128
4129 private static final Singleton<IActivityManager> IActivityManagerSingleton =
4130 new Singleton<IActivityManager>() {
4131 @Override
4132 protected IActivityManager create() {
4133 final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
//就是AMS的binder接口
4134 final IActivityManager am = IActivityManager.Stub.asInterface(b);
4135 return am;
4136 }
4137 };
在AMS里面调用startActivity方法:
@Override
5079 public final int startActivity(IApplicationThread caller, String callingPackage,
5080 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
5081 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
5082 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
5083 resultWho, requestCode, startFlags, profilerInfo, bOptions,
5084 UserHandle.getCallingUserId());
5085 }
这个地方其实和8.0的代码差别还是挺大的.mActivityStartController这个地方做了一个封装,运用建造者模式.
看来设计模式还要好好学学呀。源码中处处有设计模式的思想
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
5097 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
5098 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
5099 boolean validateIncomingUser) {
5100 enforceNotIsolatedCaller("startActivity");
5101
5102 userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
5103 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
5104
5105 // TODO: Switch to user app stacks here.
5106 return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
5107 .setCaller(caller)
5108 .setCallingPackage(callingPackage)
5109 .setResolvedType(resolvedType)
5110 .setResultTo(resultTo)
5111 .setResultWho(resultWho)
5112 .setRequestCode(requestCode)
5113 .setStartFlags(startFlags)
5114 .setProfilerInfo(profilerInfo)
5115 .setActivityOptions(bOptions)
5116 .setMayWait(userId)
5117 .execute();
5118
5119 }
5120
接着查看mActivityStartController类里面的obtainStarter方法
我就把这些全部都拿过来了.从代码里面看,构造函数里面传进了DefaultFactory.那接着查看DefaultFactory
在哪里创建。
ActivityStartController(ActivityManagerService service) {
115 this(service, service.mStackSupervisor,
116 new DefaultFactory(service, service.mStackSupervisor,
117 new ActivityStartInterceptor(service, service.mStackSupervisor)));
118 }
119
120 @VisibleForTesting
121 ActivityStartController(ActivityManagerService service, ActivityStackSupervisor supervisor,
122 Factory factory) {
123 mService = service;
124 mSupervisor = supervisor;
125 mHandler = new StartHandler(mService.mHandlerThread.getLooper());
126 mFactory = factory;
127 mFactory.setController(this);
128 mPendingRemoteAnimationRegistry = new PendingRemoteAnimationRegistry(service,
129 service.mHandler);
130 }
131
132 /**
133 * @return A starter to configure and execute starting an activity. It is valid until after
134 * {@link ActivityStarter#execute} is invoked. At that point, the starter should be
135 * considered invalid and no longer modified or used.
136 */
137 ActivityStarter obtainStarter(Intent intent, String reason) {
138 return mFactory.obtain().setIntent(intent).setReason(reason);
139 }
140
在ActivityStarter里面定义了DefaultFactory,其实就是调用ActivityStarter的execute()方法
static class DefaultFactory implements Factory {
227 /**
228 * The maximum count of starters that should be active at one time:
229 * 1. last ran starter (for logging and post activity processing)
230 * 2. current running starter
231 * 3. starter from re-entry in (2)
232 */
233 private final int MAX_STARTER_COUNT = 3;
234
235 private ActivityStartController mController;
236 private ActivityManagerService mService;
237 private ActivityStackSupervisor mSupervisor;
238 private ActivityStartInterceptor mInterceptor;
239
240 private SynchronizedPool<ActivityStarter> mStarterPool =
241 new SynchronizedPool<>(MAX_STARTER_COUNT);
242
243 DefaultFactory(ActivityManagerService service,
244 ActivityStackSupervisor supervisor, ActivityStartInterceptor interceptor) {
245 mService = service;
246 mSupervisor = supervisor;
247 mInterceptor = interceptor;
248 }
249
250 @Override
251 public void setController(ActivityStartController controller) {
252 mController = controller;
253 }
254
255 @Override
256 public ActivityStarter obtain() {
257 ActivityStarter starter = mStarterPool.acquire();
258
259 if (starter == null) {
260 starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
261 }
262
263 return starter;
264 }
265
266 @Override
267 public void recycle(ActivityStarter starter) {
268 starter.reset(true /* clearRequest*/);
269 mStarterPool.release(starter);
270 }
271 }
最终调用到的是ActivityStarter的execute方法. 这里我就省略一下了
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
1194 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1195 int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
1196 ActivityRecord[] outActivity) {
1197
1199 mService.mWindowManager.deferSurfaceLayout();
1200 result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
1201 startFlags, doResume, options, inTask, outActivity);
1202
1213
1214 postStartActivityProcessing(r, result, mTargetStack);
1215
1216 return result;
1217 }
接着调用ActivityStarter的startActivityUnchecked方法
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
1221 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1222 int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
1223 ActivityRecord[] outActivity) {
1224
1225 setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
1226 voiceInteractor);
1227
1228 computeLaunchingTaskFlags();
1229
1230 computeSourceStack();
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
mSupervisor.resumeFocusedStackTopActivityLocked();
1231}
boolean resumeFocusedStackTopActivityLocked(
2215 ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
2216
2217 if (!readyToResume()) {
2218 return false;
2219 }
2220
2221 if (targetStack != null && isFocusedStack(targetStack)) {
2222 return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
2223 }
2224
2225 final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2226 if (r == null || !r.isState(RESUMED)) {
//调用ActivityStack.java的resumeTopActivityUncheckedLocked
2227 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
2228 } else if (r.isState(RESUMED)) {
2229 // Kick off any lingering app transitions form the MoveTaskToFront operation.
2230 mFocusedStack.executeAppTransition(targetOptions);
2231 }
2232
2233 return false;
2234 }
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
2283 if (mStackSupervisor.inResumeTopActivity) {
2284 // Don't even start recursing.
2285 return false;
2286 }
2287
2288 boolean result = false;
2289 try {
2290 // Protect against recursion.
2291 mStackSupervisor.inResumeTopActivity = true;
//自身的resumeTopActivityInnerLocked方法啊
2292 result = resumeTopActivityInnerLocked(prev, options);
2293
2294 // When resuming the top activity, it may be necessary to pause the top activity (for
2295 // example, returning to the lock screen. We suppress the normal pause logic in
2296 // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
2297 // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
2298 // to ensure any necessary pause logic occurs. In the case where the Activity will be
2299 // shown regardless of the lock screen, the call to
2300 // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
2301 final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
2302 if (next == null || !next.canTurnScreenOn()) {
2303 checkReadyForSleep();
2304 }
2305 } finally {
2306 mStackSupervisor.inResumeTopActivity = false;
2307 }
2308
2309 return result;
2310 }
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
if (mResumedActivity != null) {
2443 if (DEBUG_STATES) Slog.d(TAG_STATES,
2444 "resumeTopActivityLocked: Pausing " + mResumedActivity);
//当前的Activiyt肯定执行了resume,所以先调用了自己的onPause方法,通过IPC通信
2445 pausing |= startPausingLocked(userLeaving, false, next, false);
2446 }
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
这个地方要注意, 如果这个进程没有启动过,
# com.android.server.am.ActivityStackSupervisor
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
...
//这个地方取出来的为null,所以肯定会先创建进程
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1682 r.info.applicationInfo.uid, true);
1683
if (app != null && app.thread != 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, false, true);
}
上面的startProcessLocked会通过ActivityThread这个类创建一个进程,这个会在下面一个章节中讲解
这个地方先记着,会调用到ActivityThread的main函数.创建一个新进程
public static void main(String[] args) {
6624 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
6625
6626 // CloseGuard defaults to true and can be quite spammy. We
6627 // disable it here, but selectively enable it later (via
6628 // StrictMode) on debug builds, but using DropBox, not logs.
6629 CloseGuard.setEnabled(false);
6630
6631 Environment.initForCurrentUser();
6632
6633 // Set the reporter for event logging in libcore
6634 EventLogger.setReporter(new EventLoggingReporter());
6635
6636 // Make sure TrustedCertificateStore looks in the right place for CA certificates
6637 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
6638 TrustedCertificateStore.setDefaultUserDirectory(configDir);
6639
6640 Process.setArgV0("<pre-initialized>");
6641
6642 Looper.prepareMainLooper();
6643
6644 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
6645 // It will be in the format "seq=114"
6646 long startSeq = 0;
6647 if (args != null) {
6648 for (int i = args.length - 1; i >= 0; --i) {
6649 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
6650 startSeq = Long.parseLong(
6651 args[i].substring(PROC_START_SEQ_IDENT.length()));
6652 }
6653 }
6654 }
//创建ActivityThread对象,
6655 ActivityThread thread = new ActivityThread();
6656 thread.attach(false, startSeq);
6657
6658 if (sMainThreadHandler == null) {
6659 sMainThreadHandler = thread.getHandler();
6660 }
6661
6662 if (false) {
6663 Looper.myLooper().setMessageLogging(new
6664 LogPrinter(Log.DEBUG, "ActivityThread"));
6665 }
6666
6667 // End of event ActivityThreadMain.
6668 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//开启looper循环,确保进程不退出
6669 Looper.loop();
6670
6671 throw new RuntimeException("Main thread loop unexpectedly exited");
6672 }
6673
函数attach最终调用了ActivityManagerService的远程接口ActivityManagerProxy的attachApplication函数,
传入的参数是mAppThread,这是一个ApplicationThread类型的Binder对象,它的作用是用来进行进程间通信的。
private void attach(boolean system, long startSeq) {
6479 sCurrentActivityThread = this;
6480 mSystemThread = system;
6481 if (!system) {
6482 ViewRootImpl.addFirstDrawHandler(new Runnable() {
6483 @Override
6484 public void run() {
6485 ensureJitEnabled();
6486 }
6487 });
6488 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
6489 UserHandle.myUserId());
6490 RuntimeInit.setApplicationObject(mAppThread.asBinder());
//获取到AMS对象
6491 final IActivityManager mgr = ActivityManager.getService();
6492 try {
//这个地方回调到AMS里面的attachApplication方法
6493 mgr.attachApplication(mAppThread, startSeq);
6494 } catch (RemoteException ex) {
6495 throw ex.rethrowFromSystemServer();
6496 }
6497 // Watch for getting close to heap limit.
6498 BinderInternal.addGcWatcher(new Runnable() {
6499 @Override public void run() {
6500 if (!mSomeActivitiesChanged) {
6501 return;
6502 }
6503 Runtime runtime = Runtime.getRuntime();
6504 long dalvikMax = runtime.maxMemory();
6505 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
6506 if (dalvikUsed > ((3*dalvikMax)/4)) {
6507 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
6508 + " total=" + (runtime.totalMemory()/1024)
6509 + " used=" + (dalvikUsed/1024));
6510 mSomeActivitiesChanged = false;
6511 try {
6512 mgr.releaseSomeActivities(mAppThread);
6513 } catch (RemoteException e) {
6514 throw e.rethrowFromSystemServer();
6515 }
6516 }
6517 }
6518 });
上面获取到AMS并且调用到AMS里面的attachApplication方法, 接着调用AMS里面的attachApplicationLocked方法,
private final boolean attachApplicationLocked(IApplicationThread thread,
7573 int pid, int callingUid, long startSeq) {
// See if the top visible activity is waiting to run in this process...
7867 if (normalMode) {
7868 try {
//调用ActivityStackSupervisor.java里面的attachApplicationLocked方法
7869 if (mStackSupervisor.attachApplicationLocked(app)) {
7870 didSomething = true;
7871 }
7872 } catch (Exception e) {
7873 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
7874 badApp = true;
7875 }
7876 }
}
ActivityStackSupervisor类里面的attachApplicationLocked方法
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
972 final String processName = app.processName;
973 boolean didSomething = false;
974 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
975 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
976 for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
977 final ActivityStack stack = display.getChildAt(stackNdx);
978 if (!isFocusedStack(stack)) {
979 continue;
980 }
981 stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
982 final ActivityRecord top = stack.topRunningActivityLocked();
983 final int size = mTmpActivityList.size();
984 for (int i = 0; i < size; i++) {
985 final ActivityRecord activity = mTmpActivityList.get(i);
986 if (activity.app == null && app.uid == activity.info.applicationInfo.uid
987 && processName.equals(activity.processName)) {
988 try {
// startActivity
989 if (realStartActivityLocked(activity, app,
990 top == activity /* andResume */, true /* checkConfig */)) {
991 didSomething = true;
992 }
993 } catch (RemoteException e) {
994 Slog.w(TAG, "Exception in new application when starting activity "
995 + top.intent.getComponent().flattenToShortString(), e);
996 throw e;
997 }
998 }
999 }
1000 }
1001 }
1002 if (!didSomething) {
1003 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1004 }
1005 return didSomething;
1006 }
通过realStartActivityLocked方法来调用scheduleTransaction方法
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1378 boolean andResume, boolean checkConfig) throws RemoteException {
// Create activity launch transaction.
1523 final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
1524 r.appToken);
1525 clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
1526 System.identityHashCode(r), r.info,
1527 // TODO: Have this take the merged configuration instead of separate global
1528 // and override configs.
1529 mergedConfiguration.getGlobalConfiguration(),
1530 mergedConfiguration.getOverrideConfiguration(), r.compat,
1531 r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1532 r.persistentState, results, newIntents, mService.isNextTransitionForward(),
1533 profilerInfo));
1534
1535 // Set desired final state.
1536 final ActivityLifecycleItem lifecycleItem;
1537 if (andResume) {
1538 lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
1539 } else {
1540 lifecycleItem = PauseActivityItem.obtain();
1541 }
1542 clientTransaction.setLifecycleStateRequest(lifecycleItem);
1543
1544 // Schedule transaction.//在9.0上面这个地方重构了全部转化为Transaction一类的方法来
// 调用launch
1545 mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
调用ClientLifecycleManager 里面的scheduleTransaction方法
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
46 final IApplicationThread client = transaction.getClient();
47 transaction.schedule();
48 if (!(client instanceof Binder)) {
49 // If client is not an instance of Binder - it's a remote call and at this point it is
50 // safe to recycle the object. All objects used for local calls will be recycled after
51 // the transaction is executed on client in ActivityThread.
52 transaction.recycle();
53 }
54 }
其实是调用了ClientTransaction中的schedule方法
private IApplicationThread mClient;
public void schedule() throws RemoteException {
129 mClient.scheduleTransaction(this);
130 }
IApplicationThread其实是一个aidl接口在ActivityThread中定义,
继续查看IApplicationThread里面的scheduleTransaction方法,
private class ApplicationThread extends IApplicationThread.Stub {
..........................
@Override
1539 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1540 ActivityThread.this.scheduleTransaction(transaction);
1541 }
}
..........................
接着调用ActivityThread里面的scheduleTransaction方法,如果你在ActivityThread类里面搜的话
是找不到的这个方法的.那就去查看是ActivityThread继承了谁ClientTransactionHandler,进而查找
这个里面的方法
/** Prepare and schedule transaction for execution. */
43 void scheduleTransaction(ClientTransaction transaction) {
44 transaction.preExecute(this);
//调用ActivityThread类里面的方法sendMessage方法
45 sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
46 }
47
查看ActivityThread里面的sendMessage方法,不管怎样都会调用到mH的sendMessage方法
void sendMessage(int what, Object obj) {
2757 sendMessage(what, obj, 0, 0, false);
2758 }
2759
2760 private void sendMessage(int what, Object obj, int arg1) {
2761 sendMessage(what, obj, arg1, 0, false);
2762 }
2763
2764 private void sendMessage(int what, Object obj, int arg1, int arg2) {
2765 sendMessage(what, obj, arg1, arg2, false);
2766 }
2767
2768 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
2769 if (DEBUG_MESSAGES) Slog.v(
2770 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2771 + ": " + arg1 + " / " + obj);
2772 Message msg = Message.obtain();
2773 msg.what = what;
2774 msg.obj = obj;
2775 msg.arg1 = arg1;
2776 msg.arg2 = arg2;
2777 if (async) {
2778 msg.setAsynchronous(true);
2779 }
2780 mH.sendMessage(msg);
2781 }
2782
2783 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
2784 if (DEBUG_MESSAGES) Slog.v(
2785 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
2786 "seq= " + seq);
2787 Message msg = Message.obtain();
2788 msg.what = what;
2789 SomeArgs args = SomeArgs.obtain();
2790 args.arg1 = obj;
2791 args.argi1 = arg1;
2792 args.argi2 = arg2;
2793 args.argi3 = seq;
2794 msg.obj = args;
2795 mH.sendMessage(msg);
2796 }
接着查看mH这个是什么,ActivityThread的成员变量
final H mH = new H();
class H extends Handler {
public void handleMessage(Message msg) {
.................
case EXECUTE_TRANSACTION:
1807 final ClientTransaction transaction = (ClientTransaction) msg.obj;
1808 mTransactionExecutor.execute(transaction);
1809 if (isSystem()) {
1810 // Client transactions inside system process are recycled on the client side
1811 // instead of ClientLifecycleManager to avoid being cleared before this
1812 // message is handled.
1813 transaction.recycle();
1814 }
1815 // TODO(lifecycler): Recycle locally scheduled transactions.
.................
}
}
接着查看mTransactionExecutor,这个成员变量是在ActivityThread里面被赋值的.TransactionExecutor.java
public void execute(ClientTransaction transaction) {
65 final IBinder token = transaction.getActivityToken();
66 log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
67
68 executeCallbacks(transaction);
69
70 executeLifecycleState(transaction);
71 mPendingActions.clear();
72 log("End resolving transaction");
73 }
对于executeCallbacks和executeLifecycleState来说都是调用到了cycleToPath方法,查看这个方法
private void cycleToPath(ActivityClientRecord r, int finish,
161 boolean excludeLastState) {
162 final int start = r.getLifecycleState();
163 log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
164 final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
165 performLifecycleSequence(r, path);
166 }
167
继续调用到ActivityThread类里面的方法, mTransactionHandler是ActivityThread的父类
/** Transition the client through previously initialized state sequence. */
169 private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
170 final int size = path.size();
171 for (int i = 0, state; i < size; i++) {
172 state = path.get(i);
173 log("Transitioning to state: " + state);
174 switch (state) {
175 case ON_CREATE:
176 mTransactionHandler.handleLaunchActivity(r, mPendingActions,
177 null /* customIntent */);
178 break;
179 case ON_START:
180 mTransactionHandler.handleStartActivity(r, mPendingActions);
181 break;
182 case ON_RESUME:
183 mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
184 r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
185 break;
186 case ON_PAUSE:
187 mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
188 false /* userLeaving */, 0 /* configChanges */, mPendingActions,
189 "LIFECYCLER_PAUSE_ACTIVITY");
190 break;
191 case ON_STOP:
192 mTransactionHandler.handleStopActivity(r.token, false /* show */,
193 0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
194 "LIFECYCLER_STOP_ACTIVITY");
195 break;
196 case ON_DESTROY:
197 mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
198 0 /* configChanges */, false /* getNonConfigInstance */,
199 "performLifecycleSequence. cycling to:" + path.get(size - 1));
200 break;
201 case ON_RESTART:
202 mTransactionHandler.performRestartActivity(r.token, false /* start */);
203 break;
204 default:
205 throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
206 }
207 }
208 }
在ActivityThread里面调用handleLaunchActivity, 接着调用performLaunchActivity这个方法
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
.......
mInstrumentation.callActivityOnCreate(activity, r.state);
.......
}
查看Instrumentation.java里面的callActivityOnCreate方法
终于调用到了performCreate的方法,调用Activity里面的oncreate方法
public void callActivityOnCreate(Activity activity, Bundle icicle) {
1270 prePerformCreate(activity);
1271 activity.performCreate(icicle);
1272 postPerformCreate(activity);
1273 }
1274
接着调用handleStartActivity方法,handleResumeActivity等方法,添加view的操作在onresume里面操作
bootchart 可为整个系统提供所有进程的 CPU 和 I/O 负载细分。该工具不需要重建系统映像, 可以用作进入 systrace 之前的快速健全性检查。(systrace)以后在聊
首先在电脑上安装bootchart工具
sudo apt-get install bootchart
adb shell 'touch /data/bootchart/enabled'
adb reboot
第二种方式:
进入/data/bootchart/ 目录里面, 执行 tar -czf bootchart.tar * 命令,把下面的资源打包,
然后pull出来, 接着用bootchat bootchart.tar 会自动生成一张bootchat.png图片
整个图表以时间线为横轴,图标上方为 CPU 和 磁盘的利用情况,下方是各进程的运行状态条,
显示各个进程的开始时间与结束时间以及对 CPU、I/O 的利用情况,我们关心的各个进程的运行时间以及
CPU 的使用情况,进而优化系统。
这里统计的是开启init进程到启动完成的时间, 并没有kernel的启动时间.
同样有的设备可以通过boot_completed这个时间段来确定,adb shell输入一下命令,
dmesg | grep -i boot_completed
[ 21.997797] init: processing action (sys.boot_completed=1) from (/init.rc:705)
从上面的意思来看应该是从init进程到boot_completed的时间为22s左右.如果要统计开机时间,还要加上kernel的时间
前面已经提到过在SystemServer中启动了AMS,并且AMS是android系统中很重要的服务.记录着Activity的
开启,关闭,以及一些记录,同时我们所能看到的launcher也是通过AMS启动的。
源码:
<http://androidxref.com/9.0.0_r3/xref/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java>
AMS是在SystemServer中创建的,只copy出来了主要代码
private void startBootstrapServices() {
// Activity manager runs the show.
558 traceBeginAndSlog("StartActivityManager");
//实例化对象
559 mActivityManagerService = mSystemServiceManager.startService(
560 ActivityManagerService.Lifecycle.class).getService();
//把自己添加为binder service,从而别的进程调用
mActivityManagerService.setSystemProcess();
}
先看下Lifecycle这个类是干嘛的,继承了SystemService,然后在构造函数中把AMS的对象实例化出来
public static final class Lifecycle extends SystemService {
2878 private final ActivityManagerService mService;
2879
2880 public Lifecycle(Context context) {
2881 super(context);
2882 mService = new ActivityManagerService(context);
2883 }
2884
2885 @Override
2886 public void onStart() {
2887 mService.start();
2888 }
2889
2890 @Override
2891 public void onBootPhase(int phase) {
2892 mService.mBootPhase = phase;
2893 if (phase == PHASE_SYSTEM_SERVICES_READY) {
2894 mService.mBatteryStatsService.systemServicesReady();
2895 mService.mServices.systemServicesReady();
2896 }
2897 }
2898
2899 @Override
2900 public void onCleanupUser(int userId) {
2901 mService.mBatteryStatsService.onCleanupUser(userId);
2902 }
2903
2904 public ActivityManagerService getService() {
2905 return mService;
2906 }
2907 }
接着看SystemServiceManager的startService方法,在这个方法里面通过反射实例化了lifecycle这个类
*/
83 @SuppressWarnings("unchecked")
84 public <T extends SystemService> T startService(Class<T> serviceClass) {
85 try {
86 final String name = serviceClass.getName();
87 Slog.i(TAG, "Starting " + name);
88 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
89
90 // Create the service.
91 if (!SystemService.class.isAssignableFrom(serviceClass)) {
92 throw new RuntimeException("Failed to create " + name
93 + ": service must extend " + SystemService.class.getName());
94 }
95 final T service;
96 try {
//通过构造函数实例化lifecycle对象
97 Constructor<T> constructor = serviceClass.getConstructor(Context.class);
98 service = constructor.newInstance(mContext);
99 } catch (InstantiationException ex) {
100 throw new RuntimeException("Failed to create service " + name
101 + ": service could not be instantiated", ex);
102 } catch (IllegalAccessException ex) {
103 throw new RuntimeException("Failed to create service " + name
104 + ": service must have a public constructor with a Context argument", ex);
105 } catch (NoSuchMethodException ex) {
106 throw new RuntimeException("Failed to create service " + name
107 + ": service must have a public constructor with a Context argument", ex);
108 } catch (InvocationTargetException ex) {
109 throw new RuntimeException("Failed to create service " + name
110 + ": service constructor threw an exception", ex);
111 }
112
113 startService(service);
114 return service;
115 } finally {
116 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
117 }
118 }
//调用lifecycle的onstart方法,也就是调用AMS的onStart方法
public void startService(@NonNull final SystemService service) {
121 // Register it.
122 mServices.add(service);
123 // Start it.
124 long time = SystemClock.elapsedRealtime();
125 try {
126 service.onStart();
127 } catch (RuntimeException ex) {
128 throw new RuntimeException("Failed to start service " + service.getClass().getName()
129 + ": onStart threw an exception", ex);
130 }
131 warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
132 }
到这里AMS的对象通过lifecycle实例化了。并且onStart方法开始运行了,我们来看看AMS里面是怎么实例化的
// handlers to other threads. So take care to be explicit about the looper.
3047 public ActivityManagerService(Context systemContext) {
3048 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
3049 mInjector = new Injector();
3050 mContext = systemContext;
3051
3052 mFactoryTest = FactoryTest.getMode();
3053 mSystemThread = ActivityThread.currentActivityThread();
3054 mUiContext = mSystemThread.getSystemUiContext();
3055
3056 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
3057
3058 mPermissionReviewRequired = mContext.getResources().getBoolean(
3059 com.android.internal.R.bool.config_permissionReviewRequired);
3060 /创建名为"ActivityManager"的前台线程,并获取mHandler
3061 mHandlerThread = new ServiceThread(TAG,
3062 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
3063 mHandlerThread.start();
3064 mHandler = new MainHandler(mHandlerThread.getLooper());
3065 mUiHandler = mInjector.getUiHandler(this);
3066
3067 mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
3068 THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
3069 mProcStartHandlerThread.start();
3070 mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
3071
3072 mConstants = new ActivityManagerConstants(this, mHandler);
3073
3074 /* static; one-time init here */
3075 if (sKillHandler == null) {
3076 sKillThread = new ServiceThread(TAG + ":kill",
3077 THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
3078 sKillThread.start();
3079 sKillHandler = new KillHandler(sKillThread.getLooper());
3080 }
3081
//前台广播接收器,超时时间为10S
3082 mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
3083 "foreground", BROADCAST_FG_TIMEOUT, false);
//后台广播接收器,超时时间为60S
3084 mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
3085 "background", BROADCAST_BG_TIMEOUT, true);
3086 mBroadcastQueues[0] = mFgBroadcastQueue;
3087 mBroadcastQueues[1] = mBgBroadcastQueue;
3088
3089 mServices = new ActiveServices(this);
3090 mProviderMap = new ProviderMap(this);
3091 mAppErrors = new AppErrors(mUiContext, this);
3092
//创建目录/data/system
3093 File dataDir = Environment.getDataDirectory();
3094 File systemDir = new File(dataDir, "system");
3095 systemDir.mkdirs();
3096
3097 mAppWarnings = new AppWarnings(this, mUiContext, mHandler, mUiHandler, systemDir);
3098 //创建服务BatteryStatsService
3099 // TODO: Move creation of battery stats service outside of activity manager service.
3100 mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
3101 mBatteryStatsService.getActiveStatistics().readLocked();
3102 mBatteryStatsService.scheduleWriteToDisk();
3103 mOnBattery = DEBUG_POWER ? true
3104 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
3105 mBatteryStatsService.getActiveStatistics().setCallback(this);
3106
//创建进程统计服务,信息保存在目录/data/system/procstats,
3107 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
3108
3109 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
3110
3111 mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"), "uri-grants");
3112
3113 mUserController = new UserController(this);
3114
3115 mVrController = new VrController(this);
3116
3117 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
3118 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
3119
3120 if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
3121 mUseFifoUiScheduling = true;
3122 }
3123
3124 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
3125 mTempConfig.setToDefaults();
3126 mTempConfig.setLocales(LocaleList.getDefault());
3127 mConfigurationSeq = mTempConfig.seq = 1;
3128 mStackSupervisor = createStackSupervisor();
3129 mStackSupervisor.onConfigurationChanged(mTempConfig);
3130 mKeyguardController = mStackSupervisor.getKeyguardController();
3131 mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
3132 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
3133 mTaskChangeNotificationController =
3134 new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
3135 mActivityStartController = new ActivityStartController(this);
3136 mRecentTasks = createRecentTasks();
3137 mStackSupervisor.setRecentTasks(mRecentTasks);
3138 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mHandler);
3139 mLifecycleManager = new ClientLifecycleManager();
3140
//创建名为"CpuTracker"的线程
3141 mProcessCpuThread = new Thread("CpuTracker") {
3142 @Override
3143 public void run() {
3144 synchronized (mProcessCpuTracker) {
3145 mProcessCpuInitLatch.countDown();
3146 mProcessCpuTracker.init();
3147 }
3148 while (true) {
3149 try {
3150 try {
3151 synchronized(this) {
3152 final long now = SystemClock.uptimeMillis();
3153 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
3154 lon g nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
3155 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
3156 // + ", write delay=" + nextWriteDelay);
3157 if (nextWriteDelay < nextCpuDelay) {
3158 nextCpuDelay = nextWriteDelay;
3159 }
3160 if (nextCpuDelay > 0) {
3161 mProcessCpuMutexFree.set(true);
3162 this.wait(nextCpuDelay);
3163 }
3164 }
3165 } catch (InterruptedException e) {
3166 }
//更新CPU的状态
3167 updateCpuStatsNow();
3168 } catch (Exception e) {
3169 Slog.e(TAG, "Unexpected exception collecting process stats", e);
3170 }
3171 }
3172 }
3173 };
3174
3175 mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
3176
3177 Watchdog.getInstance().addMonitor(this);
3178 Watchdog.getInstance().addThread(mHandler);
3179
3180 // bind background thread to little cores
3181 // this is expected to fail inside of framework tests because apps can't touch cpusets directly
3182 // make sure we've already adjusted system_server's internal view of itself first
3183 updateOomAdjLocked();
3184 try {
3185 Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
3186 Process.THREAD_GROUP_BG_NONINTERACTIVE);
3187 } catch (Exception e) {
3188 Slog.w(TAG, "Setting background thread cpuset failed");
3189 }
3190
3191 }
private void start() {
//移除所有的进程组
3216 removeAllProcessGroups();
//CpuTracker线程开启
3217 mProcessCpuThread.start();
3218 //启动电池统计服务
3219 mBatteryStatsService.publish();
3220 mAppOpsService.publish(mContext);
3221 Slog.d("AppOps", "AppOpsService published");
//添加到本地的service,这个地方只能在同一个进程里面可以调用,这个地方很重要,因为下面还有一个binder service
3222 LocalServices.addService(ActivityManagerInternal.class, new LocalService());
3223 // Wait for the synchronized block started in mProcessCpuThread,
3224 // so that any other acccess to mProcessCpuTracker from main thread
3225 // will be blocked during mProcessCpuTracker initialization.
3226 try {
3227 mProcessCpuInitLatch.await();
3228 } catch (InterruptedException e) {
3229 Slog.wtf(TAG, "Interrupted wait during start", e);
3230 Thread.currentThread().interrupt();
3231 throw new IllegalStateException("Interrupted wait during start");
3232 }
3233 }
在systemserver类的startBootstrapServices方法会调用setSystemProcess方法,这里有一个地方很重要
我也是找了半天才看出来, 添加binder service,为跨进程通信使用,我当时纳闷了好久,因为在ActivityManager中
会用到这个binder service,我找了很长时间才找到
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL |
这个方法里面主要就是注册各种服务
public void setSystemProcess() {
2721 try {
2722 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
2723 DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
2724 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2725 ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
2726 DUMP_FLAG_PRIORITY_HIGH);
2727 ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2728 ServiceManager.addService("dbinfo", new DbBinder(this));
2729 if (MONITOR_CPU_USAGE) {
2730 ServiceManager.addService("cpuinfo", new CpuBinder(this),
2731 /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
2732 }
2733 ServiceManager.addService("permission", new PermissionController(this));
2734 ServiceManager.addService("processinfo", new ProcessInfoService(this));
2735
2736 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2737 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
2738 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2739
2740 synchronized (this) {
2741 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
2742 app.persistent = true;
2743 app.pid = MY_PID;
2744 app.maxAdj = ProcessList.SYSTEM_ADJ;
2745 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2746 synchronized (mPidsSelfLocked) {
2747 mPidsSelfLocked.put(app.pid, app);
2748 }
2749 updateLruProcessLocked(app, false, null);
2750 updateOomAdjLocked();
2751 }
2752 } catch (PackageManager.NameNotFoundException e) {
2753 throw new RuntimeException(
2754 "Unable to find android system package", e);
2755 }
2756
2757 // Start watching app ops after we and the package manager are up and running.
2758 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2759 new IAppOpsCallback.Stub() {
2760 @Override public void opChanged(int op, int uid, String packageName) {
2761 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2762 if (mAppOpsService.checkOperation(op, uid, packageName)
2763 != AppOpsManager.MODE_ALLOWED) {
2764 runInBackgroundDisabled(uid);
2765 }
2766 }
2767 }
2768 });
2769 }
//在systemserer里面调用AMS的systemready方法
private void startOtherServices() {
mActivityManagerService.systemReady(new goingCallback()) {
startSystemUi();
}
}
这里大概的流程
public void systemReady(final Runnable goingCallback) {
...//更新操作
mSystemReady = true; //系统处于ready状态
removeProcessLocked(proc, true, false, "system update done");//杀掉所有非persistent进程
mProcessesReady = true; //进程处于ready状态
goingCallback.run(); //这里有可能启动进程。这里会启动systemui
addAppLocked(info, false, null); //启动所有的persistent进程
mBooting = true; //正在启动中
startHomeActivityLocked(mCurrentUserId, "systemReady"); //启动launcher
mStackSupervisor.resumeTopActivitiesLocked(); //恢复栈顶的Activity
}
大致的流程:
忽略我的没有注册的staruml软件 ==!
源码
</frameworks/base/services/java/com/android/server/SystemServer.java>
上面的文章中我们知道了怎么通过zygote来启动SystemServer进程,接下来我们来具体分析SystemServer里面的细节
在zygote里面会通过反射来调用到main方法
public static void main(String[] args) {
294 new SystemServer().run();
295 }
private void run() {
308 try {
309 traceBeginAndSlog("InitBeforeStartServices");
310 // If a device's clock is before 1970 (before 0), a lot of
311 // APIs crash dealing with negative numbers, notably
312 // java.io.File#setLastModified, so instead we fake it and
313 // hope that time from cell towers or NTP fixes it shortly.
如果时间比1970年早, 设置为1970年
314 if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
315 Slog.w(TAG, "System clock is before 1970; setting to 1970.");
316 SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
317 }
318
319 //
320 // Default the timezone property to GMT if not set.
321 //
322 String timezoneProperty = SystemProperties.get("persist.sys.timezone");
323 if (timezoneProperty == null || timezoneProperty.isEmpty()) {
324 Slog.w(TAG, "Timezone not set; setting to GMT.");
325 SystemProperties.set("persist.sys.timezone", "GMT");
326 }
327
328 // If the system has "persist.sys.language" and friends set, replace them with
329 // "persist.sys.locale". Note that the default locale at this point is calculated
330 // using the "-Duser.locale" command line flag. That flag is usually populated by
331 // AndroidRuntime using the same set of system properties, but only the system_server
332 // and system apps are allowed to set them.
333 //
334 // NOTE: Most changes made here will need an equivalent change to
335 // core/jni/AndroidRuntime.cpp
336 if (!SystemProperties.get("persist.sys.language").isEmpty()) {
337 final String languageTag = Locale.getDefault().toLanguageTag();
338
339 SystemProperties.set("persist.sys.locale", languageTag);
340 SystemProperties.set("persist.sys.language", "");
341 SystemProperties.set("persist.sys.country", "");
342 SystemProperties.set("persist.sys.localevar", "");
343 }
344
345 // The system server should never make non-oneway calls
346 Binder.setWarnOnBlocking(true);
347 // The system server should always load safe labels
348 PackageItemInfo.setForceSafeLabels(true);
349 // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
350 SQLiteCompatibilityWalFlags.init(null);
351
352 // Here we go!
353 Slog.i(TAG, "Entered the Android system server!");
354 int uptimeMillis = (int) SystemClock.elapsedRealtime();
355 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
356 if (!mRuntimeRestart) {
357 MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
358 }
359
360 // In case the runtime switched since last boot (such as when
361 // the old runtime was removed in an OTA), set the system
362 // property so that it is in sync. We can | xq oqi't do this in
363 // libnativehelper's JniInvocation::Init code where we already
364 // had to fallback to a different runtime because it is
365 // running as root and we need to be the system user to set
366 // the property. http://b/11463182
367 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
368
369 // Mmmmmm... more memory!
370 VMRuntime.getRuntime().clearGrowthLimit();
371
372 // The system server has to run all of the time, so it needs to be
373 // as efficient as possible with its memory usage.
374 VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
375
376 // Some devices rely on runtime fingerprint generation, so make sure
377 // we've defined it before booting further.
378 Build.ensureFingerprintProperty();
379
380 // Within the system server, it is an error to access Environment paths without
381 // explicitly specifying a user.
382 Environment.setUserRequired(true);
383
384 // Within the system server, any incoming Bundles should be defused
385 // to avoid throwing BadParcelableException.
386 BaseBundle.setShouldDefuse(true);
387
388 // Within the system server, when parceling exceptions, include the stack trace
389 Parcel.setStackTraceParceling(true);
390
391 // Ensure binder calls into the system always run at foreground priority.
392 BinderInternal.disableBackgroundScheduling(true);
393
394 // Increase the number of binder threads in system_server
395 BinderInternal.setMaxThreads(sMaxBinderThreads);
396
397 // Prepare the main looper thread (this thread).
398 android.os.Process.setThreadPriority(
399 android.os.Process.THREAD_PRIORITY_FOREGROUND);
400 android.os.Process.setCanSelfBackground(false);
401 Looper.prepareMainLooper();
402 Looper.getMainLooper().setSlowLogThresholdMs(
403 SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
404
405 // Initialize native services.
406 System.loadLibrary("android_servers");
407
408 // Check whether we failed to shut down last time we tried.
409 // This call may not return.
410 performPendingShutdown();
411
412 // Initialize the system context.
//创建系统的上下文
413 createSystemContext();
414
415 // Create the system service manager.
//系统服务管理者
416 mSystemServiceManager = new SystemServiceManager(mSystemContext);
417 mSystemServiceManager.setStartInfo(mRuntimeRestart,
418 mRuntimeStartElapsedTime, mRuntimeStartUptime);
419 LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
420 // Prepare the thread pool for init tasks that can be parallelized
421 SystemServerInitThreadPool.get();
422 } finally {
423 traceEnd(); // InitBeforeStartServices
424 }
425
426 // Start services.
427 try {
428 traceBeginAndSlog("StartServices");
429 startBootstrapServices(); // 启动引导服务
430 startCoreServices(); //核心服务
431 startOtherServices(); //一些其它的服务
432 SystemServerInitThreadPool.shutdown();
433 } catch (Throwable ex) {
434 Slog.e("System", "******************************************");
435 Slog.e("System", "************ Failure starting system services", ex);
436 throw ex;
437 } finally {
438 traceEnd();
439 }
440
441 StrictMode.initVmDefaults(null);
442
443 if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
444 int uptimeMillis = (int) SystemClock.elapsedRealtime();
445 MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
446 final int MAX_UPTIME_MILLIS = 60 * 1000;
447 if (uptimeMillis > MAX_UPTIME_MILLIS) {
448 Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
449 "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
450 }
451 }
452 //保证SystemServer进程一直存活
453 // Loop forever.
454 Looper.loop();
455 throw new RuntimeException("Main thread loop unexpectedly exited");
456 }
private void createSystemContext() {
//创建ActivityThread, 在systemMain函数里面调用ActivityThread的构造函数
//ActivityThread thread = new ActivityThread();
522 ActivityThread activityThread = ActivityThread.systemMain();
523 mSystemContext = activityThread.getSystemContext();
524 mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
525
526 final Context systemUiContext = activityThread.getSystemUiContext();
527 systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
528 }
529
当然在SystemServer里面启动了好多的java层的service,他们内部通过binder 来进行通信,这个地方就暂时不说了
以后会专门开一篇来说SystemServer里面启动的服务,以及怎么通过binder来进行通信的。到这个地方我们的SystemServer
算是启动完成了,那下面是怎么启动到launcher呢,继续看下一篇文章。