App启动流程分析(下)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014079662/article/details/79772502

我们知道Java中一个能够独立运行的java程序的方法入口是main方法,它是被Jvm识别调用的。而在Android中一个应用的开始也可说是从ActivityThread的main方法开始的,然而不同的是他不是由Jvm调用的。

上一节我们讲到在ZygoteInit中通过抛出MethodAndArgsCaller异常,然后在main方法中,通过捕获异常,然后调用run方法,然后在run方法中通过invoke来反射调用到ActivityThread中的main方法。详见App启动流程分析(上)

public static void main(String[] args) {
        SamplingProfilerIntegration.start();

        CloseGuard.setEnabled(false);
        //设置进程参数
        Process.setArgV0("<pre-initialized>");
        //创建主线程Looper
        Looper.prepareMainLooper();
        if (sMainThreadHandler == null) {
          //创建主线程Handler
            sMainThreadHandler = new Handler();
        }
        //创建ActivityThread对象
        ActivityThread thread = new ActivityThread();
        //关键的一步,详见1.1小节。false表示创建的是普通应用的进程。true表示创建的是系统应用程序的进程。
        thread.attach(false);

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        //开起主线程Looper循环。
        Looper.loop();
        //执行到这里说明退出了主线程Looper循环。抛出异常。
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

LAUNCH_ACTIVITY

1.1 ActivityThread.attach

private void attach(boolean system) {
 //将ActivityThread对象放入ThreadLocal中保存。ThreadLocal可以保证每个线程中数据独立。
    sThreadLocal.set(this);
    mSystemThread = system;
  //普通app进入这个if中。
    if (!system) {
        ViewRootImpl.addFirstDrawHandler(new Runnable() {
            public void run() {
                ensureJitEnabled();
            }
        });
        android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
      //将ApplicationThread对象传递给RuntimeInit保存,setApplicationObject是一个静态方法,且RuntimeInit中方法多为静态方法。见1.1.1与1.1.2小节
        RuntimeInit.setApplicationObject(mAppThread.asBinder());
      //获得了ActivityManagerService的本地代理对象ActivityManagerProxy,见1.1.3小节
        IActivityManager mgr = ActivityManagerNative.getDefault();
        try {
            //实际上调用了ActivityManagerProxy的attachApplication方法,见1.2小节
            mgr.attachApplication(mAppThread);
        } catch (RemoteException ex) {
            // Ignore
        }
    } else {
      //系统app会进入else
        android.ddm.DdmHandleAppName.setAppName("system_process");
        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);
        }
    }
    ...
}

对于Binder了解较深的就会发现,这里的ApplicationThread有点类似于ActivityMangerServiceActivityMangerService继承自ActivityManagerNativeActivityManagerNative继承自BinderActivityManagerNativeActivityMangerProxy均实现了IApplicationThread这个接口。而ActivityMangerProxy就是AMS在客户端的代理对象。

这里的ApplicationThread继承自ApplicationThreadNativeApplicationThreadNative继承了Binder

ApplicationThreadNativeApplicationThreadProxy均实现了IApplicationThread接口,典型的是Binder的客户端代理。

可以推测出,AMS作为系统的服务,运行在SystemServer进程。当app调用AMS中的方法时,需要获得AMS的本地代理对象ActivityManagerProxy,AMS与AMP均继承自同一个接口。客户端调用AMP中的方法,通过Binder驱动即可传递数据,跨进程调用到AMS中的方法。

那么当AMS要调用app中的方法时呢? ApplicationThreadApplicationThreadProxy均实现了IApplicationThread接口,在这里通过mgr.attachApplication()方法(mgr就是AMS在本地的代理对象ActivityManagerProxy),将ApplicationThread传递给了AMS保存。

1.1.1 RuntimeInit.setApplicationObject
    public static final void setApplicationObject(IBinder app) {
        mApplicationObject = app;
    }
1.1.2 mAppThread.asBinder
//mAppThread是ApplicationThread的实例对象。ApplicationThread继承自ApplicationThreadNative。而ApplicationThreadNative是一个Binder。
public final class ActivityThread {
    ...
    final ApplicationThread mAppThread = new ApplicationThread();
    ...
}
public abstract class ApplicationThreadNative extends Binder implements IApplicationThread {
    ...
    public IBinder asBinder(){
         return this;
    }
    ...
}
1.1.3 ActivityManagerNative.getDefault
 //熟悉AIDL的就会发现,这里的ActivityManagerNative就相当于常规下,我们AIDL创建后自动生成的Stub类,而ActivityManagerProxy类就相当于AIDL创建之后的Proxy内部代理类,当客户端和服务端在同一进程时,调用时直接调用服务端的方法,不需要走Proxy中的方法。而当客户端和服务端不在同一进程时,客户端调用方法时,先调用了Proxy中的方法,再走transact过程调用服务端的方法。
