您的位置:首页 > 移动开发 > Android开发

Android四大组件的工作过程(一)-Activity的工作过程

2017-12-08 11:34 603 查看

Activity的工作过程

在android的开发中经常需要启动一个activity,大家都知道最简单的activity启动方式就是使用startActivity(),那么Activity的工作流程就从这儿开始咯,咳咳。

1.Activity.startActivity(Intent intent)

@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}


从源码来看,startActivity()方法最终都会调用startActivityForResult(),那我们就跟过去看看

public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
if (mParent == null) {
Instrumentation.ActivityResult ar =
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);
}
}
}


这里需要关注的是mParent==null的逻辑部分,注意到mMainThread.getApplicationThread()这个参数,它的类型是ApplicationThread,ApplicationThread是ActivityThread的一个内部类,接着需要看的是Instrumentation的execStartActivity(),源码如下:

public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
Uri referrer = target != null ? target.onProvideReferrer() : null;
if (referrer != null) {
intent.putExtra(Intent.EXTRA_REFERRER, referrer);
}
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess();
//通过AMS启动
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
//检测activity的启动结果
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}


从源码中可以看到,Activity的启动最终是由ActivityManagerNative.getDefault()的startActivity()方法完成的。ActivityManagerNative.getDefault()就是期待已久的ActivityManagerService类(简称AMS)。ActivityManagerService及其子类实质都是IActivityManager的实现类,其实就是实现的AIDL接口,跟过去看看getDefault的逻辑:

static public IActivityManager getDefault() {
return gDefault.get();
}

private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};


可以发现在ActivityManagerNative中AMS这个binder对象采用单例模式对外提供。终究是回到了AMS中,接下来去看看AMS中的startActivity方法即可。

@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}

@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
userId, false, ALLOW_FULL_ONLY, "startActivity", null);
// TODO: Switch to user app stacks here.
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null);
}


发现调用了之前提到的ActivityStackSupervisor的startActivityMayWait()方法。这里的目的就是想去通过栈的管理者来通过传进来的数据去改变栈,并且拿到被启动activity的ActivityRecord实例。在startActivityMayWait方法中做了很多事情,就不贴源码了,来一张图看流程



startActivityMayWait中调用startActivityLocked,再到startActivityUncheckedLocked,进入ActivityStack中

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
2114        if (mStackSupervisor.inResumeTopActivity) {
2115            // Don't even start recursing.
2116            return false;
2117        }
2118
2119        boolean result = false;
2120        try {
2121            // Protect against recursion.
2122            mStackSupervisor.inResumeTopActivity = true;
2123            if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
2124                mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
2125                mService.updateSleepIfNeededLocked();
2126            }
2127            result = resumeTopActivityInnerLocked(prev, options);
2128        } finally {
2129            mStackSupervisor.inResumeTopActivity = false;
2130        }
2131        return result;
2132    }


