在上一篇文章有说ActivityThread启动的过程,最后讲解到ActivityThread的main函数启动。这篇文章接上篇文章讲解main方法中怎么启动Activity的,方便日后讲解有关Activity中的事件处理机制。
一、ActivityThread中main方法
public static void main(String[] args) { SamplingProfilerIntegration.start(); // CloseGuard defaults to true and can be quite spammy. We // disable it here, but selectively enable it later (via // StrictMode) on debug builds, but using DropBox, not logs. CloseGuard.setEnabled(false); Environment.initForCurrentUser(); // Set the reporter for event logging in libcore EventLogger.setReporter(new EventLoggingReporter()); Process.setArgV0("<pre-initialized>"); //准备主线程中的Loop启动 Looper.prepareMainLooper(); //创建ActivityThread实例 ActivityThread thread = new ActivityThread(); //ActivityThread内容绑定 thread.attach(false); if (sMainThreadHandler == null) { //获取主线程中的Handler sMainThreadHandler = thread.getHandler(); } AsyncTask.init(); if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } //启动主线中的Handler消息机制的loop Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
这里完成了ActivityThread的实例的创建,然后进行绑定操作。在这里还完成了主线程也就是UI中的looper的启动,以便日后使用Handler消息机制。接下来要看一下ActivityThread的绑定Application的过程,接下来看一下ActivityThread中的attach方法。
//在这里是启动的ActivityThread不是系统,在main方法中已经看到传递过来的是false private void attach(boolean system) { sThreadLocal.set(this); mSystemThread = system; if (!system) { ViewRootImpl.addFirstDrawHandler(new Runnable() { public void run() { ensureJitEnabled(); } }); android.ddm.DdmHandleAppName.setAppName("<pre-initialized>", UserHandle.myUserId()); RuntimeInit.setApplicationObject(mAppThread.asBinder()); //获取远程AMS的代理对象 IActivityManager mgr = ActivityManagerNative.getDefault(); //调用AMS中attachApplication方法,mAppThread在类加载的时候已经进行了初始化 //在以后Activity的start、stop、resume以及显示都是mAppThread进行的 try { mgr.attachApplication(mAppThread); } catch (RemoteException ex) { // Ignore } } else { // Don't set application object here -- if the system crashes, // we can't display an alert, we just want to die die die. android.ddm.DdmHandleAppName.setAppName("system_process", UserHandle.myUserId()); try { mInstrumentation = new Instrumentation(); ContextImpl context = new ContextImpl(); context.init(getSystemContext().mPackageInfo, null, this); Application app = Instrumentation.newApplication(Application.class, context); mAllApplications.add(app); mInitialApplication = app; app.onCreate(); } catch (Exception e) { throw new RuntimeException( "Unable to instantiate Application():" + e.toString(), e); } } // add dropbox logging to libcore DropBox.setReporter(new DropBoxReporter()); ViewRootImpl.addConfigCallback(new ComponentCallbacks2() { public void onConfigurationChanged(Configuration newConfig) { synchronized (mPackages) { // We need to apply this change to the resources // immediately, because upon returning the view // hierarchy will be informed about it. if (applyConfigurationToResourcesLocked(newConfig, null)) { // This actually changed the resources! Tell // everyone about it. if (mPendingConfiguration == null || mPendingConfiguration.isOtherSeqNewer(newConfig)) { mPendingConfiguration = newConfig; queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig); } } } } public void onLowMemory() { } public void onTrimMemory(int level) { } }); }在这里获取到远程AMS的代理对象,然后调用AMS方法进行Application的绑定工作。在这里有说到mAppThread这个成员变量,是ApplicationThreadNative的实例,在以后的操作Activity的操作都是在ApplicationThreadNative中进行的,这里不在详说。接下来就又回到了AMS中。
二、AMS中attachApplication
1、AMS的attachApplication
@Override public final void attachApplication(IApplicationThread thread) { synchronized (this) { int callingPid = Binder.getCallingPid(); final long origId = Binder.clearCallingIdentity(); attachApplicationLocked(thread, callingPid); Binder.restoreCallingIdentity(origId); } } private final boolean attachApplicationLocked(IApplicationThread thread, int pid) { // Find the application record that is being attached... either via // the pid if we are running in multiple processes, or just pull the // next app record if we are emulating process with anonymous threads. ProcessRecord app; long startTime = SystemClock.uptimeMillis(); if (pid != MY_PID && pid >= 0) { synchronized (mPidsSelfLocked) { //由pid获取进程记录 app = mPidsSelfLocked.get(pid); } } else { app = null; } if (app == null) { //如果不存在则做相应处理 Slog.w(TAG, "No pending application record for pid " + pid + " (IApplicationThread " + thread + "); dropping process"); EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); if (pid > 0 && pid != MY_PID) { killProcessQuiet(pid); //TODO: killProcessGroup(app.info.uid, pid); } else { try { thread.scheduleExit(); } catch (Exception e) { // Ignore exceptions. } } return false; } // If this application record is still attached to a previous // process, clean it up now. //如果当前进程记录已经和其他应用进程绑定了这里进行删除操作 if (app.thread != null) { handleAppDiedLocked(app, true, true); } // Tell the process all about itself. if (DEBUG_ALL) Slog.v( TAG, "Binding process pid " + pid + " to record " + app); final String processName = app.processName; try { AppDeathRecipient adr = new AppDeathRecipient( app, pid, thread); thread.asBinder().linkToDeath(adr, 0); app.deathRecipient = adr; } catch (RemoteException e) { app.resetPackageList(mProcessStats); startProcessLocked(app, "link fail", processName); return false; } EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName); </