static public IActivityManager getDefault() {
        return gDefault.get();
    }
//gDefault是一个泛型为IActivityManager的Singleton类型变量。实际上是一种单例模式的快速实现。
public abstract class Singleton<T> {
    private T mInstance;

    protected abstract T create();
    //调用了这个get方法,当T不存在,也就是IActivityManager不存在时,调用create方法来创建这个变量。
    public final T get() {
        synchronized (this) {
            if (mInstance == null) {
                mInstance = create();
            }
            return mInstance;
        }
    }
}

 private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
        protected IActivityManager create() {
          //通过serviceManger获得了AMS的Binder,获得的是BinderProxy这个实例,其中保存了AMS在Native层BpBinder的Handle。(关于BpBinder和BBinder可以去看binder方面源码分析),而ActivityManagerService继承自ActivityMangerNative。,具体可以看1.1.4小节
            IBinder b = ServiceManager.getService("activity");
            if (false) {
                Log.v("ActivityManager", "default service binder = " + b);
            }
          //调用ActivityManagerNative.asInterface,这个方法在客户端和服务端在同一进程时,返回ActivityManagerNative对象,否则返回的是ActivityManagerProxy这个对象。
            IActivityManager am = asInterface(b);
            if (false) {
                Log.v("ActivityManager", "default service = " + am);
            }
            //返回了ActivityManagerProxy对象。ActivityManagerService的BinderProxy就保存在了ActivityManagerProxy中的mRemote这个变量中。
            return am;
        }
    };

1.2 ActivityManagerProxy.attachApplication

ActivityManagerProxy是ActivityManagerNative的内部类

    public void attachApplication(IApplicationThread app) throws RemoteException
    {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        //这里的app是ApplicationThread对象
        data.writeStrongBinder(app.asBinder());
        //调用了mRemote的transact方法,mRemote实际上是一个BinderProxy类,它在内部调用了一个native方法transact。见1.2.1小节
        mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);
        reply.readException();
        data.recycle();
        reply.recycle();
    }
1.2.1 BinderProxy.transact

final class BinderProxy implements IBinder {
    ...
    public native boolean pingBinder();
    public native boolean isBinderAlive();
    //native的transact方法,最终会通过Binder驱动调用到ActivityManagerService中继承自ActivityManagerNative的onTransact方法。
    public native boolean transact(int code, Parcel data, Parcel reply, int flags) throws           RemoteException;
    public native void linkToDeath(DeathRecipient recipient, int flags) throws RemoteException;
    public native boolean unlinkToDeath(DeathRecipient recipient, int flags);
    ...
}
1.2.2 ActivityManagerNative.onTransact
 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
     switch (code) {
          ...
          //省略了非常多的case分支
          case ATTACH_APPLICATION_TRANSACTION: {
              data.enforceInterface(IActivityManager.descriptor);
              //见下方说明
              IApplicationThread app = ApplicationThreadNative.asInterface(
                    data.readStrongBinder());
              if (app != null) {
                  //调用了AMS中的attachApplication方法,见1.2.3小节
                  attachApplication(app);
              }
              reply.writeNoException();
              return true;
           }
           ...
       }
     return super.onTransact(code, data, reply, flags);
}
  1. 这里的app实际是一个ApplicationThreadProxy实例。
  2. readStrongBinder会返回一个IBinder对象,实际上是前面写入的ApplicationThread经过Binder驱动后在native层转为一个BpBinder,同过JNI转为一个BinderProxy对象。
  3. ApplicationThreadNative.asInterface调用之后会返回一个ApplicationThreadProxy对象,就像在App进程获得的AMS代理对象ActivityMangerProxy一样,这个ApplicationThreadProxy就是App进程中ApplicationThread的代理。
  4. 当app进程调用AMS中方法时,app进程是客户端,AMS所在的SystemServer是服务端。 此时,在AMS中保存了app端的代理对象ApplicationThreadProxy,当AMS要调用ApplicationThread中方法时,AMS就是客户端,而app进程就是服务端了。
