ui绘制流程2

2020-04-05  本文已影响0人  ArcherZang

----->main(String[] args)

//ActivityThread.java

ActivityThread thread = new ActivityThread();
//ActivityThread实例化时其属性mAppThread也实例化
//final ApplicationThread mAppThread = new ApplicationThread();
thread.attach(false, startSeq);

------->attach(boolean system, long startSeq)

//ActivityThread.java

final IActivityManager mgr = ActivityManager.getService();
try {
    mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
    throw ex.rethrowFromSystemServer();
}
  1. ------->ActivityManager.getService()
    //ActivityManager.java

    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
    
    private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;
                }
            };
    
    • ------->ServiceManager.getService(Context.ACTIVITY_SERVICE)

    • ------->BinderInternal.getContextObject()最终调用native层方法获取的是ActivityManagerService的binder

      * Returns a reference to a service with the given name.
      * @param name the name of the service to get
       @return a reference to the service, or <code>null</code> if the service doesn't exist
       */
       @UnsupportedAppUsage
      public static IBinder getService(String name) {
          try {
              IBinder service = sCache.get(name);
              if (service != null) {
                  return service;
              } else {
                  return Binder.allowBlocking(rawGetService(name));
              }
          } catch (RemoteException e) {
              Log.e(TAG, "error in getService", e);
          }
              return null;
          }
      
        private static IBinder rawGetService(String name) throws RemoteException {
              final long start = sStatLogger.getTime();
      
              final IBinder binder = getIServiceManager().getService(name);
      
              final int time = (int) sStatLogger.logDurationStat(Stats.GET_SERVICE, start);
      
              final int myUid = Process.myUid();
              final boolean isCore = UserHandle.isCore(myUid);
      
              final long slowThreshold = isCore
                      ? GET_SERVICE_SLOW_THRESHOLD_US_CORE
                      : GET_SERVICE_SLOW_THRESHOLD_US_NON_CORE;
      
              synchronized (sLock) {
                  sGetServiceAccumulatedUs += time;
                  sGetServiceAccumulatedCallCount++;
      
                  final long nowUptime = SystemClock.uptimeMillis();
      
                  // Was a slow call?
                  if (time >= slowThreshold) {
                      // We do a slow log:
                      // - At most once in every SLOW_LOG_INTERVAL_MS
                      // - OR it was slower than the previously logged slow call.
                      if ((nowUptime > (sLastSlowLogUptime + SLOW_LOG_INTERVAL_MS))
                              || (sLastSlowLogActualTime < time)) {
                          EventLogTags.writeServiceManagerSlow(time / 1000, name);
      
                          sLastSlowLogUptime = nowUptime;
                          sLastSlowLogActualTime = time;
                      }
                  }
      
                  // Every GET_SERVICE_LOG_EVERY_CALLS calls, log the total time spent in getService().
      
                  final int logInterval = isCore
                          ? GET_SERVICE_LOG_EVERY_CALLS_CORE
                          : GET_SERVICE_LOG_EVERY_CALLS_NON_CORE;
      
                  if ((sGetServiceAccumulatedCallCount >= logInterval)
                          && (nowUptime >= (sLastStatsLogUptime + STATS_LOG_INTERVAL_MS))) {
      
                      EventLogTags.writeServiceManagerStats(
                              sGetServiceAccumulatedCallCount, // Total # of getService() calls.
                              sGetServiceAccumulatedUs / 1000, // Total time spent in getService() calls.
                              (int) (nowUptime - sLastStatsLogUptime)); // Uptime duration since last log.
                      sGetServiceAccumulatedCallCount = 0;
                      sGetServiceAccumulatedUs = 0;
                      sLastStatsLogUptime = nowUptime;
                  }
              }
              return binder;
          }
      
          @UnsupportedAppUsage
          private static IServiceManager getIServiceManager() {
              if (sServiceManager != null) {
                  return sServiceManager;
              }
      
              // Find the service manager
              sServiceManager = ServiceManagerNative
                      .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
              return sServiceManager;
          }
      
    • 简单叙述AMS注册过程

      SystemServer的static void main(String[] args)

      ---->run()

----> mSystemServiceManager = new SystemServiceManager(mSystemContext);

---->startBootstrapServices()
----->1. mActivityManagerService = mSystemServiceManager.startService(
   ActivityManagerService.Lifecycle.class).getService();