继续看resumeTopActivityInnerLocked(prev, options);这个方法太长了,我分析了一整天,终于所有体会吧。这个方法最终的作用是将启动者activity的生命周期变成paused,这样之后被启动的activity的实例创建了之后才能顺利的resumed。我们来看部分代码:

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
......
2149
2150        mStackSupervisor.cancelInitializingActivities();
2151
2152        // Find the first activity that is not finishing.
//找出栈顶中第一个没有在被finish的activity,既我们要启动的actiivty
2153        final ActivityRecord next = topRunningActivityLocked();
2154
2155        // Remember how we'll process this pause/resume situation, and ensure
2156        // that the state is reset however we wind up proceeding.
2157        final boolean userLeaving = mStackSupervisor.mUserLeaving;
2158        mStackSupervisor.mUserLeaving = false;
2159
2160        final TaskRecord prevTask = prev != null ? prev.task : null;
//如果整个stack里面是空的,那么直接启动launcher
2161        if (next == null) {
2162            // There are no more activities!
2163            final String reason = "noMoreActivities";
2164            final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack()
2165                    ? HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
2166            if (!mFullscreen && adjustFocusToNextFocusableStackLocked(returnTaskType, reason)) {
2167                // Try to move focus to the next visible stack with a running activity if this
2168                // stack is not covering the entire screen.
2169                return mStackSupervisor.resumeFocusedStackTopActivityLocked(
2170                        mStackSupervisor.getFocusedStack(), prev, null);
2171            }
2172
2173            // Let's just start up the Launcher...
2174            ActivityOptions.abort(options);
2175            if (DEBUG_STATES) Slog.d(TAG_STATES,
2176                    "resumeTopActivityLocked: No more activities go home");
2177            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2178            // Only resume home if on home display
2179            return isOnHomeDisplay() &&
2180                    mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
2181        }
2182
2183        next.delayedResume = false;
2184
2185        // If the top activity is the resumed one, nothing to do.
//如果被启动的activity就是当前处理Resumed状态的activity的话,就什么不做。(一个activity启动自己就是这种情况)
2186        if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
2187                    mStackSupervisor.allResumedActivitiesComplete()) {
2188            // Make sure we have executed any pending transitions, since there
2189            // should be nothing left to do at this point.
2190            mWindowManager.executeAppTransition();
2191            mNoAnimActivities.clear();
2192            ActivityOptions.abort(options);
2193            if (DEBUG_STATES) Slog.d(TAG_STATES,
2194                    "resumeTopActivityLocked: Top activity resumed " + next);
2195            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2196            return false;
2197        }
2198
2199        final TaskRecord nextTask = next.task;
2200        if (prevTask != null && prevTask.stack == this &&
2201                prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
2202            if (DEBUG_STACK)  mStackSupervisor.validateTopActivitiesLocked();
2203            if (prevTask == nextTask) {
2204                prevTask.setFrontOfTask();
2205            } else if (prevTask != topTask()) {
2206                // This task is going away but it was supposed to return to the home stack.
2207                // Now the task above it has to return to the home task instead.
2208                final int taskNdx = mTaskHistory.indexOf(prevTask) + 1;
2209                mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE);
2210            } else if (!isOnHomeDisplay()) {
2211                return false;
2212            } else if (!isHomeStack()){
2213                if (DEBUG_STATES) Slog.d(TAG_STATES,
2214                        "resumeTopActivityLocked: Launching home next");
2215                final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
2216                        HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
2217                return isOnHomeDisplay() &&
2218                        mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "prevFinished");
2219            }
2220        }
2221
2222        // If we are sleeping, and there is no resumed activity, and the top
2223        // activity
155fc
is paused, well that is the state we want.
//如果系统正在休眠,并且当前最上层的activity都已经是paused状态了(top activity就是我们要启动的activity)。那就是完美的状态。
2224        if (mService.isSleepingOrShuttingDownLocked()
2225                && mLastPausedActivity == next
2226                && mStackSupervisor.allPausedActivitiesComplete()) {
2227            // Make sure we have executed any pending transitions, since there
2228            // should be nothing left to do at this point.
2229            mWindowManager.executeAppTransition();
2230            mNoAnimActivities.clear();
2231            ActivityOptions.abort(options);
2232            if (DEBUG_STATES) Slog.d(TAG_STATES,
2233                    "resumeTopActivityLocked: Going to sleep and all paused");
2234            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2235            return false;
2236        }
2237
2238        // Make sure that the user who owns this activity is started.  If not,
2239        // we will just leave it as is because someone should be bringing
2240        // another user's activities to the top of the stack.
2241        if (!mService.mUserController.hasStartedUserState(next.userId)) {
2242            Slog.w(TAG, "Skipping resume of top activity " + next
2243                    + ": user " + next.userId + " is stopped");
2244            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2245            return false;
2246        }
2247
2248        // The activity may be waiting for stop, but that is no longer
2249        // appropriate for it.
2250        mStackSupervisor.mStoppingActivities.remove(next);
2251        mStackSupervisor.mGoingToSleepActivities.remove(next);
2252        next.sleeping = false;
2253        mStackSupervisor.mWaitingVisibleActivities.remove(next);
2254
2255        if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resuming " + next);
2256
2257        // If we are currently pausing an activity, then don't do anything until that is done.
2258        if (!mStackSupervisor.allPausedActivitiesComplete()) {
2259            if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
2260                    "resumeTopActivityLocked: Skip resume: some activity pausing.");
2261            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2262            return false;
2263        }
2264
2265        mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
2266
2267        // We need to start pausing the current activity so the top one can be resumed...
//先把现在的当前还是resumed的activity pause了,这样新加进来的activity才能resume。基础知识
2268        final boolean dontWaitForPause = (next.info.flags & FLAG_RESUME_WHILE_PAUSING) != 0;
////开始暂定现在stack里面所有的activity
2269        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, dontWaitForPause);
//开始pausing当前的所有activity,并且返回一个是否暂定成功的结果回来
2270        if (mResumedActivity != null) {
2271            if (DEBUG_STATES) Slog.d(TAG_STATES,
2272                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
2273            pausing |= startPausingLocked(userLeaving, false, next, dontWaitForPause);
2274        }
2275        if (pausing) {
2276            if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG_STATES,
2277                    "resumeTopActivityLocked: Skip resume: need to start pausing");
2278            // At this point we want to put the upcoming activity's process
2279            // at the top of the LRU list, since we know we will be needing it
2280            // very soon and it would be a waste to let it get killed if it
2281            // happens to be sitting towards the end.
2282            if (next.app != null && next.app.thread != null) {
2283                mService.updateLruProcessLocked(next.app, true, null);
2284            }
2285            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2286            return true;
2287        } else if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
2288                mStackSupervisor.allResumedActivitiesComplete()) {
2289            // It is possible for the activity to be resumed when we paused back stacks above if the
2290            // next activity doesn't have to wait for pause to complete.
2291            // So, nothing else to-do except:
2292            // Make sure we have executed any pending transitions, since there
2293            // should be nothing left to do at this point.
2294            mWindowManager.executeAppTransition();
2295            mNoAnimActivities.clear();
2296            ActivityOptions.abort(options);
2297            if (DEBUG_STATES) Slog.d(TAG_STATES,
2298                    "resumeTopActivityLocked: Top activity resumed (dontWaitForPause) " + next);
2299            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2300            return true;
2301        }
2302
2303        // If the most recent activity was noHistory but was only stopped rather
2304        // than stopped+finished because the device went to sleep, we need to make
2305        // sure to finish it as we're making a new activity topmost.
2306        if (mService.isSleepingLocked() && mLastNoHistoryActivity != null &&
2307                !mLastNoHistoryActivity.finishing) {
2308            if (DEBUG_STATES) Slog.d(TAG_STATES,
2309                    "no-history finish of " + mLastNoHistoryActivity + " on new resume");
2310            requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
2311                    null, "resume-no-history", false);
2312            mLastNoHistoryActivity = null;
2313        }
2314
2315        if (prev != null && prev != next) {
2316            if (!mStackSupervisor.mWaitingVisibleActivities.contains(prev)
2317                    && next != null && !next.nowVisible) {
2318                mStackSupervisor.mWaitingVisibleActivities.add(prev);
2319                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
2320                        "Resuming top, waiting visible to hide: " + prev);
2321            } else {
2322                // The next activity is already visible, so hide the previous
2323                // activity's windows right now so we can show the new one ASAP.
2324                // We only do this if the previous is finishing, which should mean
2325                // it is on top of the one being resumed so hiding it quickly
2326                // is good.  Otherwise, we want to do the normal route of allowing
2327                // the resumed activity to be shown so we can decide if the
2328                // previous should actually be hidden depending on whether the
2329                // new one is found to be full-screen or not.
2330                if (prev.finishing) {
2331                    mWindowManager.setAppVisibility(prev.appToken, false);
2332                    if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
2333                            "Not waiting for visible to hide: " + prev + ", waitingVisible="
2334                            + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
2335                            + ", nowVisible=" + next.nowVisible);
2336                } else {
2337                    if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
2338                            "Previous already visible but still waiting to hide: " + prev
2339                            + ", waitingVisible="
2340                            + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
2341                            + ", nowVisible=" + next.nowVisible);
2342                }
2343            }
2344        }