1.2.3 ActivityManagerService.attachApplication
public final void attachApplication(IApplicationThread thread) {
        synchronized (this) {
            //获得远远程调用进程的进程id
            int callingPid = Binder.getCallingPid();
            final long origId = Binder.clearCallingIdentity();
            //见1.2.4小节
            attachApplicationLocked(thread, callingPid);
            Binder.restoreCallingIdentity(origId);
        }
}
1.2.4 ActivityManagerService.attachApplicationLocked

这段代码很长,其中部分if判断提高程序健壮性的代码,log日志代码,以及 thread.bindApplication后的一大段代码等等已被略去

//在AMS对象被创建时,这个集合就被实例化了
final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {
        //在上篇中的4.3小节中,我们成功启动一个新的进程之后,以进程的pid作为键,ProcessRecord对象作为值保存在了mPidsSelfLocked这个SparseArray集合中。
        ProcessRecord app;
        if (pid != MY_PID && pid >= 0) {
            synchronized (mPidsSelfLocked) {
                app = mPidsSelfLocked.get(pid);
            }
        } else {
            app = null;
        }

        if (app == null) {
            EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
            if (pid > 0 && pid != MY_PID) {
                Process.killProcessQuiet(pid);
            } else {
                try {
                    thread.scheduleExit();
                } catch (Exception e) {
                    // Ignore exceptions.
                }
            }
            return false;
        }


        //app.thread不为null,说明这个ProcessRecord依然绑定的有另一个进程,需要清理干净。这里的thread指的是IApplicationThread对象。实际上是ApplicationThreadProxy实例对象。
        if (app.thread != null) {
            handleAppDiedLocked(app, true, true);
        }
        //获得进程名称
        String processName = app.processName;
        try {
            //设置当app进程死亡,Binder的死亡代理
            AppDeathRecipient adr = new AppDeathRecipient(
                    app, pid, thread);
            thread.asBinder().linkToDeath(adr, 0);
            app.deathRecipient = adr;
        } catch (RemoteException e) {
            app.resetPackageList();
            startProcessLocked(app, "link fail", processName);
            return false;
        }

        EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
        //将ProcessRecord中的thread这个成员变量指向传递进来的IApplicationThread实例,即ApplicationThreadProxy。
        app.thread = thread;
        app.curAdj = app.setAdj = -100;
        app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
        app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
        app.forcingToForeground = null;
        app.foregroundServices = false;
        app.hasShownUi = false;
        app.debugging = false;

        mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);

        boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
        List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
        try {
            int testMode = IApplicationThread.DEBUG_OFF;
            ...
            String profileFile = app.instrumentationProfileFile;
            ParcelFileDescriptor profileFd = null;
            boolean profileAutoStop = false;
            if (mProfileApp != null && mProfileApp.equals(processName)) {
                mProfileProc = app;
                profileFile = mProfileFile;
                profileFd = mProfileFd;
                profileAutoStop = mAutoStopProfiler;
            }

            boolean isRestrictedBackupMode = false;

            ApplicationInfo appInfo = app.instrumentationInfo != null
                    ? app.instrumentationInfo : app.info;
            //通过thread,即ApplicationThreadProxy跨进程调用了ApplicationThread中的bindApplication方法。从这里,这里又到了app进程
            thread.bindApplication(processName, appInfo, providers,
                    app.instrumentationClass, profileFile, profileFd, profileAutoStop,
                    app.instrumentationArguments, app.instrumentationWatcher, testMode, 
                    isRestrictedBackupMode || !normalMode, app.persistent,
                    new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
                    mCoreSettingsObserver.getCoreSettingsLocked());
            updateLruProcessLocked(app, false, true);
            app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
        } catch (Exception e) {
            app.resetPackageList();
            app.unlinkDeathRecipient();
            startProcessLocked(app, "bind fail", processName);
            return false;
        }
    // See if the top visible activity is waiting to run in this process
    //启动即将要被启动的Activity
        ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
        if (hr != null && normalMode) {
            if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
                    && processName.equals(hr.processName)) {
                try {
                    //realStartActivityLocked才是真正启动Activity的方法。见2.1小节
                    if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
                        didSomething = true;
                    }
                } catch (Exception e) {
                    Slog.w(TAG, "Exception in new application when starting activity "
                          + hr.intent.getComponent().flattenToShortString(), e);
                    badApp = true;
                }
            } else {
                mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
            }
        }

        // Find any services that should be running in this process...
    //启动进程中应该被启动的Services
        if (!badApp && mPendingServices.size() > 0) {
            ServiceRecord sr = null;
            try {
                for (int i=0; i<mPendingServices.size(); i++) {
                    sr = mPendingServices.get(i);
                    if (app.info.uid != sr.appInfo.uid
                            || !processName.equals(sr.processName)) {
                        continue;
                    }

                    mPendingServices.remove(i);
                    i--;
                    realStartServiceLocked(sr, app);
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.w(TAG, "Exception in new application when starting service "
                      + sr.shortName, e);
                badApp = true;
            }
        }

        // Check if the next broadcast receiver is in this process...
    //启动进程中应该被启动的Broadcast
        BroadcastRecord br = mPendingBroadcast;
        if (!badApp && br != null && br.curApp == app) {
            try {
                mPendingBroadcast = null;
                processCurBroadcastLocked(br, app);
                didSomething = true;
            } catch (Exception e) {
                Slog.w(TAG, "Exception in new application when starting receiver "
                      + br.curComponent.flattenToShortString(), e);
                badApp = true;
                logBroadcastReceiverDiscardLocked(br);
                finishReceiverLocked(br.receiver, br.resultCode, br.resultData,
                        br.resultExtras, br.resultAbort, true);
                scheduleBroadcastsLocked();
                // We need to reset the state if we fails to start the receiver.
                br.state = BroadcastRecord.IDLE;
            }
        }
        ...
        return true;
    }

