Activity的启动过程
来源:互联网 发布:淘宝实拍保护入口 编辑:程序博客网 时间:2024/06/05 08:47
ActivityThread类main方法是一个Andorid应用程序的入口。
ActivityThread类只是一个普通的类,他并是一个Thread。
下面就从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);
- Process.setArgV0("<pre-initialized>");
- //此方法其实就是创建UI线程相关的Looper实例
- Looper.prepareMainLooper();
- if (sMainThreadHandler == null) {
- sMainThreadHandler = new Handler();
- }
- //创建一个ActivityThread对象
- ActivityThread thread = new ActivityThread();
- //调用ActivityThread的attach(Boolean)方法,与AMS进行通信,
- thread.attach(false);
- if (false) {
- Looper.myLooper().setMessageLogging(new
- LogPrinter(Log.DEBUG, "ActivityThread"));
- }
- //让Looper去轮询消息队列
- Looper.loop();
- throw new RuntimeException("Main thread loop unexpectedly exited");
- }
ThreadActivity就是通过
- thread.attach(false);
这个方法来实现与Ams进行交互,当然attach中还会调用很多其他的类和方法。下面看
- 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>");
- RuntimeInit.setApplicationObject(mAppThread.asBinder());
- /*
- *ActivityManagerNative是ActivityManagerService的代理类,
- <span style="white-space:pre"> </span> *此类是Binder的子类,用来实现Activity与ActivityManagerService之间的交互
- *所以说与AMS的交互是通过Binder机制来实现的
- *
- */
- IActivityManager mgr = ActivityManagerNative.getDefault();
- try {
- <span style="white-space:pre"> </span>
- <span style="white-space:pre"> </span>//向AMSf发送消息。
- 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");
- try {
- <span style="white-space:pre"> </span>/*Instrumentation的作用
- <span style="white-space:pre"> </span> * 1.调用Activity的相关周期方法
- <span style="white-space:pre"> </span> * 2.创建application
- <span style="white-space:pre"> </span> * 3.启动Activity
- <span style="white-space:pre"> </span> */
- mInstrumentation = new Instrumentation();
- //下面的代码就是创建一个Application实例对象,并调用它的onCreate()
- 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);
- }
- }
- 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) {
- }
- });
- }
- final ApplicationThread mAppThread = new ApplicationThread();
Ams在接到请求后就会给ActivityThread反馈。反馈回来的消息将传递给
H类来处理,H类是Handler的子类。当H收到的是一个开启Activity的消息时会执行以下代码
- case LAUNCH_ACTIVITY: {
- ActivityClientRecord r = (ActivityClientRecord)msg.obj;
- r.packageInfo = getPackageInfoNoCheck(
- r.activityInfo.applicationInfo, r.compatInfo);
- handleLaunchActivity(r, null);
- } break;
首先来了解几个类
ActivityClientRecord类
此类是对一个客户端的Activity的描述,只是做一个记录。每一个Activity被创建是都会有一个ActivityClientRecord与之对应,
此类中还包含一个ActivityInfo成员,ActivityInfo主要描述了Activity的权限信息,粘合性。
ActivityRecord类:主要用于AMS中记录Activity,与客户端中的ActivityClientRecord类相对应。
下面看
- private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
- // If we are getting ready to gc after going to the background, well
- // we are back active so skip it.
- unscheduleGcIdler();
- if (r.profileFd != null) {
- mProfiler.setProfiler(r.profileFile, r.profileFd);
- mProfiler.startProfiling();
- mProfiler.autoStopProfiler = r.autoStopProfiler;
- }
- // Make sure we are running with the most recent config.
- handleConfigurationChanged(null, null);
- if (localLOGV) Slog.v(
- TAG, "Handling launch of " + r);
- Activity a = performLaunchActivity(r, customIntent);
- if (a != null) {
- r.createdConfig = new Configuration(mConfiguration);
- Bundle oldState = r.state;
- handleResumeActivity(r.token, false, r.isForward);
- if (!r.activity.mFinished && r.startsNotResumed) {
- // The activity manager actually wants this one to start out
- // paused, because it needs to be visible but isn't in the
- // foreground. We accomplish this by going through the
- // normal startup (because activities expect to go through
- // onResume() the first time they run, before their window
- // is displayed), and then pausing it. However, in this case
- // we do -not- need to do the full pause cycle (of freezing
- // and such) because the activity manager assumes it can just
- // retain the current state it has.
- try {
- r.activity.mCalled = false;
- mInstrumentation.callActivityOnPause(r.activity);
- // We need to keep around the original state, in case
- // we need to be created again.
- r.state = oldState;
- if (!r.activity.mCalled) {
- throw new SuperNotCalledException(
- "Activity " + r.intent.getComponent().toShortString() +
- " did not call through to super.onPause()");
- }
- } catch (SuperNotCalledException e) {
- throw e;
- } catch (Exception e) {
- if (!mInstrumentation.onException(r.activity, e)) {
- throw new RuntimeException(
- "Unable to pause activity "
- + r.intent.getComponent().toShortString()
- + ": " + e.toString(), e);
- }
- }
- r.paused = true;
- }
- } else {
- // If there was an error, for any reason, tell the activity
- // manager to stop us.
- try {
- ActivityManagerNative.getDefault()
- .finishActivity(r.token, Activity.RESULT_CANCELED, null);
- } catch (RemoteException ex) {
- // Ignore
- }
- }
- }
- Activity a = performLaunchActivity(r, customIntent);
- private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
- // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
- ActivityInfo aInfo = r.activityInfo;
- if (r.packageInfo == null) {
- r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
- Context.CONTEXT_INCLUDE_CODE);
- }
- ComponentName component = r.intent.getComponent();
- if (component == null) {
- component = r.intent.resolveActivity(
- mInitialApplication.getPackageManager());
- r.intent.setComponent(component);
- }
- if (r.activityInfo.targetActivity != null) {
- component = new ComponentName(r.activityInfo.packageName,
- r.activityInfo.targetActivity);
- }
- Activity activity = null;
- try {
- /*
- * 此代码其实就是通过反射创建一个Activity的实例对象,但他此时仅仅只是一个普通的对象
- */
- java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
- activity = mInstrumentation.newActivity(
- cl, component.getClassName(), r.intent);
- StrictMode.incrementExpectedActivityCount(activity.getClass());
- r.intent.setExtrasClassLoader(cl);
- if (r.state != null) {
- r.state.setClassLoader(cl);
- }
- } catch (Exception e) {
- if (!mInstrumentation.onException(activity, e)) {
- throw new RuntimeException(
- "Unable to instantiate activity " + component
- + ": " + e.toString(), e);
- }
- }
- try {
- <span style="white-space:pre"> </span>
- <span style="white-space:pre"> </span>//创建Application次数其实也是通过反射方式来创建的。
- Application app = r.packageInfo.makeApplication(false, mInstrumentation);
- if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
- if (localLOGV) Slog.v(
- TAG, r + ": app=" + app
- + ", appName=" + app.getPackageName()
- + ", pkg=" + r.packageInfo.getPackageName()
- + ", comp=" + r.intent.getComponent().toShortString()
- + ", dir=" + r.packageInfo.getAppDir());
- if (activity != null) {
- ContextImpl appContext = new ContextImpl();
- appContext.init(r.packageInfo, r.token, this);
- appContext.setOuterContext(activity);
- CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
- Configuration config = new Configuration(mCompatConfiguration);
- if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
- + r.activityInfo.name + " with config " + config);
- //给Activity相关字段赋值,并与WindowManager进行关联
- activity.attach(appContext, this, getInstrumentation(), r.token,
- r.ident, app, r.intent, r.activityInfo, title, r.parent,
- r.embeddedID, r.lastNonConfigurationInstances, config);
- if (customIntent != null) {
- activity.mIntent = customIntent;
- }
- r.lastNonConfigurationInstances = null;
- activity.mStartedActivity = false;
- int theme = r.activityInfo.getThemeResource();
- if (theme != 0) {
- activity.setTheme(theme);
- }
- activity.mCalled = false;
- //回调Activity的Oncreate方法
- mInstrumentation.callActivityOnCreate(activity, r.state);
- if (!activity.mCalled) {
- throw new SuperNotCalledException(
- "Activity " + r.intent.getComponent().toShortString() +
- " did not call through to super.onCreate()");
- }
- r.activity = activity;
- r.stopped = true;
- if (!r.activity.mFinished) {
- activity.performStart();
- r.stopped = false;
- }
- if (!r.activity.mFinished) {
- if (r.state != null) {
- mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
- }
- }
- if (!r.activity.mFinished) {
- activity.mCalled = false;
- mInstrumentation.callActivityOnPostCreate(activity, r.state);
- if (!activity.mCalled) {
- throw new SuperNotCalledException(
- "Activity " + r.intent.getComponent().toShortString() +
- " did not call through to super.onPostCreate()");
- }
- }
- }
- r.paused = true;
- mActivities.put(r.token, r);
- } catch (SuperNotCalledException e) {
- throw e;
- } catch (Exception e) {
- if (!mInstrumentation.onException(activity, e)) {
- throw new RuntimeException(
- "Unable to start activity " + component
- + ": " + e.toString(), e);
- }
- }
- return activity;
- }
- Activity activity = null;
- try {
- java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
- activity = mInstrumentation.newActivity(
- cl, component.getClassName(), r.intent);
- StrictMode.incrementExpectedActivityCount(activity.getClass());
- r.intent.setExtrasClassLoader(cl);
- if (r.state != null) {
- r.state.setClassLoader(cl);
- }
- } catch (Exception e) {
- if (!mInstrumentation.onException(activity, e)) {
- throw new RuntimeException(
- "Unable to instantiate activity " + component
- + ": " + e.toString(), e);
- }
- }
此段代码就是创建Activity
mInstrumentation是Instrumentation的实例对象,
看Instrumentation的 newActivity()方法
- public Activity newActivity(ClassLoader cl, String className,
- Intent intent)
- throws InstantiationException, IllegalAccessException,
- ClassNotFoundException {
- return (Activity)cl.loadClass(className).newInstance();
- }
发现其实就是通过反射的方式来创建一个Activity的实例对象。
然后handleLaunchActivity方法中会调用
- handleResumeActivity(r.token, false, r.isForward);
下面看
- final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
- // If we are getting ready to gc after going to the background, well
- // we are back active so skip it.
- unscheduleGcIdler();
- ActivityClientRecord r = performResumeActivity(token, clearHide);
- if (r != null) {
- final Activity a = r.activity;
- if (localLOGV) Slog.v(
- TAG, "Resume " + r + " started activity: " +
- a.mStartedActivity + ", hideForNow: " + r.hideForNow
- + ", finished: " + a.mFinished);
- final int forwardBit = isForward ?
- WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
- // If the window hasn't yet been added to the window manager,
- // and this guy didn't finish itself or start another activity,
- // then go ahead and add the window.
- boolean willBeVisible = !a.mStartedActivity;
- if (!willBeVisible) {
- try {
- willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
- a.getActivityToken());
- } catch (RemoteException e) {
- }
- }//下面就是将activity的Veiw添加到手机的窗口的代码逻辑
- if (r.window == null && !a.mFinished && willBeVisible) {
- r.window = r.activity.getWindow();
- View decor = r.window.getDecorView();
- decor.setVisibility(View.INVISIBLE);
- ViewManager wm = a.getWindowManager();
- WindowManager.LayoutParams l = r.window.getAttributes();
- a.mDecor = decor;
- l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
- l.softInputMode |= forwardBit;
- if (a.mVisibleFromClient) {
- a.mWindowAdded = true;
- wm.addView(decor, l);
- }
- // If the window has already been added, but during resume
- // we started another activity, then don't yet make the
- // window visible.
- } else if (!willBeVisible) {
- if (localLOGV) Slog.v(
- TAG, "Launch " + r + " mStartedActivity set");
- r.hideForNow = true;
- }
- // Get rid of anything left hanging around.
- cleanUpPendingRemoveWindows(r);
- // The window is now visible if it has been added, we are not
- // simply finishing, and we are not starting another activity.
- if (!r.activity.mFinished && willBeVisible
- && r.activity.mDecor != null && !r.hideForNow) {
- if (r.newConfig != null) {
- if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
- + r.activityInfo.name + " with newConfig " + r.newConfig);
- performConfigurationChanged(r.activity, r.newConfig);
- r.newConfig = null;
- }
- if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
- + isForward);
- WindowManager.LayoutParams l = r.window.getAttributes();
- if ((l.softInputMode
- & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
- != forwardBit) {
- l.softInputMode = (l.softInputMode
- & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
- | forwardBit;
- if (r.activity.mVisibleFromClient) {
- ViewManager wm = a.getWindowManager();
- View decor = r.window.getDecorView();
- wm.updateViewLayout(decor, l);
- }
- }
- r.activity.mVisibleFromServer = true;
- mNumVisibleActivities++;
- if (r.activity.mVisibleFromClient) {
- r.activity.makeVisible();
- }
- }
- if (!r.onlyLocalRequest) {
- r.nextIdle = mNewActivities;
- mNewActivities = r;
- if (localLOGV) Slog.v(
- TAG, "Scheduling idle handler for " + r);
- Looper.myQueue().addIdleHandler(new Idler());
- }
- r.onlyLocalRequest = false;
- } else {
- // If an exception was thrown when trying to resume, then
- // just end this activity.
- try {
- ActivityManagerNative.getDefault()
- .finishActivity(token, Activity.RESULT_CANCELED, null);
- } catch (RemoteException ex) {
- }
- }
- }
此方法中调用了Activity的performResume()方法,performResume()又会调用Instrumentation类的callActivityOnResume()方法。callActivityOnResume方法就是通过反射的方式调用ACtivity的onResume()方法.
下面先看H类的performResume()方法
- public final ActivityClientRecord performResumeActivity(IBinder token,
- boolean clearHide) {
- ActivityClientRecord r = mActivities.get(token);
- if (localLOGV) Slog.v(TAG, "Performing resume of " + r
- + " finished=" + r.activity.mFinished);
- if (r != null && !r.activity.mFinished) {
- if (clearHide) {
- r.hideForNow = false;
- r.activity.mStartedActivity = false;
- }
- try {
- if (r.pendingIntents != null) {
- deliverNewIntents(r, r.pendingIntents);
- r.pendingIntents = null;
- }
- if (r.pendingResults != null) {
- deliverResults(r, r.pendingResults);
- r.pendingResults = null;
- }
- //调用Activity的performResume()方法
- r.activity.performResume();
- EventLog.writeEvent(LOG_ON_RESUME_CALLED,
- r.activity.getComponentName().getClassName());
- r.paused = false;
- r.stopped = false;
- r.state = null;
- } catch (Exception e) {
- if (!mInstrumentation.onException(r.activity, e)) {
- throw new RuntimeException(
- "Unable to resume activity "
- + r.intent.getComponent().toShortString()
- + ": " + e.toString(), e);
- }
- }
- }
- return r;
- }
- final void performResume() {
- performRestart();
- mFragments.execPendingActions();
- mLastNonConfigurationInstances = null;
- mCalled = false;
- // mResumed is set by the instrumentation
- //Instrumentation类的callActivityOnResume()方法
- mInstrumentation.callActivityOnResume(this);
- sp;
- </span> if (!mCalled) {
- throw new SuperNotCalledException(
- "Activity " + mComponent.toShortString() +
- " did not call through to super.onResume()");
- }
- // Now really resume, and install the current status bar and menu.
- mCalled = false;
- mFragments.dispatchResume();
- mFragments.execPendingActions();
- onPostResume();
- if (!mCalled) {
- throw new SuperNotCalledException(
- "Activity " + mComponent.toShortString() +
- " did not call through to super.onPostResume()");
- }
- }
- public void callActivityOnResume(Activity activity) {
- activity.mResumed = true;
- //回调Activity的onResume()方法
- activity.onResume();
- 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());
- }
- }
- }
- }
到此时Activity的onResume方法已经被调用了,但是关于界面的东西并没有看到,其实handleResumeActivity()方法的一下代码片段就是将Activity的Veiw添加到手机的窗口,并且显示出来。
- //下面就是将activity的Veiw添加到手机的窗口的代码逻辑
- if (r.window == null && !a.mFinished && willBeVisible) {
- r.window = r.activity.getWindow();
- View decor = r.window.getDecorView();
- decor.setVisibility(View.INVISIBLE);
- ViewManager wm = a.getWindowManager();
- WindowManager.LayoutParams l = r.window.getAttributes();
- a.mDecor = decor;
- l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
- l.softInputMode |= forwardBit;
- if (a.mVisibleFromClient) {
- a.mWindowAdded = true;
- wm.addView(decor, l);
- }
- final void attach(Context context, ActivityThread aThread,
- Instrumentation instr, IBinder token, int ident,
- Application application, Intent intent, ActivityInfo info,
- CharSequence title, Activity parent, String id,
- NonConfigurationInstances lastNonConfigurationInstances,
- Configuration config) {
- ....
- mWindow.setWindowManager(null, mToken, mComponent.flattenToString(),
- (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
- if (mParent != null) {
- mWindow.setContainer(mParent.getWindow());
- }
- mWindowManager = mWindow.getWindowManager();
- mCurrentConfig = config;
- }
- public void setWindowManager(WindowManager wm, IBinder appToken, String appName) {
- setWindowManager(wm, appToken, appName, false);
- }
- /**
- * Set the window manager for use by this Window to, for example,
- * display panels. This is <em>not</em> used for displaying the
- * Window itself -- that must be done by the client.
- *
- * @param wm The ViewManager for adding new windows.
- */
- public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
- boolean hardwareAccelerated) {
- mAppToken = appToken;
- mAppName = appName;
- if (wm == null) {
- wm = WindowManagerImpl.getDefault();
- }
- mWindowManager = new LocalWindowManager(wm, hardwareAccelerated);
- }
发现WindowManager 的实例为LocalWindowManager类型的;
ViewManager是一个接口,管理Activity的View添加 删除,更新
- package android.view;
- /** Interface to let you add and remove child views to an Activity. To get an instance
- * of this class, call {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
- */
- public interface ViewManager
- {
- public void addView(View view, ViewGroup.LayoutParams params);
- public void updateViewLayout(View view, ViewGroup.LayoutParams params);
- public void removeView(View view);
- }
handleResumeActivity()方法中的
- ....
- if (a.mVisibleFromClient) {
- a.mWindowAdded = true;
- wm.addView(decor, l);
- }
- ....
其实就是将Activity的根View decor添加到手机屏幕并显示,下面看LocalWindowManager的addView方法
- public final void addView(View view, ViewGroup.LayoutParams params) {
- // Let this throw an exception on a bad params.
- WindowManager.LayoutParams wp = (WindowManager.LayoutParams)params;
- CharSequence curTitle = wp.getTitle();
- if (wp.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
- wp.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
- if (wp.token == null) {
- View decor = peekDecorView();
- if (decor != null) {
- wp.token = decor.getWindowToken();
- }
- }
- if (curTitle == null || curTitle.length() == 0) {
- String title;
- if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA) {
- title="Media";
- } else if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY) {
- title="MediaOvr";
- } else if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
- title="Panel";
- } else if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL) {
- title="SubPanel";
- } else if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG) {
- title="AtchDlg";
- } else {
- title=Integer.toString(wp.type);
- }
- if (mAppName != null) {
- title += ":" + mAppName;
- }
- wp.setTitle(title);
- }
- } else {
- if (wp.token == null) {
- wp.token = mContainer == null ? mAppToken : mContainer.mAppToken;
- }
- if ((curTitle == null || curTitle.length() == 0)
- && mAppName != null) {
- wp.setTitle(mAppName);
- }
- }
- if (wp.packageName == null) {
- wp.packageName = mContext.getPackageName();
- }
- if (mHardwareAccelerated) {
- wp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
- } [java] view plaincopy
- //调用父类的方法
- super.addView(view, params);
- }
- }
我们看他的父类WindowManagerImpl.CompatModeWrapper的子类的addView方法
- @Override
- public void addView(View view, android.view.ViewGroup.LayoutParams params) {
- mWindowManager.addView(view, params, mCompatibilityInfo);
- }
mWindowManager是在CompatModeWrapper的构造方法中初始化,他是WindowManagerImpl类型的。
- CompatModeWrapper(WindowManager wm, CompatibilityInfoHolder ci) {
- //
- mWindowManager = wm instanceof CompatModeWrapper
- ? ((CompatModeWrapper)wm).mWindowManager : (WindowManagerImpl)wm;
- // Use the original display if there is no compatibility mode
- // to apply, or the underlying window manager is already a
- // compatibility mode wrapper. (We assume that if it is a
- // wrapper, it is applying the same compatibility mode.)
- if (ci == null) {
- mDefaultDisplay = mWindowManager.getDefaultDisplay();
- } else {
- //mDefaultDisplay = mWindowManager.getDefaultDisplay();
- mDefaultDisplay = Display.createCompatibleDisplay(
- mWindowManager.getDefaultDisplay().getDisplayId(), ci);
- }
- mCompatibilityInfo = ci;
- }
所以addVeiw调用的都是WindowManagerImpl的addVeiw的方法。WindowManagerImpl有多个addVeiw重载函数,但最终都是调用下面这个方法
该方法会创建一个ViewRootImp实例对象,ViewRootImp是实现每一个具体类的管理的核心类,ViewRootImp中的内部类W实现与WindowManager的交互。
每一个Activity都对应一个ViewRootImp实例对象
- private void addView(View view, ViewGroup.LayoutParams params,
- CompatibilityInfoHolder cih, boolean nest) {
- if (false) Log.v("WindowManager", "addView view=" + view);
- if (!(params instanceof WindowManager.LayoutParams)) {
- throw new IllegalArgumentException(
- "Params must be WindowManager.LayoutParams");
- }
- final WindowManager.LayoutParams wparams
- = (WindowManager.LayoutParams)params;
- ViewRootImpl root;
- View panelParentView = null;
- synchronized (this) {
- // Here's an odd/questionable case: if someone tries to add a
- // view multiple times, then we simply bump up a nesting count
- // and they need to remove the view the corresponding number of
- // times to have it actually removed from the window manager.
- // This is useful specifically for the notification manager,
- // which can continually add/remove the same view as a
- // notification gets updated.
- int index = findViewLocked(view, false);
- if (index >= 0) {
- if (!nest) {
- throw new IllegalStateException("View " + view
- + " has already been added to the window manager.");
- }
- root = mRoots[index];
- root.mAddNesting++;
- // Update layout parameters.
- view.setLayoutParams(wparams);
- root.setLayoutParams(wparams, true);
- return;
- }
- // If this is a panel window, then find the window it is being
- // attached to for future reference.
- if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
- wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
- final int count = mViews != null ? mViews.length : 0;
- for (int i=0; i<count; i++) {
- if (mRoots[i].mWindow.asBinder() == wparams.token) {
- panelParentView = mViews[i];
- }
- }
- }
- root = new ViewRootImpl(view.getContext());
- root.mAddNesting = 1;
- if (cih == null) {
- root.mCompatibilityInfo = new CompatibilityInfoHolder();
- } else {
- root.mCompatibilityInfo = cih;
- }
- view.setLayoutParams(wparams);
- if (mViews == null) {
- index = 1;
- mViews = new View[1];
- mRoots = new ViewRootImpl[1];
- mParams = new WindowManager.LayoutParams[1];
- } else {
- index = mViews.length + 1;
- Object[] old = mViews;
- mViews = new View[index];
- System.arraycopy(old, 0, mViews, 0, index-1);
- old = mRoots;
- mRoots = new ViewRootImpl[index];
- System.arraycopy(old, 0, mRoots, 0, index-1);
- old = mParams;
- mParams = new WindowManager.LayoutParams[index];
- System.arraycopy(old, 0, mParams, 0, index-1);
- }
- index--;
- //每一Activity对应一个View(decor)
- mViews[index] = view;
- //每一个Activity都对应一个ViewRootImp实例对象
- mRoots[index] = root;
- mParams[index] = wparams;
- }
- // do this last because it fires off messages to start doing things
- //让ViewRootImp与当前要显示的View进行关联
- root.setView(view, wparams, panelParentView);
- }
- public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
- synchronized (this) {
- <span style="white-space:pre"> </span>.......
- .......
- .......
- // Schedule the first layout -before- adding to the window
- // manager, to make sure we do the relayout before receiving
- // any other events from the system.
- requestLayout();
- .......
- .......
- .......
- <span style="white-space:pre"> </span>//给View设置一个父View,这里的父子关系不是继承关系,而是一种包含关系
- view.assignParent(this);
- .......
- .......
- .......
- }
- }
- }
- }
到目前为止Activity的View还是没有显示出来。
handleResumeActivity()方法中以下语句就是让Activity的View显示出来
- ......
- activity.makeVisible();
- .......
- void makeVisible() {
- if (!mWindowAdded) {
- ViewManager wm = getWindowManager();
- wm.addView(mDecor, getWindow().getAttributes());
- mWindowAdded = true;
- }
- mDecor.setVisibility(View.VISIBLE);
- }
- 启动Activity的过程
- Activity启动的过程
- Activity的启动过程
- Activity的启动过程
- Activity的启动过程
- Activity启动的过程
- Activity的启动过程
- Activity的启动过程
- Activity的启动过程
- activity 的启动过程
- activity的启动过程分析
- Activity组件的启动过程
- Activity组件的启动过程
- Activity的启动过程详解
- Activity组件的启动过程
- Activity的启动过程--startActivity()
- 关于Activity的启动过程
- 启动activity的过程追踪
- test
- mahout出错了,utility.concurrent.threadpool编程
- Java Socket学习---nio实现阻塞多线程通信
- iOS开发 ----- UIViewController转场动画
- Android学习系列: 采用pull解析xml文件
- Activity的启动过程
- 第5章 TCP服务器-客服端程序例子
- Git教程干货集锦
- AndroidStuido在svn下需要忽略的文件
- EClispe 开发下 不自动生成R文件
- 判断iframe是否加载完毕,在执行某方法
- java—封装、继承、多态
- HDU 4421 & ZOJ 3556 Bit Magic(2-SAT 位运算 模板题)
- 集体智慧编程第二三章学习总结