---->SystemServiceManager的startService(Class<T> serviceClass)
---->最终反射实例调用,因为ActivityManagerService.Lifecycle extends SystemService service.onStart()
---->ActivityManagerService.Lifecycle.onStart() 

---->因为构造Lifecycle时内部mService = new ActivityManagerService(context, sAtm);

----->ActivityManagerService.Lifecycle.getService()返回内部mService

----->2.mActivityManagerService.setSystemProcess();在startBootstrapServices()里面调用

----->注册自己ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                      DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
  1. ---->mgr.attachApplication(mAppThread, startSeq)

    // ActivityManagerService.java

    public class ActivityManagerService extends IActivityManager.Stub
            implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
        @Override
        public final void attachApplication(IApplicationThread thread, long startSeq) {
            synchronized (this) {
                int callingPid = Binder.getCallingPid();
                final int callingUid = Binder.getCallingUid();
                final long origId = Binder.clearCallingIdentity();
                attachApplicationLocked(thread, callingPid, callingUid, startSeq);
                Binder.restoreCallingIdentity(origId);
        }
    

}


-----> attachApplicationLocked(thread, callingPid, callingUid, startSeq)

// ActivityManagerService.java

//TO Do有空深究ProcessRecord创建

```java
    private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
        ...
        ProcessRecord app;
        long startTime = SystemClock.uptimeMillis();
        if (pid != MY_PID && pid >= 0) {
            synchronized (mPidsSelfLocked) {
                app = mPidsSelfLocked.get(pid);
            }
        } else {
            app = null;
        }
        // It's possible that process called attachApplication before we got a chance to
        // update the internal state.
        if (app == null && startSeq > 0) {
            final ProcessRecord pending = mPendingStarts.get(startSeq);
            if (pending != null && pending.startUid == callingUid
                    && handleProcessStartedLocked(pending, pid, pending.usingWrapper,
                            startSeq, true)) {
                app = pending;
            }
        }
        ...
        try {
            
            if (app.isolatedEntryPoint != null) {
                // This is an isolated process which should just call an entry point instead of
                // being bound to an application.
                thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
            } else if (app.instr != null) {
                thread.bindApplication(processName, appInfo, providers,
                        app.instr.mClass,
                        profilerInfo, app.instr.mArguments,
                        app.instr.mWatcher,
                        app.instr.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);
            } else {
                thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                        null, null, null, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);
            }
            ...
        } catch (Exception e) {
            // todo: Yikes!  What should we do?  For now we will try to
            // start another process, but that could easily get us in
            // an infinite loop of restarting processes...
            Slog.wtf(TAG, "Exception thrown during bind of " + app, e);

            app.resetPackageList(mProcessStats);
            app.unlinkDeathRecipient();
            startProcessLocked(app, "bind fail", processName);
            return false;
        }

        // Remove this record from the list of starting applications.
        mPersistentStartingProcesses.remove(app);
     if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
                "Attach application locked removing on hold: " + app);
        mProcessesOnHold.remove(app);

        boolean badApp = false;
        boolean didSomething = false;

        // 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;
            }
        }
        ...

        return true;
 }
// ActivityThread.Java
if (r.isPersistable()) {
    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
    mInstrumentation.callActivityOnCreate(activity, r.state);
}
// Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    activity.performCreate(icicle);
    postPerformCreate(activity);
}

/**
 * Perform calling of an activity's {@link Activity#onCreate}
 * method.  The default implementation simply calls through to that method.
 *  @param activity The activity being created.
 * @param icicle The previously frozen state (or null) to pass through to
 * @param persistentState The previously persisted state (or null)
 */
public void callActivityOnCreate(Activity activity, Bundle icicle,
        PersistableBundle persistentState) {
    prePerformCreate(activity);
    activity.performCreate(icicle, persistentState);
    postPerformCreate(activity);
}

private void postPerformCreate(Activity activity) {
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    am.match(activity, activity, activity.getIntent());
                }
            }
    }
}
public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback, WindowControllerCallback,
        AutofillManager.AutofillClient {
    final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }

    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        mCanEnterPictureInPicture = true;
        restoreHasCurrentPermissionRequest(icicle);
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
        mActivityTransitionState.readState(icicle);

        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
            com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated();
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    }
    
    final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读