这里主要是通过pid获得了app进程保存在AMS中的ProcessRecord对象。设置了ApplicationThread这个Binder的死亡代理,通过ProcessRecord获得了许多调用bindApplication的必要参数。然后通过Binder跨进程调用了ApplicationThread中的bindApplication方法。

1.3 ApplicationThread.bindApplication

public final void bindApplication(String processName,
                ApplicationInfo appInfo, List<ProviderInfo> providers,
                ComponentName instrumentationName, String profileFile,
                ParcelFileDescriptor profileFd, boolean autoStopProfiler,
                Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
                int debugMode, boolean isRestrictedBackupMode, boolean persistent,
                Configuration config, CompatibilityInfo compatInfo,
                Map<String, IBinder> services, Bundle coreSettings) {
            //这个services是一个HashMap,其中保存了WindowManagerService,PackageManagersService,AlarmMangerService的Ibinder,见1.3.1小节
            if (services != null) {
                // Setup the service cache in the ServiceManager
                ServiceManager.initServiceCache(services);
            }
            //一些设置参数,coreSettings是一个Bundle对象,最终通过H Handler发送消息,调用了ActivityThread.handleSetCoreSettings。 见1.3.2小节
            setCoreSettings(coreSettings);
            //创建一个dataBean,将数据打包成一个Bean
            AppBindData data = new AppBindData();
            data.processName = processName;
            data.appInfo = appInfo;
            data.providers = providers;
            data.instrumentationName = instrumentationName;
            data.instrumentationArgs = instrumentationArgs;
            data.instrumentationWatcher = instrumentationWatcher;
            data.debugMode = debugMode;
            data.restrictedBackupMode = isRestrictedBackupMode;
            data.persistent = persistent;
            data.config = config;
            data.compatInfo = compatInfo;
            data.initProfileFile = profileFile;
            data.initProfileFd = profileFd;
            data.initAutoStopProfiler = false;
            //见1.3.3小节
            queueOrSendMessage(H.BIND_APPLICATION, data);
        }
1.3.1 ActivityMangaerService.getCommonServicesLocked

services是在AMS中作为参数传入的,查看AMS中原方法,实际上直接调用了getCommonServicesLocked方法,将返回值作为参数传入,所以我们直接看getCommonServicesLocked这个方法。

    private HashMap<String, IBinder> getCommonServicesLocked() {
        //mAppBindArgs是一个HashMap,作为AMS中的一个成员变量
        if (mAppBindArgs == null) {
            mAppBindArgs = new HashMap<String, IBinder>();
            //获得并保存PackageManagerService的IBInder
            mAppBindArgs.put("package", ServiceManager.getService("package"));
            //获得并保存WindowMangerService的IBInder
            mAppBindArgs.put("window", ServiceManager.getService("window"));
            //获得并保存AlarmMangerService的IBInder
            mAppBindArgs.put(Context.ALARM_SERVICE,
                    ServiceManager.getService(Context.ALARM_SERVICE));
        }
        return mAppBindArgs;
    }
1.3.2 ActivityThread.handleSetCoreSettings
    private void handleSetCoreSettings(Bundle coreSettings) {synchronized (mPackages) {
        //即,最后将其保存在了ActivityThread中的mCoreSettings。
            mCoreSettings = coreSettings;
        }
    }
