Android点击应用Icon发生了什么

来源:互联网 发布:联通网络信号怎么样 编辑:程序博客网 时间:2024/05/01 07:02

Android点击应用Icon发生了什么
首发个人博客地址

启动一个Android应用

启动一个Android应用的代码如下所示:

Intent intent = new Intent();    intent.setClassName(getApplicationContext(), "com.xx.xx.MainActivity");    startActivity(intent);

当startActivity(intent)开始时,走进了Android系统的Android Framework代码;

Launch发送启动启动应用命令

找到启动应用ActivityStack;

  1. 代码从Activity.java开始,首先封装对startActivity进行了三次封装;
        startActivity(intent);        //套一层        startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) 
  1. 从这里开始调用Instrumentation.java类execStartActivity()方法
//再套一层        public ActivityResult execStartActivity(            Context who, IBinder contextThread, IBinder token, Activity target,            Intent intent, int requestCode){             intent.setAllowFds(false);         int result = ActivityManagerNative.getDefault()                .startActivity(whoThread, intent,                        intent.resolveTypeIfNeeded(who.getContentResolver()),                        null, 0, token, target != null ? target.mEmbeddedID : null,                        requestCode, false, false, null, null, false);         checkStartActivityResult(result, intent);        }
  1. 这里通过进程间调用,从Launch应用的进程调用到system_process进程中;这里调用
    ActivityManagerNative.getDefault()的startActivity()方法实际调用ActivityManagerService.startActivity()方法;