最终在函数的末尾会又调用ActivityStackSupervisor的startSpecificActivityLocked(next, true, true);

void startSpecificActivityLocked(ActivityRecord r,
1390            boolean andResume, boolean checkConfig) {
1391        // Is this activity's application already running?
//注意了,这里的app之后会用到,因为app.thread就是获得了applicationthread实例!
1392        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1393                r.info.applicationInfo.uid, true);
1394
1395        r.task.stack.setLaunchTime(r);
1396
1397        if (app != null && app.thread != null) {
1398            try {
1399                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1400                        || !"android".equals(r.info.packageName)) {
1401                    // Don't add this if it is a platform component that is marked
1402                    // to run in multiple processes, because this is actually
1403                    // part of the framework so doesn't make sense to track as a
1404                    // separate apk in the process.
1405                    app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1406                            mService.mProcessStats);
1407                }
//将app,信息完整的要启动的ActivityRecord类的实例传到另一个方法里面去
1408                realStartActivityLocked(r, app, andResume, checkConfig);
1409                return;
1410            } catch (RemoteException e) {
1411                Slog.w(TAG, "Exception when starting activity "
1412                        + r.intent.getComponent().flattenToShortString(), e);
1413            }
1414
1415            // If a dead object exception was thrown -- fall through to
1416            // restart the application.
1417        }
1418
1419        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
1420                "activity", r.intent.getComponent(), false, false, true);
1421    }