1.3.3 ApplicationThread.queueOrSendMessage(H.BIND_APPLICATION, data);
    private void queueOrSendMessage(int what, Object obj) {
        queueOrSendMessage(what, obj, 0, 0);
    }
    //最终,将其包装为一个message。发送给了mH这个Handler。跳到了1.3.4小节
    private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
        synchronized (this) {
            if (DEBUG_MESSAGES) Slog.v(
                TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
                + ": " + arg1 + " / " + obj);
            Message msg = Message.obtain();
            msg.what = what;
            msg.obj = obj;
            msg.arg1 = arg1;
            msg.arg2 = arg2;
            mH.sendMessage(msg);
        }
    }

mH这个Handler在AcitivityThread被实例话时,直接作为成员变量被实例化了。

1.3.4 H Handler
private class H extends Handler {
        public static final int LAUNCH_ACTIVITY         = 100;
        public static final int PAUSE_ACTIVITY          = 101;
        public static final int PAUSE_ACTIVITY_FINISHING= 102;
        public static final int STOP_ACTIVITY_SHOW      = 103;
        public static final int STOP_ACTIVITY_HIDE      = 104;
        public static final int SHOW_WINDOW             = 105;
        public static final int HIDE_WINDOW             = 106;
        public static final int RESUME_ACTIVITY         = 107;
        public static final int SEND_RESULT             = 108;
        public static final int DESTROY_ACTIVITY        = 109;
        public static final int BIND_APPLICATION        = 110;
        public static final int EXIT_APPLICATION        = 111;
        public static final int NEW_INTENT              = 112;
        public static final int RECEIVER                = 113;
        public static final int CREATE_SERVICE          = 114;
        public static final int SERVICE_ARGS            = 115;
        public static final int STOP_SERVICE            = 116;
        public static final int REQUEST_THUMBNAIL       = 117;
        public static final int CONFIGURATION_CHANGED   = 118;
        public static final int CLEAN_UP_CONTEXT        = 119;
        public static final int GC_WHEN_IDLE            = 120;
        public static final int BIND_SERVICE            = 121;
        public static final int UNBIND_SERVICE          = 122;
        public static final int DUMP_SERVICE            = 123;
        public static final int LOW_MEMORY              = 124;
        public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
        public static final int RELAUNCH_ACTIVITY       = 126;
        public static final int PROFILER_CONTROL        = 127;
        public static final int CREATE_BACKUP_AGENT     = 128;
        public static final int DESTROY_BACKUP_AGENT    = 129;
        public static final int SUICIDE                 = 130;
        public static final int REMOVE_PROVIDER         = 131;
        public static final int ENABLE_JIT              = 132;
        public static final int DISPATCH_PACKAGE_BROADCAST = 133;
        public static final int SCHEDULE_CRASH          = 134;
        public static final int DUMP_HEAP               = 135;
        public static final int DUMP_ACTIVITY           = 136;
        public static final int SLEEPING                = 137;
        public static final int SET_CORE_SETTINGS       = 138;
        public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
        public static final int TRIM_MEMORY             = 140;
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
            switch (msg.what) {
                    ...
                    //1.3.3发送的消息会进入这个case
                    case BIND_APPLICATION:
                    AppBindData data = (AppBindData)msg.obj;
                    //调用了ActivityThread的handleBindApplication方法。见1.3.5小节
                    handleBindApplication(data);
                    break;
                    ...
            }
        }
        ...
}

H Handler是ActivityThread的一个内部类,其中我们可以看到定义了非常多的状态量,常见的SHOW_WINDOW,CREATE_SERVICE,NEW_INTENT,LAUNCH_ACTIVITY,PAUSE_ACTIVITY,RECEIVER,BIND_SERVICE等等都是android中非常常见的一些操作。 由此可见H Handler是非常重要的一个类,在Window,Activity,Service,Intent,Receiver等等的许多操作中都会用到它来发送消息。

1.3.5 ActivityThread.handleBindApplication

