// com.android.server.SystemServer.java; publicfinalclassSystemServer{ /** * The main entry point from zygote. */ publicstaticvoidmain(String[] args){ new SystemServer().run(); }
// com.android.server.SystemServiceManager.java /** * Creates and starts a system service. The class must be a subclass of * {@link com.android.server.SystemService}. * * @param serviceClass A Java class that implements the SystemService interface. * @return The service instance, never null. * @throws RuntimeException if the service fails to start. */ @SuppressWarnings("unchecked") publicT startService(Class serviceClass){ ... // 通过反射的方式实例化该 service Constructor constructor = serviceClass.getConstructor(Context.class); service = constructor.newInstance(mContext); ... startService(service); return service; }
privatevoidstart(){ removeAllProcessGroups(); mProcessCpuThread.start(); mBatteryStatsService.publish(); mAppOpsService.publish(mContext); Slog.d("AppOps", "AppOpsService published"); LocalServices.addService(ActivityManagerInternal.class, newLocalService()); mActivityTaskManager.onActivityManagerInternalAdded(); mUgmInternal.onActivityManagerInternalAdded(); mPendingIntentController.onActivityManagerInternalAdded(); // Wait for the synchronized block started in mProcessCpuThread, // so that any other access to mProcessCpuTracker from main thread // will be blocked during mProcessCpuTracker initialization. try { mProcessCpuInitLatch.await(); } catch (InterruptedException e) { Slog.wtf(TAG, "Interrupted wait during start", e); Thread.currentThread().interrupt(); thrownew IllegalStateException("Interrupted wait during start"); } }
// Note: This method is invoked on the main thread but may need to attach various // handlers to other threads. So take care to be explicit about the looper. publicActivityManagerService(Context systemContext, ActivityTaskManagerService atm){ LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY); mInjector = new Injector(); mContext = systemContext;
mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false/*allowIo*/); mHandlerThread.start(); mHandler = new MainHandler(mHandlerThread.getLooper()); mUiHandler = mInjector.getUiHandler(this);
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", THREAD_PRIORITY_FOREGROUND, false/* allowIo */); mProcStartHandlerThread.start(); mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
mConstants = new ActivityManagerConstants(mContext, this, mHandler); final ActiveUids activeUids = new ActiveUids(this, true/* postChangesToAtm */); mPlatformCompat = (PlatformCompat) ServiceManager.getService( Context.PLATFORM_COMPAT_SERVICE); mProcessList.init(this, activeUids, mPlatformCompat); mLowMemDetector = new LowMemDetector(this); mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
// 第二步 // Broadcast policy parameters final BroadcastConstants foreConstants = new BroadcastConstants( Settings.Global.BROADCAST_FG_CONSTANTS); foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
final BroadcastConstants backConstants = new BroadcastConstants( Settings.Global.BROADCAST_BG_CONSTANTS); backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
final BroadcastConstants offloadConstants = new BroadcastConstants( Settings.Global.BROADCAST_OFFLOAD_CONSTANTS); offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; // by default, no "slow" policy in this queue offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
finalclassActivityRecordextendsConfigurationContainer{ final ActivityTaskManagerService mAtmService; // owner final IApplicationToken.Stub appToken; // window manager token final ActivityInfo info; // all about me ApplicationInfo appInfo; // information about activity's app final Intent intent; // the original intent that generated us final ComponentName mActivityComponent; // the intent component, or target of an alias. final String taskAffinity; // as per ActivityInfo.taskAffinity private TaskRecord task; // the task this is in. ActivityRecord resultTo; // who started this entry, so will get our reply finalint requestCode; // code given by requester (resultTo) int launchMode; // the launch mode activity attribute. final ActivityStackSupervisor mStackSupervisor; }
// Native callback. privatevoidonPointerDownOutsideFocus(IBinder touchedToken){ /** * Notifies window manager that a {@link android.view.MotionEvent#ACTION_DOWN} pointer event * occurred on a window that did not have focus. * * @param touchedToken The token for the window that received the input event. */ mWindowManagerCallbacks.onPointerDownOutsideFocus(touchedToken); }
privatevoidhandleDisplayFocusChange(WindowState window){ final DisplayContent displayContent = window.getDisplayContent(); ... // For compatibility, only the topmost activity is allowed to be resumed for pre-Q // app. Ensure the topmost activities are resumed whenever a display is moved to top. // TODO(b/123761773): Investigate whether we can move this into // RootActivityContainer#updateTopResumedActivityIfNeeded(). Currently, it is risky // to do so because it seems possible to resume activities as part of a larger // transaction and it's too early to resume based on current order when performing // updateTopResumedActivityIfNeeded(). displayContent.mAcitvityDisplay.ensureActivitiesVisible(null/* starting */, 0/* configChanges */, !PRESERVE_WINDOWS, true/* notifyClients */); }
/** * Exactly one of these classes per Display in the system. Capable of holding zero or more * attached {@link ActivityStack}s. */ classActivityDisplay{ ... /** * All of the stacks on this display. Order matters, topmost stack is in front of all other * stacks, bottommost behind. Accessed directly by ActivityManager package classes. Any calls * changing the list should also call {@link #onStackOrderChanged()}. */ final ArrayList mStacks = new ArrayList(); ... voidaddChild(ActivityStack stack, int position){ if (position == POSITION_BOTTOM) { position = 0; } elseif (position == POSITION_TOP) { position = mStacks.size(); } addStackReferenceIfNeeded(stack); positionChildAt(stack, position); }
// com.android.server.vm.ActivityStack.java /** * Ensure visibility with an option to also update the configuration of visible activities. * @see #ensureActivitiesVisibleLocked(ActivityRecord, int, boolean) * @see RootActivityContainer#ensureActivitiesVisible(ActivityRecord, int, boolean) */ // TODO: Should be re-worked based on the fact that each task as a stack in most cases. // 由这个 TODO 可以看出,日后 Android 必定会变成一个 task 中只有一个 stack,毕竟大多数情况下是这样的 finalvoidensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges, boolean preserveWindows, boolean notifyClients){ ... for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { ... final TaskRecord task = mTaskHistory.get(taskNdx); final ArrayList activities = task.mActivities; for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = activities.get(activityNdx); ... r.makeClientVisible(); ... } }
来到了ActivityRecord.makeClientVisible():
// com.android.server.wm.ActivityRecord.java
/** Send visibility change message to the client and pause if needed. */ voidmakeClientVisible(){ ... makeActiveIfNeeded(null/* activeActivity*/); ... }
/** * Make activity resumed or paused if needed. * @param activeActivity an activity that is resumed or just completed pause action. * We won't change the state of this activity. */ booleanmakeActiveIfNeeded(ActivityRecord activeActivity){ if (shouldResumeActivity(activeActivity)) { return getActivityStack().resumeTopActivityUncheckedLocked(activeActivity /* prev */, null/* options */); } elseif (shouldPauseActivity(activeActivity)) { ... } returnfalse; }
/** * Ensure that the top activity in the stack is resumed. * * @param prev The previously resumed activity, for when in the process * of pausing; can be null to call from elsewhere. * @param options Activity options. * * @return Returns true if something is being resumed, or false if * nothing happened. * * NOTE: It is not safe to call this method directly as it can cause an activity in a * non-focused stack to be resumed. * Use {@link RootActivityContainer#resumeFocusedStacksTopActivities} to resume the * right activity for the current system state. */ @GuardedBy("mService") booleanresumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options){ ... result = resumeTopActivityInnerLocked(prev, options); ... return result; }