继续跟进这个realStartActivityLocked()(真正启动activity的过程在这里):

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1191            boolean andResume, boolean checkConfig) throws RemoteException {
1192
1193        if (!allPausedActivitiesComplete()) {
1194            // While there are activities pausing we skipping starting any new activities until
1195            // pauses are complete. NOTE: that we also do this for activities that are starting in
1196            // the paused state because they will first be resumed then paused on the client side.
1197            if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1198                    "realStartActivityLocked: Skipping start of r=" + r
1199                    + " some activities pausing...");
1200            return false;
1201        }
1202
1203        if (andResume) {
1204            r.startFreezingScreenLocked(app, 0);
1205            mWindowManager.setAppVisibility(r.appToken, true);
1206
1207            // schedule launch ticks to collect information about slow apps.
1208            r.startLaunchTickingLocked();
1209        }
1210
1211        // Have the window manager re-evaluate the orientation of
1212        // the screen based on the new activity order.  Note that
1213        // as a result of this, it can call back into the activity
1214        // manager with a new orientation.  We don't care about that,
1215        // because the activity is not currently running so we are
1216        // just restarting it anyway.
1217        if (checkConfig) {
1218            Configuration config = mWindowManager.updateOrientationFromAppTokens(
1219                    mService.mConfiguration,
1220                    r.mayFreezeScreenLocked(app) ? r.appToken : null);
1221            // Deferring resume here because we're going to launch new activity shortly.
1222            // We don't want to perform a redundant launch of the same record while ensuring
1223            // configurations and trying to resume top activity of focused stack.
1224            mService.updateConfigurationLocked(config, r, false, true /* deferResume */);
1225        }
1226
1227        r.app = app;
1228        app.waitingToKill = null;
1229        r.launchCount++;
1230        r.lastLaunchTime = SystemClock.uptimeMillis();
1231
1232        if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1233
1234        int idx = app.activities.indexOf(r);
1235        if (idx < 0) {
1236            app.activities.add(r);
1237        }
1238        mService.updateLruProcessLocked(app, true, null);
1239        mService.updateOomAdjLocked();
1240
1241        final TaskRecord task = r.task;
1242        if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1243                task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
1244            setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE", false);
1245        }
1246
1247        final ActivityStack stack = task.stack;
1248        try {
1249            if (app.thread == null) {
1250                throw new RemoteException();
1251            }
1252            List<ResultInfo> results = null;
1253            List<ReferrerIntent> newIntents = null;
1254            if (andResume) {
1255                results = r.results;
1256                newIntents = r.newIntents;
1257            }
1258            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1259                    "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1260                    + " newIntents=" + newIntents + " andResume=" + andResume);
1261            if (andResume) {
1262                EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
1263                        r.userId, System.identityHashCode(r),
1264                        task.taskId, r.shortComponentName);
1265            }
1266            if (r.isHomeActivity()) {
1267                // Home process is the root process of the task.
1268                mService.mHomeProcess = task.mActivities.get(0).app;
1269            }
.......
//通过applicaitonthread调用客户端binder实体的方法。
1309            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1310                    System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
1311                    new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
1312                    task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
1313                    newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
1314
1315         .......
1387    }