这又是一个长到爆炸的方法,我们依然是省略部分代码,只留下整体中最重要的调用代码

    private void handleBindApplication(AppBindData data) {
        //现将打包的data保存起来,接下来一大段都是获得data中对应的数据,将其赋值给对应的一些变量。
        mBoundApplication = data;
        mConfiguration = new Configuration(data.config);
        mCompatConfiguration = new Configuration(data.config);

        mProfiler = new Profiler();
        mProfiler.profileFile = data.initProfileFile;
        mProfiler.profileFd = data.initProfileFd;
        mProfiler.autoStopProfiler = data.initAutoStopProfiler;

        Process.setArgV0(data.processName);
        android.ddm.DdmHandleAppName.setAppName(data.processName);

        if (data.persistent) {
            Display display = WindowManagerImpl.getDefault().getDefaultDisplay();
            if (!ActivityManager.isHighEndGfx(display)) {
                HardwareRenderer.disable(false);
            }
        }

        if (mProfiler.profileFd != null) {
            mProfiler.startProfiling();
        }

        //当app版本小于等于12时,设置AsyncTask的默认线程池
        if (data.appInfo.targetSdkVersion <= 12) {
            AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
        //默认时区设置
        TimeZone.setDefault(null);

        Locale.setDefault(data.config.locale);

        ...
        if (data.instrumentationName != null) {
            //创建ContextImpl,我们知道,在android中,Context是一个抽象类,它的具体实现类就是ContextImpl。而像Application,Service类均继承自COntextWapper。而ContextWapper虽然也继承自Context,但它只是ContextImpl的一个包装类,它里面很多具体的处理都是直接丢给了ContextImpl。
            ContextImpl appContext = new ContextImpl();
            appContext.init(data.info, null, this);
            InstrumentationInfo ii = null;

            try {
                ii = appContext.getPackageManager().
                    getInstrumentationInfo(data.instrumentationName, 0);
            } catch (PackageManager.NameNotFoundException e) {
            }
            if (ii == null) {
                throw new RuntimeException(
                    "Unable to find instrumentation info for: "
                    + data.instrumentationName);
            }

            mInstrumentationAppDir = ii.sourceDir;
            mInstrumentationAppPackage = ii.packageName;
            mInstrumentedAppDir = data.info.getAppDir();

            ApplicationInfo instrApp = new ApplicationInfo();
            instrApp.packageName = ii.packageName;
            instrApp.sourceDir = ii.sourceDir;
            instrApp.publicSourceDir = ii.publicSourceDir;
            instrApp.dataDir = ii.dataDir;

            instrApp.nativeLibraryDir = ii.nativeLibraryDir;
            LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
                    appContext.getClassLoader(), false, true);

            ContextImpl instrContext = new ContextImpl();
            instrContext.init(pi, null, this);
            //创建ClassLoader,创建Instrumentation实例
            try {
                java.lang.ClassLoader cl = instrContext.getClassLoader();
                mInstrumentation = (Instrumentation)
                    cl.loadClass(data.instrumentationName.getClassName()).newInstance();
            } catch (Exception e) {
                throw new RuntimeException(
                    "Unable to instantiate instrumentation "
                    + data.instrumentationName + ": " + e.toString(), e);
            }

            mInstrumentation.init(this, instrContext, appContext,
                    new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);

            if (mProfiler.profileFile != null && !ii.handleProfiling
                    && mProfiler.profileFd == null) {
                mProfiler.handlingProfiling = true;
                File file = new File(mProfiler.profileFile);
                file.getParentFile().mkdirs();
                Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
            }

            try {
                mInstrumentation.onCreate(data.instrumentationArgs);
            }
            catch (Exception e) {
                throw new RuntimeException(
                    "Exception thrown in onCreate() of "
                    + data.instrumentationName + ": " + e.toString(), e);
            }

        } else {
            mInstrumentation = new Instrumentation();
        }

        if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
            dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
        }

        //创建Application实例,见1.3.6小节
        Application app = data.info.makeApplication(data.restrictedBackupMode, null);
        mInitialApplication = app;

        if (!data.restrictedBackupMode){ 
            List<ProviderInfo> providers = data.providers;
            if (providers != null) {
                //创建本进程的ContentProvider,并启动ContentProvider,见1.3.7小节
                installContentProviders(app, providers);
                // For process that contains content providers, we want to
                // ensure that the JIT is enabled "at some point".
                mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
            }
        }
        //调用了application的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);
            }
        }
    }

主要做了一下几件事:

  1. 解包AMS传过来的数据。
  2. 创建Instrumentation实例对象。
  3. 创建Application实例对象。
  4. 创建所在进程的ContentProvider实例对象,并调用它的onCreate方法
  5. 调用了Application的onCreate方法。