public final int startActivity(IApplicationThread caller, String callingPackage,            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,            int startFlags, ProfilerInfo profilerInfo, Bundle options) {            return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,            resultWho, requestCode, startFlags, profilerInfo, options,            UserHandle.getCallingUserId());}
  1. 这里内部套一层直接调用startActivityAsUser()方法;

    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,    Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,    int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {    ...    //调用ActivityStackSupervisor方法;    return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,        resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,        profilerInfo, null, null, options, userId, null, null);}
  2. 调用ActivityStackSupervisor.java的startActivityMayWait方法。首先拷贝intent数据,然后调用resolveActivity()解析数据。最后调用startActivityLocked()方法;

    int startActivityMayWait(IApplicationThread caller, int callingUid,    String callingPackage, Intent intent, String resolvedType,    IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,    IBinder resultTo, String resultWho, int requestCode, int startFlags,    ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,    Bundle options, int userId, IActivityContainer iContainer, TaskRecord inTask) {    //拷贝对象,终于干了一件正事    intent = new Intent(intent);    // 解析数据,构造ActivityInfo 对象,process,apk安装的文件路径    //解析一下目标Acitivity,安装没,那个包里,安装位置在哪里,设计到应用安装。以后再讲;    ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,profilerInfo, userId);    ....省略    //再一层;    int res = startActivityLocked(caller, intent, resolvedType, aInfo,            voiceSession, voiceInteractor, resultTo, resultWho,            requestCode, callingPid, callingUid, callingPackage,            realCallingPid, realCallingUid, startFlags, options,            componentSpecified, null, container, inTask);    ....省略    return res;}}
  3. 检测一下启动权限,发RESULT_CANCELED;new AcitivityRecord对象;然后把还没启动的Activity的启动,然后在启动我们需要Activity;

    final int startActivityLocked(IApplicationThread caller,    Intent intent, String resolvedType, ActivityInfo aInfo,    IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,    IBinder resultTo, String resultWho, int requestCode,    int callingPid, int callingUid, String callingPackage,    int realCallingPid, int realCallingUid, int startFlags, Bundle options,    boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container,    TaskRecord inTask) {    ...    int err = ActivityManager.START_SUCCESS;    //... 构造ActivityRecord对象,很重要对象,后面要用到哦    ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,        intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,        requestCode, componentSpecified, this, container, options);    if (outActivity != null) {        outActivity[0] = r;    }    final ActivityStack stack = getFocusedStack();    //启动还未启动Acitvity.mPendingActivityLaunches 调用            startActivityUncheckedLocked()    doPendingActivityLaunchesLocked(false);    //再套一层;    err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,        startFlags, true, options, inTask);    ....省略return err;}
  4. 根据用户指定的启动形式获取应用启动的堆栈。然后通过Activity堆栈来启动Activity;

    final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord,    IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,boolean doResume, Bundle options, TaskRecord inTask) {    ...    targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);    ...return ActivityManager.START_SUCCESS;}
  5. 调用ActivityStack.java的addActivityToTop(),把需要加入Activity加栈顶,然后通ActivityStackSupervisor的resumeTopActivitiesLocked();

    final void startActivityLocked(ActivityRecord r, boolean newTask,    boolean doResume, boolean keepCurTransition, Bundle options) {TaskRecord task = null;if (!newTask) {    //从 mTaskHistory对象中找到Task任务    boolean startIt = true;    for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {        task = mTaskHistory.get(taskNdx);        if (task.getTopActivity() == null) {            continue;        }        if (task == r.task) {        ...        } else if (task.numFullscreen > 0) {            startIt = false;        }    }}task = r.task;task.addActivityToTop(r);task.setFrontOfTask();r.putInHistory();...if (doResume) {    //又回去了,到ActivityStackSupervisor去    mStackSupervisor.resumeTopActivitiesLocked(this, r, options);}}
  6. 找到需要启动ActivityStack,调用targetStack.resumeTopActivityLocked方法;

    boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,    Bundle targetOptions) {if (targetStack == null) {    targetStack = getFocusedStack();}boolean result = false;if (isFrontStack(targetStack)) {    result = targetStack.resumeTopActivityLocked(target, targetOptions);}...return result;}

pause当前Activity

  1. 找到ActivityStack后,先暂停当前的Activity,即当前luncher;停了之后在启动当前的Activity;这里,我们先看系统如何停止当前的Activity;下期在看如何启动Activity;

    final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {... next : com.app.monitor.demo/.MainActivity t932}ActivityRecord next = topRunningActivityLocked(null);....final TaskRecord nextTask = next.task;if (mResumedActivity != null) {    //暂停当前Activity    pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);}if (pausing) {    //next.app.thread 还没建    if (next.app != null && next.app.thread != null) {        mService.updateLruProcessLocked(next.app, true, null);    }    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();    return true;} AppGlobals.getPackageManager().setPackageStoppedState(            next.packageName, false, next.userId);//停了当前Activity,下面开始启动DemoActivity;boolean anim = true;if (prev != null) {    if (prev.finishing) {       //擦屁股事情要做一下    } else {        //准备下一个Activity显示,过渡事情;        ...    }    ...}...ActivityStack lastStack = mStackSupervisor.getLastStack();if (next.app != null && next.app.thread != null) {//程序还没启动,这个暂时不看....} else {    ...    这里开始调用了ActivityStackSupervisor.startSpecificActivityLocked();     mStackSupervisor.startSpecificActivityLocked(next, true, true);}return true; }
  2. 调用自己的startPausingLocked方法。先把luncher所在Activity赋值给了mPausingActivity;状态也改为ActivityState.PAUSING;任何调用了 prev.app.thread.schedulePauseActivity()方法;这里涉及到从system_process到要启动应用,因此这里有一个超时检查;

    final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,    boolean dontWait) {ActivityRecord prev = mResumedActivity;...//自己是父,pausing自己所有子Activityif (mActivityContainer.mParentActivity == null) {    // Top level stack, not a child. Look for child stacks.    mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait);}//改变当前Activity的状态未pausingmResumedActivity = null;mPausingActivity = prev;mLastPausedActivity = prev;mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0        || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;prev.state = ActivityState.PAUSING;prev.task.touchActiveTime();clearLaunchTime(prev);final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();if (prev.app != null && prev.app.thread != null) {    try {        ....       //这里真正干pause事情了        prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,                userLeaving, prev.configChangeFlags, dontWait);    } catch (Exception e) {    }} if (!mService.isSleepingOrShuttingDown()) {    mStackSupervisor.acquireLaunchWakelock();}if (mPausingActivity != null) {    if (dontWait) {    ...    } else {    //这个做一次暂停任务检测,看看在这个时间段内有没有执行完        Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);        msg.obj = prev;        prev.pauseTime = SystemClock.uptimeMillis();        mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);        if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");        return true;    }}}

    3.这里最终会通过system_procee进程中最后调用Launch进程中UI进程;在UI进程找,调用Launch进程所在Activity.onPause()方法;

创建一个app进程

前面说到,已经停止了Launch的Activity,但是这个时候,app的进程还不存在,所以首先应该创建一个应用进程。

  1. 如果进程存在,启动Activity,不存在,创建进程;

     void startSpecificActivityLocked(ActivityRecord r,    boolean andResume, boolean checkConfig) {// Is this activity's application already running?ProcessRecord app = mService.getProcessRecordLocked(r.processName,        r.info.applicationInfo.uid, true);r.task.stack.setLaunchTime(r);if (app != null && app.thread != null) {//如果进程已经存在话,不需要启动进程了,如果没,启动进程;    try {        if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0                || !"android".equals(r.info.packageName)) {            // Don't add this if it is a platform component that is marked            // to run in multiple processes, because this is actually            // part of the framework so doesn't make sense to track as a            // separate apk in the process.            app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,                    mService.mProcessStats);        }        realStartActivityLocked(r, app, andResume, checkConfig);        return;    } catch (RemoteException e) {        Slog.w(TAG, "Exception when starting activity "                + r.intent.getComponent().flattenToShortString(), e);    }}//准备启动进程喽mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,        "activity", r.intent.getComponent(), false, false, true);}
  2. 套了一层接口

     final ProcessRecord startProcessLocked(String processName,    ApplicationInfo info, boolean knownToBeDead, int intentFlags,    String hostingType, ComponentName hostingName, boolean allowWhileBooting,    boolean isolated, boolean keepIfLarge) {return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,        hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,        null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,        null /* crashHandler */);}
  3. 如果进程没创建,那么先建个对象,记录一下,不然system_process怎么表示一个进程;然后才开始创建一个进程

    //开始干事了final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,    boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,    boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,    String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {if (app == null) {   //app还没创建,先创建一个对象,表示这个app进程的    app = newProcessRecordLocked(info, processName, isolated, isolatedUid);    ...} else {  ...}//开始干,再包一层startProcessLocked(app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);return (app.pid != 0) ? app : null;}
  4. newProcessRecordLocked()是对new ProcessRecord()封装;

     final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess,    boolean isolated, int isolatedUid) {String proc = customProcess != null ? customProcess : info.processName;BatteryStatsImpl.Uid.Proc ps = null;BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();int uid = info.uid;...return new ProcessRecord(stats, info, proc, uid);}
  5. ProcessRecord构造函数

    ProcessRecord(BatteryStatsImpl _batteryStats, ApplicationInfo _info,    String _processName, int _uid) {mBatteryStats = _batteryStats;info = _info;isolated = _info.uid != _uid;uid = _uid;userId = UserHandle.getUserId(_uid);processName = _processName;pkgList.put(_info.packageName, new ProcessStats.ProcessStateHolder(_info.versionCode));maxAdj = ProcessList.UNKNOWN_ADJ;curRawAdj = setRawAdj = -100;curAdj = setAdj = -100;persistent = false;removed = false;lastStateTime = lastPssTime = nextPssTime = SystemClock.uptimeMillis();}
  6. 调用Process.start()启动应用,这里同样是跨进程调用,所以也做了超时检查;

    private final void startProcessLocked(ProcessRecord app, String hostingType,    String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {    try {    int uid = app.uid;    int[] gids = null;    int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;    if (!app.isolated) {        int[] permGids = null;        ....        if (permGids == null) {            gids = new int[2];//[50091, 9997]        } else {            gids = new int[permGids.length + 2];            System.arraycopy(permGids, 0, gids, 2, permGids.length);        }        gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));        gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid));    }    //开始,这里定义了entryPoint:也就是Android世界的入口android.app.ActivityThread    Process.ProcessStartResult startResult = Process.start(entryPoint,            app.processName, uid, uid, gids, debugFlags, mountExternal,            app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,            app.info.dataDir, entryPointArgs);    synchronized (mPidsSelfLocked) {        //pid放到map,存起来,AMS要这些信息        this.mPidsSelfLocked.put(startResult.pid, app);        if (isActivityProcess) {            //超时检测            Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);            msg.obj = app;            mHandler.sendMessageDelayed(msg, startResult.usingWrapper                    ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);        }    }} }
  7. 调用startViaZygote()函数;

     /* processClass:android.app.ActivityThread niceName:com.example.lession1 */ public static final ProcessStartResult start(final String processClass,                          final String niceName,                          int uid, int gid, int[] gids,                          int debugFlags, int mountExternal,                          int targetSdkVersion,                          String seInfo,                          String abi,                          String instructionSet,                          String appDataDir,                          String[] zygoteArgs) {try {//再套一层    return startViaZygote(processClass, niceName, uid, gid, gids,            debugFlags, mountExternal, targetSdkVersion, seInfo,            abi, instructionSet, appDataDir, zygoteArgs);} catch (ZygoteStartFailedEx ex) {    Log.e(LOG_TAG,            "Starting VM process through Zygote failed");    throw new RuntimeException(            "Starting VM process through Zygote failed", ex);}}
  8. 再封装一层

     private static ProcessStartResult startViaZygote(final String processClass,                          final String niceName,                          final int uid, final int gid,                          final int[] gids,                          int debugFlags, int mountExternal,                          int targetSdkVersion,                          String seInfo,                          String abi,                          String instructionSet,                          String appDataDir,                          String[] extraArgs)                          throws ZygoteStartFailedEx {    //再套一层    return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);}}
  9. 这里通过localsockett,通知zygote创建一个进程;

     private static ProcessStartResult zygoteSendArgsAndGetResult(ZygoteState zygoteState, ArrayList<String> args)throws ZygoteStartFailedEx {try {    final BufferedWriter writer = zygoteState.writer;    final DataInputStream inputStream = zygoteState.inputStream;    writer.write(Integer.toString(args.size()));    writer.newLine();    int sz = args.size();    for (int i = 0; i < sz; i++) {        String arg = args.get(i);        if (arg.indexOf('\n') >= 0) {            throw new ZygoteStartFailedEx(                    "embedded newlines not allowed");        }        writer.write(arg);        writer.newLine();    }    writer.flush();    ProcessStartResult result = new ProcessStartResult();    result.pid = inputStream.readInt();    if (result.pid < 0) {        throw new ZygoteStartFailedEx("fork() failed");    }    result.usingWrapper = inputStream.readBoolean();    return result;} catch (IOException ex) {    zygoteState.close();    throw new ZygoteStartFailedEx(ex);}}

思考,这里为什么要通过zygote创建进程?

Application启动

进程创建完成后,会调用ActivityThread.main()函数。这个对象是在创建进程时,传递的参数,大家可以回过头看创建进程时传入的参数。

  1. 一切还是从main函数开始。首先创建了一个ActivityThread对象。然后调用了attach()方法。注意这里传入的参数是false;

     public static void main(String[] args) {SamplingProfilerIntegration.start();...Process.setArgV0("<pre-initialized>");//开始为Android程序员创建一个UI线程后,从此以后再也逃不出这个looperLooper.prepareMainLooper();//创建一个自己;ActivityThread thread = new ActivityThread();//告诉system_process;thread.attach(false);if (sMainThreadHandler == null) {    sMainThreadHandler = thread.getHandler();}AsyncTask.init();if (false) {    Looper.myLooper().setMessageLogging(new            LogPrinter(Log.DEBUG, "ActivityThread"));}Looper.loop();throw new RuntimeException("Main thread loop unexpectedly exited");}
  2. 首先告诉ActivityManagerService我已经创建好了,起来了一个新应用。上面说了这里走上面逻辑;

     private void attach(boolean system) {    sCurrentActivityThread = this;        mSystemThread = system;        if (!system) {        ...    RuntimeInit.setApplicationObject(mAppThread.asBinder());    //告诉system_process我已经好了    final IActivityManager mgr = ActivityManagerNative.getDefault();    try {        mgr.attachApplication(mAppThread);    } catch (RemoteException ex) {        // Ignore    }} else {    //下面是系统的,App滚    // 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 = ContextImpl.createAppContext(                this, getSystemContext().mPackageInfo);        mInitialApplication = context.mPackageInfo.makeApplication(true, null);        mInitialApplication.onCreate();    } catch (Exception e) {        throw new RuntimeException(                "Unable to instantiate Application():" + e.toString(), e);    }} ...}
  3. AMS接到应用被创建后,调用attachApplicationLocked()方法;

     public final void attachApplication(IApplicationThread thread) {synchronized (this) {    int callingPid = Binder.getCallingPid();    final long origId = Binder.clearCallingIdentity();    attachApplicationLocked(thread, callingPid);    Binder.restoreCallingIdentity(origId);}}
  4. 这里先检查一下是否合法;加载应用dex文件,找到Application实例,初始化;

     private final boolean attachApplicationLocked(IApplicationThread thread,    int pid) {获取我们创建appProcessRecord app;if (pid != MY_PID && pid >= 0) {    synchronized (mPidsSelfLocked) {        app = mPidsSelfLocked.get(pid);    }} else {    app = null;}//没有的话,就把当前进程杀了if (app == null) {    if (pid > 0 && pid != MY_PID) {        Process.killProcessQuiet(pid);    } else {        try {            thread.scheduleExit();        } catch (Exception e) {            // Ignore exceptions.        }    }    return false;}try {    ...    //dexopt 不讲    ensurePackageDexOpt(app.instrumentationInfo != null            ? app.instrumentationInfo.packageName            : app.info.packageName);    ....    //这里再次回到ActivityThread进程    thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,            profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,            app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,            isRestrictedBackupMode || !normalMode, app.persistent,            new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),            mCoreSettingsObserver.getCoreSettingsLocked());}....//启动Acitivityif (mStackSupervisor.attachApplicationLocked(app)) {//启动servicedidSomething |= mServices.attachApplicationLocked(app, processName);//注册broadcastdidSomething |= sendPendingBroadcastsLocked(app);....return true;}
  5. 调用 IApplicationThread.bindApplication(),再到应用的UI线程;

     public final void bindApplication(String processName, ApplicationInfo appInfo,        List<ProviderInfo> providers, ComponentName instrumentationName,        ProfilerInfo profilerInfo, Bundle instrumentationArgs,        IInstrumentationWatcher instrumentationWatcher,        IUiAutomationConnection instrumentationUiConnection, int debugMode,        boolean enableOpenGlTrace, boolean isRestrictedBackupMode, boolean persistent,        Configuration config, CompatibilityInfo compatInfo, Map<String, IBinder> services,        Bundle coreSettings) {    ...        //异步到UI线程里    sendMessage(H.BIND_APPLICATION, data);}
  6. 回到AcitvityThread.bindApplication()方法,创建Application,调用application.oncreate()方法。这里就是Android程序看到App.oncreate()回调函数了,

     private void handleBindApplication(AppBindData data) {mBoundApplication = data;...//终于看到神奇的Contextfinal ContextImpl appContext = ContextImpl.createAppContext(this, data.info);        if (data.appInfo.targetSdkVersion > 9) {    StrictMode.enableDeathOnNetwork();}if (data.instrumentationName != null) {...    LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,            appContext.getClassLoader(), false, true, false);    ContextImpl instrContext = ContextImpl.createAppContext(this, pi);    //创建了监控类    try {        java.lang.ClassLoader cl = instrContext.getClassLoader();        mInstrumentation = (Instrumentation)            cl.loadClass(data.instrumentationName.getClassName()).newInstance();    } catch (Exception e) {    }    //init    mInstrumentation.init(this, instrContext, appContext,           new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher,           data.instrumentationUiAutomationConnection);} else {    mInstrumentation = new Instrumentation();}try {    //获取Application    Application app = data.info.makeApplication(data.restrictedBackupMode, null);    mInitialApplication = app;    ...    try {        mInstrumentation.onCreate(data.instrumentationArgs);    }    catch (Exception e) {        throw new RuntimeException(            "Exception thrown in onCreate() of "            + data.instrumentationName + ": " + e.toString(), e);    }    //app.oncreate();    try {        mInstrumentation.callApplicationOnCreate(app);    } catch (Exception e) {        if (!mInstrumentation.onException(app, e)) {            throw new RuntimeException(                "Unable to create application " + app.getClass().getName()                + ": " + e.toString(), e);        }    }} finally {    StrictMode.setThreadPolicy(savedPolicy);}

    }

  7. 至此Application已经创建完成;app.oncreate()被调用;

     public void callApplicationOnCreate(Application app) {app.onCreate(); }

Activity创建和启动

  1. 回去我们接着看Activity创建和启动,application创建之后,调用了attachApplicationLocked方法;

     boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {final String processName = app.processName;boolean didSomething = false;for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {    ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;    for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {        ActivityRecord hr = stack.topRunningActivityLocked(null);                 if (hr != null) {            if (hr.app == null && app.uid == hr.info.applicationInfo.uid                    && processName.equals(hr.processName)) {               ...                    if (realStartActivityLocked(hr, app, true, true)) {                        didSomething = true;                    }                ...            }        }       }}return didSomething; }
  2. 这里调用自己的realStartActivityLocked方法,这里调用了app进程的ActivityThread的scheduleLaunchActivity

     final boolean realStartActivityLocked(ActivityRecord r,    ProcessRecord app, boolean andResume, boolean checkConfig)    throws RemoteException {    ...    final ActivityStack stack = r.task.stack;try {    ...    app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,            System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),            r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,            results, newIntents, !andResume, mService.isNextTransitionForward(),            profilerInfo);    ....} catch (RemoteException e) { } ...}
  3. 终于要启动了,异步到用户进程里,到UI线程中启动。handleLaunchActivity(r, null);

     public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,        ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,        IVoiceInteractor voiceInteractor, int procState, Bundle state,        PersistableBundle persistentState, List<ResultInfo> pendingResults,        List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,        ProfilerInfo profilerInfo) {    updateProcessState(procState, false);    ActivityClientRecord r = new ActivityClientRecord();    ...    异步到UI线程里    sendMessage(H.LAUNCH_ACTIVITY, r);}
  4. 在UT线程中执行performLaunchActivity方法

     private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {....Activity a = performLaunchActivity(r, customIntent);....if (a != null) {    handleResumeActivity(r.token, false, r.isForward,            !r.activity.mFinished && !r.startsNotResumed);}}
  5. performLaunchActivity方法中通过mInstrumentation.newActivity创建实例

     private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {....Activity activity = null;try {    java.lang.ClassLoader cl = r.packageInfo.getClassLoader();    //创建了Activity实例了    activity = mInstrumentation.newActivity(            cl, component.getClassName(), r.intent);            ...   } catch (Exception e) {}try {    Application app = r.packageInfo.makeApplication(false, mInstrumentation);    if (activity != null) {        ....        if (r.isPersistable()) {            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);        } else {            mInstrumentation.callActivityOnCreate(activity, r.state);        }    }    r.paused = true;    mActivities.put(r.token, r);} return activity;}
  6. 实例创建完成了,就是要调用onCreate方法了

     public void callActivityOnCreate(Activity activity, Bundle icicle) {prePerformCreate(activity);activity.performCreate(icicle);postPerformCreate(activity);}
  7. 这里终于到了Activity.onCreate方法。至此进程创建,Appliccation.onCreate(),Activity.onCreate都已经完成;

     final void performCreate(Bundle icicle) {onCreate(icicle);mActivityTransitionState.readState(icicle);performCreateCommon();

    }

0 0
原创粉丝点击