这里面两个很重要的参数,一个是ActivityRecord,一个是app。前者就是在ActivityStack里面转了一圈之后得出来的最终要启动的Activity的信息记录类。后者就是用来获得ApplicationThread来通知客户端拿这个ActivityRecord去管理你的activity的生命周期吧!相当于AMS给了ActivityThread一个任务,让后者去执行。同样,这也是一个IPC的过程。最终调用链绕了好大一圈终于又回到了ApplicaitonThread。

​ 值得一提的是,凡是schedule开头的函数都是通过handler来做线程调度的

2        @Override
713        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
714                ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
715                CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
716                int procState, Bundle state, PersistableBundle persistentState,
717                List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
718                boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
719
720            updateProcessState(procState, false);
721
722            ActivityClientRecord r = new ActivityClientRecord();
723
724            r.token = token;
725            r.ident = ident;
726            r.intent = intent;
727            r.referrer = referrer;
728            r.voiceInteractor = voiceInteractor;
729            r.activityInfo = info;
730            r.compatInfo = compatInfo;
731            r.state = state;
732            r.persistentState = persistentState;
733
734            r.pendingResults = pendingResults;
735            r.pendingIntents = pendingNewIntents;
736
737            r.startsNotResumed = notResumed;
738            r.isForward = isForward;
739
740            r.profilerInfo = profilerInfo;
741
742            r.overrideConfig = overrideConfig;
743            updatePendingConfiguration(curConfig);
744
//andler发送了一个message
745            sendMessage(H.LAUNCH_ACTIVITY, r);
746        }


我们来看handler的处理会最终调用handlerLaunchActivity方法:

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
2707        // If we are getting ready to gc after going to the background, well
2708        // we are back active so skip it.
2709        unscheduleGcIdler();
2710        mSomeActivitiesChanged = true;
2711
2712        if (r.profilerInfo != null) {
2713            mProfiler.setProfiler(r.profilerInfo);
2714            mProfiler.startProfiling();
2715        }
2716
2717        // Make sure we are running with the most recent config.
2718        handleConfigurationChanged(null, null);
2719
2720        if (localLOGV) Slog.v(
2721            TAG, "Handling launch of " + r);
2722
2723        // Initialize before creating the activity
2724        WindowManagerGlobal.initialize();
2725
2726        Activity a = performLaunchActivity(r, customIntent);
2727
2728        if (a != null) {
2729            r.createdConfig = new Configuration(mConfiguration);
2730            reportSizeConfigurations(r);
2731            Bundle oldState = r.state;
2732            handleResumeActivity(r.token, false, r.isForward,
2733                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
2734
2735            if (!r.activity.mFinished && r.startsNotResumed) {
2736                // The activity manager actually wants this one to start out paused, because it
2737                // needs to be visible but isn't in the foreground. We accomplish this by going
2738                // through the normal startup (because activities expect to go through onResume()
2739                // the first time they run, before their window is displayed), and then pausing it.
2740                // However, in this case we do -not- need to do the full pause cycle (of freezing
2741                // and such) because the activity manager assumes it can just retain the current
2742                // state it has.
2743                performPauseActivityIfNeeded(r, reason);
2744
2745                // We need to keep around the original state, in case we need to be created again.
2746                // But we only do this for pre-Honeycomb apps, which always save their state when
2747                // pausing, so we can not have them save their state when restarting from a paused
2748                // state. For HC and later, we want to (and can) let the state be saved as the
2749                // normal part of stopping the activity.
2750                if (r.isPreHoneycomb()) {
2751                    r.state = oldState;
2752                }
2753            }
2754        } else {
2755            // If there was an error, for any reason, tell the activity manager to stop us.
2756            try {
2757                ActivityManagerNative.getDefault()
2758                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
2759                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
2760            } catch (RemoteException ex) {
2761                throw ex.rethrowFromSystemServer();
2762            }
2763        }
2764    }


可以看到activity的实例是由performLaunchActivity方法生成的。做了这些事情

从ActivityClientRecord中获取获取组件信息

通过Instrumentation创建Activity对象

通过LoadApk的makeApplication创建application,这个方法有兴趣自己去看,就是一个单例而已。

创建contextImpl对象,并且调用activity的attach()方法来进行一些activity初始化

调用activity的onCreat()方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android