1.3.6 Loaded.makeApplication
public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
    //存在Application就直接返回
        if (mApplication != null) {
            return mApplication;
        }

        Application app = null;
        //Application的包名,如果不存在就使用默认包名路径
        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }

        try {
            java.lang.ClassLoader cl = getClassLoader();
            //创建ApplicationContext中的ContextImpl对象
            ContextImpl appContext = new ContextImpl();
            appContext.init(this, null, mActivityThread);
            //创建了Application对象。最终通过包名路径,clazz.newInstance()的方式获得Application对象,并将appContext绑定到Application中。(Application继承自ContextWapper)
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {
            if (!mActivityThread.mInstrumentation.onException(app, e)) {
                throw new RuntimeException(
                    "Unable to instantiate application " + appClass
                    + ": " + e.toString(), e);
            }
        }
        mActivityThread.mAllApplications.add(app);
        mApplication = app;

    //instrumentation不为null的情况下,调用Application的onCreate方法,但在前面传入时,传的值就是null,所以这里不会调用onCreate
        if (instrumentation != null) {
            try {
                instrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                if (!instrumentation.onException(app, e)) {
                    throw new RuntimeException(
                        "Unable to create application " + app.getClass().getName()
                        + ": " + e.toString(), e);
                }
            }
        }

        return app;
    }
1.3.7 ActivityThread.installContentProviders
private void installContentProviders(Context context, List<ProviderInfo> providers) {
        final ArrayList<IActivityManager.ContentProviderHolder> results =
            new ArrayList<IActivityManager.ContentProviderHolder>();

        Iterator<ProviderInfo> i = providers.iterator();
        while (i.hasNext()) {
            ProviderInfo cpi = i.next();
            StringBuilder buf = new StringBuilder(128);
            buf.append("Pub ");
            buf.append(cpi.authority);
            buf.append(": ");
            buf.append(cpi.name);
            Log.i(TAG, buf.toString());
            //通过ClassLoder创建ContentProvider对象并调用了ContentProvider的onCreate方法
            IContentProvider cp = installProvider(context, null, cpi,
                    false /*noisy*/, true /*noReleaseNeeded*/);
            if (cp != null) {
                IActivityManager.ContentProviderHolder cph =
                        new IActivityManager.ContentProviderHolder(cpi);
                cph.provider = cp;
                cph.noReleaseNeeded = true;
                results.add(cph);
            }
        }
        //将ContentProvider的Binder 保存到AMS中,方便其他进程调用。
        try {
            ActivityManagerNative.getDefault().publishContentProviders(
                getApplicationThread(), results);
        } catch (RemoteException ex) {
        }
    }

2.1 ActivityStack.realStartActivityLocked

    final boolean realStartActivityLocked(ActivityRecord r,
            ProcessRecord app, boolean andResume, boolean checkConfig)
            throws RemoteException {
        ...

        try {
           ...
            //启动Activity。这里的thread从1.2.4小节可以知道是ApplicationThreadProxy实例,它实际上是一个IBinder对象,最终通过Bind而跨进程调用了ApplicationThread中的对应方法,见2.2.1小节
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info,
                    new Configuration(mService.mConfiguration),
                    r.compat, r.icicle, results, newIntents, !andResume,
                    mService.isNextTransitionForward(), profileFile, profileFd,
                    profileAutoStop);
          ...
            }

        } catch (RemoteException e) {
            if (r.launchFailed) {
                Slog.e(TAG, "Second failure launching "
                      + r.intent.getComponent().flattenToShortString()
                      + ", giving up", e);
                mService.appDiedLocked(app, app.pid, app.thread);
                requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
                        "2nd-crash");
                return false;
            }

            app.activities.remove(r);
            throw e;
        }
        ...
        return true;
    }

整段代码中最重要的就是调用了 app.thread.scheduleLaunchActivity这个方法。实际上,普通的启动Activity流程最后也会调用到realStartActivityLocked这个方法。

2.2.1 ApplicationThread.scheduleLaunchActivity
 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
                Bundle state, List<ResultInfo> pendingResults,
                List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
                String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
     //将跨进程传递的数据封装到一个ActivityClientRecord,类似1.3小节
      ActivityClientRecord r = new ActivityClientRecord();

      r.token = token;
      r.ident = ident;
      r.intent = intent;
      r.activityInfo = info;
      r.compatInfo = compatInfo;
      r.state = state;

      r.pendingResults = pendingResults;
      r.pendingIntents = pendingNewIntents;

      r.startsNotResumed = notResumed;
      r.isForward = isForward;

      r.profileFile = profileName;
      r.profileFd = profileFd;
      r.autoStopProfiler = autoStopProfiler;

      updatePendingConfiguration(curConfig);
    //通过H Handler发送消息
      queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
}

最终,在H Handler中调用了handleLaunchActivity方法。

public void handleMessage(Message msg) {
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    ActivityClientRecord r = (ActivityClientRecord)msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    //见2.3小节
                    handleLaunchActivity(r, null);
                } break;
                ...
            }
}

2.3 ActivityThread.handleLaunchActivity

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

        //确保我们在最新的一个config下运行
        handleConfigurationChanged(null, null);

    //创建Activity实例,并调用了Activity的onCreate,onStart方法。见2.3.1小节
        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
            //调用了Activity的onResume方法。见2.3.4小节
            handleResumeActivity(r.token, false, r.isForward);

            if (!r.activity.mFinished && r.startsNotResumed) {
                //特殊的一些情况下,需要Activity可见但不在前台,在if中判断成功之后,在这里调用了onPause方法。
                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
            }
        }
    }

在这个方法中,通过Clazz.newInstance创建了Activity,完整的调用了Activity的onCreate,onStart,onResume方法。

2.3.1 ActivityThread.performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

        ... 
        Activity activity = null;
        try {
            //通过classloader加载器,最终通过newInstance方法创建了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 {
            //获得Aplication对象
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            //创建Activity的ContextImpl对象,并进行初始化。
            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);
                //在attach方法中将Activity传递给FragmentManger,创建了Window对象。初始化Window对象。见2.3.2小节
                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;
                //获取app的theme,将其设置给Activity
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                //调用了Activity的onCreate方法,见2.3.3小节
                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;
                //调用了Activity的onStart方法,见2.3.3小节。
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
                //调用了OnRestoreInstanceState方法,即当Activity异常被销毁再重新创建时,会调用到这个方法来加载被销毁前保存的数据。
                if (!r.activity.mFinished) {
                    if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
                //调用了onPostCreate方法,这个生命周期很少见。
                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;
    }
2.3.2 Activity.attach
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) {
        //ContextImpl保存在contextWrapper中。
        attachBaseContext(context);
        //将Activity传递给FragmentManger,方便管理attach到Activity上的Fragment
        mFragments.attachActivity(this);
        //创建Window的实例。Window是一个抽象类,具体的实现类是PhoneWindow。
        mWindow = PolicyManager.makeNewWindow(this);
        //Activity实现了Window的callback接口类。当Window接收到外界状态的改变时就会回调Activity的方法。常见的我们熟悉的例如:onAttachedToWindow,dispatchTouchEvent等等
        mWindow.setCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            mWindow.setSoftInputMode(info.softInputMode);
        }
        if (info.uiOptions != 0) {
            mWindow.setUiOptions(info.uiOptions);
        }
        //一大堆Activity中的变量进行了赋值
        mUiThread = Thread.currentThread();

        mMainThread = aThread;
        mInstrumentation = instr;
        mToken = token;
        mIdent = ident;
        mApplication = application;
        mIntent = intent;
        mComponent = intent.getComponent();
        mActivityInfo = info;
        mTitle = title;
        mParent = parent;
        mEmbeddedID = id;
        mLastNonConfigurationInstances = lastNonConfigurationInstances;

        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;
    }
2.3.3 Activity中的onCreate,onStart
public void callActivityOnCreate(Activity activity, Bundle icicle) {
        if (mWaitingActivities != null) {
            synchronized (mSync) {
                final int N = mWaitingActivities.size();
                for (int i=0; i<N; i++) {
                    final ActivityWaiter aw = mWaitingActivities.get(i);
                    final Intent intent = aw.intent;
                    if (intent.filterEquals(activity.getIntent())) {
                        aw.activity = activity;
                        mMessageQueue.addIdleHandler(new ActivityGoing(aw));
                    }
                }
            }
        }
        //调用了onCrate方法。
        activity.performCreate(icicle);

        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());
                }
            }
        }
    }
//调用了onCreate方法。
final void performCreate(Bundle icicle) {
        onCreate(icicle);
        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated();
}

final void performStart() {
        mFragments.noteStateNotSaved();
        mCalled = false;
        mFragments.execPendingActions();
    //最终调用了onStart方法。
        mInstrumentation.callActivityOnStart(this);
        if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onStart()");
        }
    //调用了Fragment的onStart方法
        mFragments.dispatchStart();
        if (mAllLoaderManagers != null) {
            for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
                LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
                lm.finishRetain();
                lm.doReportStart();
            }
        }
    }

至此,点击Launcher上一个app图标,到启动一个新的app进程,创建app的Window,Activity,再到Activity的三大生命周期全部结束,app的启动流程结束。

阅读更多

没有更多推荐了,返回首页