精华内容
下载资源
问答
  • ActivityThread源码分析

    2021-05-12 19:42:30
    Android 11 Launcher启动流程分析说过,Android App进程的入口是“android.app.ActivityThread”,那么: ActivityThread在Android App中充当一个什么样的角色? 它是怎么创建Application的?Application的生命周期...

    1、问题

    Android 11 Launcher启动流程分析说过,Android App进程的入口是“android.app.ActivityThread”,那么:

    1. ActivityThread在Android App中充当一个什么样的角色?
    2. 它是怎么创建Application的?Application的生命周期是怎样的?
    3. 第一个Activity是怎么启动的?

    2、ActivityThread#main

    Android 11 进程启动分析(一)中可以看到,Android进程创建(fork)之后都会调用入口类的main方法,这与Java语言本身的设定是一致的。所以这里我们从ActivityThread#main入手,看看它都干了些什么。

    public static void main(String[] args) {
        
        // 初始化选择性的系统拦截,这里我们不深究
        AndroidOs.install();
    
        ...
    
        Looper.prepareMainLooper();
    
        ...
    
        ActivityThread thread = new ActivityThread();
        thread.attach(/*system*/false, startSeq);
    
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
    
        ...
    
        Looper.loop();
    
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    

    这里的操作很简单,就是创建了一个ActivityThread对象并调用它的attach方法,然后进入主线程消息循环。

    3、ActivityThread#attach

    private void attach(boolean system, long startSeq) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                    UserHandle.myUserId());
            // 这里只是进行了一个赋值操作,没有额外的方法调用
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            // IActivityManager是一个AIDL接口,实现类是ActivityManagerService
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            
            // 添加监听,当使用内存超过最大可用内存3/4的时候,释放一些Activity,避免OOM
            BinderInternal.addGcWatcher(new Runnable() {
                @Override public void run() {
                    if (!mSomeActivitiesChanged) {
                        return;
                    }
                    Runtime runtime = Runtime.getRuntime();
                    long dalvikMax = runtime.maxMemory();
                    long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
                    if (dalvikUsed > ((3*dalvikMax)/4)) {
                        if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
                                + " total=" + (runtime.totalMemory()/1024)
                                + " used=" + (dalvikUsed/1024));
                        mSomeActivitiesChanged = false;
                        try {
                            ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
                        } catch (RemoteException e) {
                            throw e.rethrowFromSystemServer();
                        }
                    }
                }
            });
        } else {
            ...
        }
    
        ...
    }
    

    这里对是否是系统进程做了一个判断,我们这里是分析非系统进程,所以只看if分支。if分支做了两件事情:

    1. 调用ActivityManagerService的attachApplication方法,注册ActivityThread
    2. 添加监听,当使用内存超过最大可用内存3/4的时候,释放一些Activity,避免OOM

    这里有一个规律,一般系统的IxxxManager AIDL接口,实现类为xxxManagerService,比如IActivityManager -> ActivityManagerService,IActivityTaskManager -> ActivityTaskManagerService,IWindowManager -> WindowManagerService等等。

    这里跟进ActivityManagerService的attachApplication方法。需要注意的是这个方法传进去的mAppThread参数是一个ApplicationThread的对象,它在ActivityThread初始化的时候就new了

    final ApplicationThread mAppThread = new ApplicationThread();
    

    ApplicationThread实现了IApplicationThread AIDL接口,用于与AMS通信。

    4、ActivityManagerService#attachApplication

    public final void attachApplication(IApplicationThread thread, long startSeq) {
        if (thread == null) {
            throw new SecurityException("Invalid application interface");
        }
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }
    

    这里做了一个判空,然后调用了attachApplicationLocked方法

    private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
                int pid, int callingUid, long startSeq) {
    
        
        ProcessRecord app;
        
        if (app.isolatedEntryPoint != null) {
            // This is an isolated process which should just call an entry point instead of
            // being bound to an application.
            thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
        } else if (instr2 != null) {
            thread.bindApplication(processName, appInfo, providerList,
                    instr2.mClass,
                    profilerInfo, instr2.mArguments,
                    instr2.mWatcher,
                    instr2.mUiAutomationConnection, testMode,
                    mBinderTransactionTrackingEnabled, enableTrackAllocation,
                    isRestrictedBackupMode || !normalMode, app.isPersistent(),
                    new Configuration(app.getWindowProcessController().getConfiguration()),
                    app.compat, getCommonServicesLocked(app.isolated),
                    mCoreSettingsObserver.getCoreSettingsLocked(),
                    buildSerial, autofillOptions, contentCaptureOptions,
                    app.mDisabledCompatChanges);
        } else {
            thread.bindApplication(processName, appInfo, providerList, null, profilerInfo,
                    null, null, null, testMode,
                    mBinderTransactionTrackingEnabled, enableTrackAllocation,
                    isRestrictedBackupMode || !normalMode, app.isPersistent(),
                    new Configuration(app.getWindowProcessController().getConfiguration()),
                    app.compat, getCommonServicesLocked(app.isolated),
                    mCoreSettingsObserver.getCoreSettingsLocked(),
                    buildSerial, autofillOptions, contentCaptureOptions,
                    app.mDisabledCompatChanges);
        }
        if (profilerInfo != null) {
            profilerInfo.closeFd();
            profilerInfo = null;
        }
    
        app.makeActive(thread, mProcessStats);
    
        mProcessList.updateLruProcessLocked(app, false, null);
        
    
        boolean badApp = false;
        boolean didSomething = false;
    
        // See if the top visible activity is waiting to run in this process...
        // 处理栈顶等待运行的Activity
        didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
    
        // Find any services that should be running in this process...
        didSomething |= mServices.attachApplicationLocked(app, processName);
    
        // Check if a next-broadcast receiver is in this process...
        if (!badApp && isPendingBroadcastProcessLocked(pid)) {
            didSomething |= sendPendingBroadcastsLocked(app);
        }
    
        // Check whether the next backup agent is in this process...
        if (!badApp && backupTarget != null && backupTarget.app == app) {
            
            thread.scheduleCreateBackupAgent(backupTarget.appInfo,
                        compatibilityInfoForPackage(backupTarget.appInfo),
                        backupTarget.backupMode, backupTarget.userId);
        }
    
        ...
    
        return true;
    }
    

    这里做了一系列检查和处理之后调用了IApplicationThread对象thread的bindApplication接口,然后调用ProcessList.updateLruProcessLocked方法,让ProcessList去管理这个进程,这个在后续Android的进程管理相关文章会讲到。
    紧接着,由调用了mAtmInternal.attachApplication方法,通过注释我们可以看到,这会检查栈顶Activity是否等待运行。
    接下来是检查服务和广播,以及备份代理(BackupAgent)?

    5、ApplicationThread#bindApplication

    先看IApplicationThread#bindApplication,我们知道IApplicationThread的实现类就是ApplicationThread,ApplicationThread#bindApplication方法如下:

    public final void bindApplication(String processName, ApplicationInfo appInfo,
                    ProviderInfoList providerList, ComponentName instrumentationName,
                    ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                    IInstrumentationWatcher instrumentationWatcher,
                    IUiAutomationConnection instrumentationUiConnection, int debugMode,
                    boolean enableBinderTracking, boolean trackAllocation,
                    boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                    CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
                    String buildSerial, AutofillOptions autofillOptions,
                    ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
        ...
    
        AppBindData data = new AppBindData();
        data.processName = processName;
        data.appInfo = ...
    
        sendMessage(H.BIND_APPLICATION, data);
    }
    

    总体来说就是打包了传进来的参数,然后通过Message发给Handler处理。该Message的处理定义在ActivityThread的内部类H中:

    H.handleMessage():

    public void handleMessage(Message msg) {
        
        switch (msg.what) {
            case BIND_APPLICATION:
                AppBindData data = (AppBindData)msg.obj;
                handleBindApplication(data);
                break;
    
            case...
    }
    

    这里进而调用了ActivityThread的handleBindApplication方法。

    private void handleBindApplication(AppBindData data) {
        
        ...
    
        mInstrumentation = new Instrumentation();
        mInstrumentation.basicInit(this);
    
        Application app;
        
        ...
        
        // 实例化Application对象!
        app = data.info.makeApplication(data.restrictedBackupMode, null);
    
        ...
    
        mInitialApplication = app;
    
        ...
        
        mInstrumentation.onCreate(data.instrumentationArgs);
        
        mInstrumentation.callApplicationOnCreate(app);
        
        ...
    }
    

    这里创建了mInstrumentation和mInitialApplication成员变量。data.info是一个LoadedApk类对象,一起来看看它的makeApplication方法吧。

    LoadedApk#makeApplication():

    public Application makeApplication(boolean forceDefaultAppClass,
                Instrumentation instrumentation) {
        if (mApplication != null) {
            return mApplication;
        }
    
        Application app = null;
    
        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }
    
        
        final java.lang.ClassLoader cl = getClassLoader();
    
        ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
        
        ...
    
        app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
        appContext.setOuterContext(app);
        
        mActivityThread.mAllApplications.add(app);
        mApplication = app;
    
        ...
    
        return app;
    }
    

    这里先创建了Application的Context,然后通过ActivityThread的mInstrumentation成员变量的newApplication方法。

    Instrumentation#newApplication(java.lang.ClassLoader, java.lang.String, android.content.Context):

    public Application newApplication(ClassLoader cl, String className, Context context)
                throws InstantiationException, IllegalAccessException, 
                ClassNotFoundException {
        Application app = getFactory(context.getPackageName())
                .instantiateApplication(cl, className);
        app.attach(context);
        return app;
    }
    

    这里先获取了一个AppComponentFactory对象,然后调用它的instantiateApplication方法,然后调用了Application#attach方法。可以看到Application创建完成后,第一时间被调用的并不是它的onCreate方法。

    AppComponentFactory类的注释是

    Interface used to control the instantiation of manifest elements

    也就是说,它是专门用来实例化manifest里面定义的元素对应组件的工厂类,包括Application和四大组件。我们来看它的instantiateApplication方法:

    public @NonNull Application instantiateApplication(@NonNull ClassLoader cl,
                @NonNull String className)
                throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return (Application) cl.loadClass(className).newInstance();
    }
    

    这个很简单,无须多言。接下来我们看看Application第一个被调用的方法Application#attach(Context)

    final void attach(Context context) {
        attachBaseContext(context);
        mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
    }
    

    这里又调用了它的attachBaseContext方法,并给mLoadedApk赋值。Application本身继承自ContextWrapper,关于Context、ContextWrapper和ContextImpl可以参考这篇文章

    回到ActivityThread的handleBindApplication方法。

    private void handleBindApplication(AppBindData data) {
    
        ...
        
        // 实例化Application对象!
        app = data.info.makeApplication(data.restrictedBackupMode, null);
    
        ...
    
        mInitialApplication = app;
    
        ...
        
        mInstrumentation.onCreate(data.instrumentationArgs);
        
        // callApplicationOnCreate里调用了Application的onCreate方法
        mInstrumentation.callApplicationOnCreate(app);
        
        ...
    }
    

    Application创建完成之后,调用了attach方法,然后才是我们熟悉的onCreate方法。这是因为Context包含了Android为我们封装好的上下文环境,有了它我们才更方便地在onCreate中进行各种操作。

    至此,Application的创建和初始化就完成了。

    6、ActivityTaskManagerService.LocalService#attachApplication

    回到第4节分析ActivityManagerService#attachApplicationLocked方法的时候,看到:

    // See if the top visible activity is waiting to run in this process...
    didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
    

    这里就是启动Activity的相关代码了。mAtmInternal是ActivityTaskManagerInternal的实例,实现类为ActivityTaskManagerService.LocalService。来看看ActivityTaskManagerService.LocalService#attachApplication 都干了些什么吧

    public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
        synchronized (mGlobalLockWithoutBoost) {
            ...
            mRootWindowContainer.attachApplication(wpc);
            ...
        }
    }
    

    跟进RootWindowContainer#attachApplication()

    boolean attachApplication(WindowProcessController app) throws RemoteException {
        final String processName = app.mName;
        boolean didSomething = false;
        for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
            final DisplayContent display = getChildAt(displayNdx);
            final ActivityStack stack = display.getFocusedStack();
            if (stack == null) {
                continue;
            }
    
            mTmpRemoteException = null;
            mTmpBoolean = false; // Set to true if an activity was started.
            final PooledFunction c = PooledLambda.obtainFunction(
                    RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this,
                    PooledLambda.__(ActivityRecord.class), app, stack.topRunningActivity());
            stack.forAllActivities(c);
            c.recycle();
            if (mTmpRemoteException != null) {
                throw mTmpRemoteException;
            }
            didSomething |= mTmpBoolean;
        }
        if (!didSomething) {
            ensureActivitiesVisible(null, 0, false /* preserve_windows */);
        }
        return didSomething;
    }
    

    这里做了一个遍历,获取每个DisplayContent中活跃的任务栈,然后去启动对应的Activity。

    跟进RootWindowContainer#startActivityForAttachedApplicationIfNeeded()

    private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,
                WindowProcessController app, ActivityRecord top) {
        ...
        if (mStackSupervisor.realStartActivityLocked(r, app, top == r /*andResume*/,
                    true /*checkConfig*/)) {
            mTmpBoolean = true;
        }
        ...
    }
    

    这里我们如果是启动Launcher或者从Launcher启动App,top == r应为true,也就是andResume参数为true
    跟进StackSupervisor#realStartActivityLocked()方法

    boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
                boolean andResume, boolean checkConfig) throws RemoteException {
    
        ...
    
        // Create activity launch transaction.
        // 创建activity启动事务
        final ClientTransaction clientTransaction = ClientTransaction.obtain(
                proc.getThread(), r.appToken);
    
        final DisplayContent dc = r.getDisplay().mDisplayContent;
        clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                System.identityHashCode(r), r.info,
                // TODO: Have this take the merged configuration instead of separate global
                // and override configs.
                mergedConfiguration.getGlobalConfiguration(),
                mergedConfiguration.getOverrideConfiguration(), r.compat,
                r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
                dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
    
        // Set desired final state.
        final ActivityLifecycleItem lifecycleItem;
        if (andResume) {
            lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
        } else {
            lifecycleItem = PauseActivityItem.obtain();
        }
        clientTransaction.setLifecycleStateRequest(lifecycleItem);
    
        // Schedule transaction.
        mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    
        ...
    
        return true;
    }
    

    可以看到,这里andResume为true的情况下,事务会连续执行LaunchActivityItem和ResumeActivityItem的动作。
    LaunchActivityItem和ResumeActivityItem是都是ClientTransactionItem的子类。

    根据经验可以看出LaunchActivityItem和ResumeActivityItem等等是对操作Activity不同生命周期的封装,具体操作应该会在子类实现。这里具体操作在execute方法。

    先看LaunchActivityItem#execute:

    public void execute(ClientTransactionHandler client, IBinder token,
                PendingTransactionActions pendingActions) {
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    }
    

    方法很简单,就是调用了ClientTransactionHandler的handleLaunchActivity,而ActivityThread正是继承自ClientTransactionHandler。来看看ActivityThread#handleLaunchActivity:

    public Activity handleLaunchActivity(ActivityClientRecord r,
                PendingTransactionActions pendingActions, Intent customIntent) {
        ...
    
        final Activity a = performLaunchActivity(r, customIntent);
    
        ...
    
        return a;
    }
    

    这里核心代码也很简单,跟进

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        
        ...
        
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    
        
        if (activity != null) {
            ...
    
            // Activity resources must be initialized with the same loaders as the
            // application context.
            appContext.getResources().addLoaders(
                    app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
    
            appContext.setOuterContext(activity);
            // 没有调用onCreate前,先调用attach
            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.referrer, r.voiceInteractor, window, r.configCallback,
                    r.assistToken);
    
            ...
    
            activity.mCalled = false;
            // 执行onCreate方法
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
        }
        r.setState(ON_CREATE);
    
        // updatePendingActivityConfiguration() reads from mActivities to update
        // ActivityClientRecord which runs in a different thread. Protect modifications to
        // mActivities to avoid race.
        synchronized (mResourcesManager) {
            mActivities.put(r.token, r);
        }
    
        ...
    
        return activity;
    }
    

    可以看到,这里Activity创建之后也不是第一时间调用onCreate方法,而是先调用attach准备上下文环境。

    Instrumentation#callActivityOnCreate(android.app.Activity, android.os.Bundle):

    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }
    

    这里调用了Activty#performCreate,看看它都干了些啥:

    final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }
    
    @UnsupportedAppUsage
    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        dispatchActivityPreCreated(icicle);
        
        ...
        
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
    
        ...
    
        dispatchActivityPostCreated(icicle);
    }
    

    这里有3个关键调用,onCreate就不必多说了。来看看dispatchActivityPreCreated方法:

    private void dispatchActivityPreCreated(@Nullable Bundle savedInstanceState) {
        getApplication().dispatchActivityPreCreated(this, savedInstanceState);
        Object[] callbacks = collectActivityLifecycleCallbacks();
        if (callbacks != null) {
            for (int i = 0; i < callbacks.length; i++) {
                ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreCreated(this,
                        savedInstanceState);
            }
        }
    }
    

    这就是为什么我们可以在Application或者Activity中调用registerActivityLifecycleCallbacks方法来添加Activity声明周期的监听了。

    这里分析了Activity的创建流程,resume的流程也是类似,自行查看以下就可以了,这里不啰嗦了。

    7、ActivityThread总览

    在这里插入图片描述

    8、总结

    本文开头提出了3个问题,现在总结答案。

    1. ActivityThread在Android App中充当一个什么样的角色?
      ActivityThread是App进程的入口类,它负责主线程消息循环的创建、Application的创建、与AMS通信、调度四大组件的创建和它们的生命周期。

    2. 它是怎么创建Application的?Application的生命周期是怎样的?
      这个问题并没有完全回答,Application的创建是在AMS调度下通过ActicityThread的mInstrumentation反射创建的,在调用onCreate方法之前先调用了attach方法来初始化上下文。至于销毁和低内存等,会在后续的进程管理相关文章继续解答。

    3. 第一个Activity是怎么启动的?
      AMS在调度完Application的创建和绑定之后,检查是否有待启动的,有的化通知ActivityThread进行创建并执行相关的生命周期方法。与Application一样,先调用了attach准备上下文环境,然后才是onCreate。

    另外,需要注意的是,可以看出Application是与进程相关的,一个App如果有多个进程,那么Application也会创建多次。

    展开全文
  • 一、ActivityThread 源码分析、 二、ActivityThread 部分代码示例



    dex 解密时 , 需要将 代理 Application 替换为 真实 Application ; 替换 Application 首先要理解系统如何注册应用的 Application 的 ;





    一、ActivityThread 源码分析



    参考源码 : /frameworks/base/core/java/android/app/ActivityThread.java


    Zygote 进程孵化器 fork 出应用进程后 , 就会执行 ActivityThread 中的 main 函数 ;

    在 main 函数中 , 调用了 Looper.prepareMainLooper() 方法 , 初始化了 Looper , 在 main 方法最后 , 执行了 Looper.loop() , 开启了无限循环获取 Message 并执行 ;

    准备完 Looper 之后 , ActivityThread thread = new ActivityThread() 创建了 ActivityThread 对象 , 并调用了该对象的 attach 函数 , thread.attach(false) ;


        public static void main(String[] args) {
            Looper.prepareMainLooper();
    
            ActivityThread thread = new ActivityThread();
            thread.attach(false);
            Looper.loop();
        }
    

    在 attach 函数中 , private void attach(boolean system) , 传入的参数是 false , 进入第一个分支 if (!system) { ;

    在该分支中 , final IActivityManager mgr = ActivityManagerNative.getDefault() , 通过 ActivityManager 拿到了 Binder 对象 ;

    通过调用该 Binder 对象的 attachApplication 方法 , mgr.attachApplication(mAppThread) , 将本 ApplicationThread 对象传送出去 ;


        private void attach(boolean system) {
            sCurrentActivityThread = this;
            mSystemThread = system;
            if (!system) {
                RuntimeInit.setApplicationObject(mAppThread.asBinder());
                final IActivityManager mgr = ActivityManagerNative.getDefault();
                try {
                    mgr.attachApplication(mAppThread);
                } catch (RemoteException ex) {
                    // Ignore
                }
                // Watch for getting close to heap limit.
            } else {
                // Don't set application object here -- if the system crashes,
                // we can't display an alert, we just want to die die die.
            }
        }
    

    在 main 函数中创建 ActivityThread 对象时 , 会自动创建其内部的成员属性 , 包括主线程的 Handler , final H mH = new H() 成员 , H 类型就是 Handler 的子类 , private class H extends Handler ;


    利用 Binder 调用 ActivityThread 的 bindApplication 方法 , public final void bindApplication , 在 bindApplication 方法中 , 接收 ActivityManagerService 发送来的参数 , 最后发送一条 Message 给 H mH 对象 , 即 Hander 子类对象 , sendMessage(H.BIND_APPLICATION, data) ;

    最终由 H 对象 , private class H extends Handler 类型 , 处理上述逻辑 , 最终调用 handleBindApplication 方法处理 , private void handleBindApplication(AppBindData data) ;


        final H mH = new H();
        
        private class H extends Handler {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case BIND_APPLICATION:
                        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                        AppBindData data = (AppBindData)msg.obj;
                        handleBindApplication(data);
                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                        break;
    		}
    	}
    

    在 ActivityThread 的 handleBindApplication 方法中就是进行的 Application 准备工作 , 构建 Application , 并调用 Application 中的 onCreate 等生命周期函数 ;

    在 handleBindApplication 方法 中 , Application app = data.info.makeApplication(data.restrictedBackupMode, null) , 此处创建 Application ;

    应用 Application 的具体创建方法 , 需要查看该 data.info.makeApplication 方法 , makeApplication 是 data.info 对象中的函数 , data.info 对象类型是 android.app.LoadedApk 类型 , data.info 是调用 getPackageInfoNoCheck 获取的 , data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo) ;

        private void handleBindApplication(AppBindData data) {
            try {
                // If the app is being launched for full backup or restore, bring it up in
                // a restricted environment with the base application class.
                Application app = data.info.makeApplication(data.restrictedBackupMode, null);
                mInitialApplication = app;
            } finally {
                StrictMode.setThreadPolicy(savedPolicy);
            }
    	}
    




    二、ActivityThread 部分代码示例



    ActivityThread 部分代码示例 :

    public final class ActivityThread {
        final ApplicationThread mAppThread = new ApplicationThread();
        final Looper mLooper = Looper.myLooper();
        final H mH = new H();
        
        private class H extends Handler {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case BIND_APPLICATION:
                        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                        AppBindData data = (AppBindData)msg.obj;
                        handleBindApplication(data);
                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                        break;
    		}
    	}
    
        private void handleBindApplication(AppBindData data) {
            try {
                // If the app is being launched for full backup or restore, bring it up in
                // a restricted environment with the base application class.
                Application app = data.info.makeApplication(data.restrictedBackupMode, null);
                mInitialApplication = app;
            } finally {
                StrictMode.setThreadPolicy(savedPolicy);
            }
    	}
    
        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) {
                sendMessage(H.BIND_APPLICATION, data);
        }    
    
        private void attach(boolean system) {
            sCurrentActivityThread = this;
            mSystemThread = system;
            if (!system) {
                RuntimeInit.setApplicationObject(mAppThread.asBinder());
                final IActivityManager mgr = ActivityManagerNative.getDefault();
                try {
                    mgr.attachApplication(mAppThread);
                } catch (RemoteException ex) {
                    // Ignore
                }
                // Watch for getting close to heap limit.
            } else {
                // Don't set application object here -- if the system crashes,
                // we can't display an alert, we just want to die die die.
            }
        }
    
        public static void main(String[] args) {
            Looper.prepareMainLooper();
    
            ActivityThread thread = new ActivityThread();
            thread.attach(false);
            Looper.loop();
        }
    }
    
    展开全文
  • ActivityThread相关源码分析

    千次阅读 2019-02-26 16:08:20
    分析核心的类:ActivityThread 各个关键类简介:  1、ActivityThread(进程内唯一):负责进程下Application、所有Activity  2、Instrumentation(进程内唯一):作为ActivityThread组合部分,负责统一创建...

    前言

    先看ActivityThread相关类图

     

    分析核心的类:ActivityThread

    各个关键类简介:

          1、ActivityThread(进程内唯一):负责进程下Application、所有Activity

          2、Instrumentation(进程内唯一):作为ActivityThread组合部分,负责统一创建Application,创建Activity,管理某一个Activity生命周期。

          3、ApplicationThread(进程内唯一):作为ActivityThread组合部分,管理整个App的生命周期,例如:通知App进入sleep状态,广播接收,应用退出等一堆App事件的分发。

          4、H(进程内唯一):作为ActivityThread组合部分,继承于Handler,分发App内部Framework层的所有事件,将异步事件转入主线程。

          5、LoadedApk(进程内唯一):常用变量名称:packageInfo。所以顾名思义,该类表示包相关的信息,例如:APK数据文件地址、ApplicationInfo(由此可知,LoadedApk含有Application的所有信息)

          6、ActivityClientRecord:新建Activity时会创建,用来持有Activity、ActivityInfo、LoadedApk等和具体Activity有关的信息

          7、ActivityManagerService:管理Activity、Service等活动栈、记录及与C++层交互

          8、ActivityStarter:主要负责Activity的启动,及联系Activity的Stack和Task相关

    启动ActivityThread

    1)启动入口

          看源码,我们可以发现,ActivityThread的构造器被两个静态方法使用,一个是ActivityThread的main方法,一个是ActivityThread的systemMain方法。

          先看systemMain方法,其由SystemServer的createSystemContext方法调用,同时该方法又被SystemServer的run方法调用。从Android启动源码那篇博客可以知道,run方法为System进程Java端的初始化过程。所以可以看出该方法是专门为SystemServer创建ActivityThread使用的。

          相对的,那么ActivityThread的main方法为普通App进程的启动方式。

    2)下面进入main@ActivityThread

    public static void main(String[] args) {
        // 初始化Environment
        Environment.initForCurrentUser();
        // 初始化Event日志
        EventLogger.setReporter(new EventLoggingReporter());
        // 根据用户Id创建指定目录
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        // 将当前线程作为主线程,初始化Looper
        Looper.prepareMainLooper();
        // 创建ActivityThread
        ActivityThread thread = new ActivityThread();
        // 如果是System则直接创建Application,如果非System则将ApplicationThread注册到AM中
        thread.attach(false);
        // 初始化Handler
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        // 无限循环中
        Looper.loop();
        // 异常终止,注意这里的异常通常是执行不到的,上方loop有异常也不会执行到这里。
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    
    

          ActivityThread 构造器仅仅new ResourcesManager();ResourceManager,顾名思义,是我们获取资源的管理类,DisplayMetrics和AssetManager也都是其负责的。

          main方法进入循环前只执行了一个方法:thread.attach(false);而后进入循环,说明了在该方法里面,集合了整个应用进程的生命周期。

    3)开启应用App创建,查看thread.attach(false);

    private void attach(boolean system) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) { // 进入应用创建
            ViewRootImpl.addFirstDrawHandler(new Runnable() {
                @Override
                public void run() {
                    ensureJitEnabled();
                }
            });
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
            UserHandle.myUserId());
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            // 创建应用Application
            final IActivityManager mgr = ActivityManagerNative.getDefault();
            try {   
                mgr.attachApplication(mAppThread);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            ...
        } else { // 进入SystemServer创建
            ...
            try {
                // 创建Activity生命周期管理类
                mInstrumentation = new Instrumentation();
                // 创建系统级别的上下文
                ContextImpl context = ContextImpl.createAppContext(
                    this, getSystemContext().mPackageInfo);
                // 创建Application,并启动onCreate方法
                mInitialApplication = context.mPackageInfo.makeApplication(true, null);
                mInitialApplication.onCreate();
            } catch (Exception e) {
                throw new RuntimeException("Unable to instantiate Application():" + e.toString(), e);
            }
        }
        // 记录着系统关键log信息,主要功能用于Debug调试
        DropBox.setReporter(new DropBoxReporter());
        // 注册到ViewRootImpl中,监听组件配置信息变化监听
        ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
            ...
        });
    }

    创建System的Application代码比较明显,但是创建应用Application链路比较长,我们将这里分析下:

    attach()中进入应用Application的入口:

    final IActivityManager mgr = ActivityManagerNative.getDefault();
    try {
        mgr.attachApplication(mAppThread);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }

    mgr在这里就是ActivityManagerProxy(可以看gDefault这个单例,里面先找到AMS,再利用AMS创建了ActivityManagerProxy),看ActivityManagerProxy里面的attachApplication,这里面执行了:

    mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);

    mRemote为创建ActivityManagerProxy时传入的IBinder,也就是AMS。这里执行的就是跨进程了。

    通过ATTACH_APPLICATION_TRANSACTION可以确定,处理的代码在AMS的父类ActivityManagerNative中onTransact,

    case ATTACH_APPLICATION_TRANSACTION: {
        data.enforceInterface(IActivityManager.descriptor);
        IApplicationThread app = ApplicationThreadNative.asInterface(
            data.readStrongBinder());
        if (app != null) {
            attachApplication(app);
        }
        reply.writeNoException();
        return true;
    }

    4)下一步执行attachApplication(app);这里执行的代码不再是ActivityManagerProxy,而是在AMS中:

    @Override
    public final void attachApplication(IApplicationThread thread) {
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid);
            Binder.restoreCallingIdentity(origId);
        }
    }
    
    private final boolean attachApplicationLocked(IApplicationThread thread,int pid) {
        ...
        try {
            ...
            // 绑定Application
            thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,app.instrumentationUiAutomationConnection, testMode,
    mBinderTransactionTrackingEnabled, enableTrackAllocation,
    isRestrictedBackupMode || !normalMode, app.persistent,
    new Configuration(mConfiguration), app.compat,
    getCommonServicesLocked(app.isolated),
    mCoreSettingsObserver.getCoreSettingsLocked());
            ...
    
        } catch (Exception e) {
            ...
        }
        if (normalMode) {
            try {
                // 加载Launch Activity
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
        }
        ...
        return true;
    }

    看源码,可以发现,创建Application,下一步应该是在这个传入的IApplicationThread的bindApplication方法中执行,从之前的代码中我们可以看到,ActivityThread传入了

    mgr.attachApplication(mAppThread);

    mAppThread为ApplicationThread,所以,AMS中执行的thread为ApplicationThread的Binder,最终代码我们看ApplicationThread的bindApplication方法。

    创建Application

    1)查看ApplicationThread的bindApplication方法

    public final void bindApplication(String processName, ApplicationInfo appInfo,
    List<ProviderInfo> providers, ComponentName instrumentationName,
    ProfilerInfo profilerInfo, Bundle instrumentationArgs,
    IInstrumentationWatcher instrumentationWatcher,
    IUiAutomationConnection instrumentationUiConnection, int debugMode,
    boolean enableBinderTracking, boolean trackAllocation,
    boolean isRestrictedBackupMode, boolean persistent, Configuration config,
    CompatibilityInfo compatInfo, Map<String, IBinder> services, Bundle coreSettings) {
        ...
        sendMessage(H.BIND_APPLICATION, data);
    }
    
    

    ApplicationThread为ActivityThread的内部类,这里刚好有这么一个方法,同时参数都对应的上,说明我们之前确实没有找错对象。可以看到该方法最终又找到了H这个Handler,进而在主线程中执行了ActivityThread的handleBindApplication();

    2)看handleBindApplication:

    private void handleBindApplication(AppBindData data) {
        ...
        try {
            ...
            Application app = data.info.makeApplication(data.restrictedBackupMode, null);
            mInitialApplication = app;
            ...
            try {
                // 该方法为空,应该是预留方法
                mInstrumentation.onCreate(data.instrumentationArgs);
            } catch (Exception e) {
                ...
            }
            try {
                // 开启Application的onCreate方法
                mInstrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                ...
            }
            ...
        } finally {
            StrictMode.setThreadPolicy(savedPolicy);
        }
    }
    
    

    到了这里我们的Application已经启动了。

    启动Launch Activity

    下面分析Activity启动,这里要回到ActivityThread启动的第4步,执行:

    1)第一步:m.attachApplicationLocked(app);

    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
        ...
        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
            ...
            try {
                if (realStartActivityLocked(hr, app, true, true)) {
                    didSomething = true;
                }
            } catch (RemoteException e) {
                ...
                throw e;
            }
            ...
        }
        ...
        return didSomething;
    }

    2)第二步:StackSupervisor的realStartActivityLocked方法

    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
    boolean andResume, boolean checkConfig) throws RemoteException {
        ...
        app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
            System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
        new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
        task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
        newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
        ...
    }
    
    

    通之前的Application一样,这里的thread为ApplicationThread

    3)第三步:ApplicationThread的scheduleLaunchActivity

    @Override
    public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
    ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
    CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
    int procState, Bundle state, PersistableBundle persistentState,
    List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
    boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
        ...
        sendMessage(H.LAUNCH_ACTIVITY, r);
    }

    4)第四步:ActivityThread的handleLaunchActivity

    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        ...
        // 初始化窗体
        WindowManagerGlobal.initialize();
        // 启动Launch Acitivity
        Activity a = performLaunchActivity(r, customIntent);
        if(a != null){
            ...
            // 将Activity状态置为Resume状态
            handleResumeActivity(r.token, false, r.isForward,
            !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
            ...
        }
        ...
    }

    5)第五步:ActivityThread的performLaunchActivity

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            // 创建Actiivty实体类
            activity = mInstrumentation.newActivity(
            cl, component.getClassName(), r.intent);
            ...
        } catch (Exception e) {
            ...
        }
        try {
            // 如果packageinfo中没有Application,则创建新的Application,并onCreate(),否则直接返回
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            if (activity != null) {
                // 绑定上下文,Window设置
                activity.attach(appContext, this, getInstrumentation(), r.token,
                r.ident, app, r.intent, r.activityInfo, title, r.parent,
                r.embeddedID, r.lastNonConfigurationInstances, config,
                r.referrer, r.voiceInteractor, window);
                // Activity onCreate方法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                // 执行 onStart()方法
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
                // 执行状态恢复生命周期
                if (!r.activity.mFinished) {
                    if (r.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
    r.persistentState);
                        }
                    } else if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                }
            }
            ...
        }
        r.paused = true;
        mActivities.put(r.token, r);
        } catch (SuperNotCalledException e) {
            ...
        }
        return activity;
    }

    代码执行完performLaunchActivity,Launch Activity已经进入了onStart。而后回到第四步,进入handleResumeActivity,使Activity进入Resume状态。

    至此,我们的Launch Activity已经完成启动,ActivityThread在这之中扮演的角色也比较清晰了。

     

     

    展开全文
  • 一、ActivityThread 、 二、ActivityThread 绑定 ApplicationThread、 三、AMS attachApplication -> attachApplicationLocked、 四、ApplicationThread.bindApplication、 五、H 处理 BIND_APPLICATION 消息、 六、...





    一、ActivityThread 主函数启动



    ActivityThread 是应用的主线程 , 从 main 函数开始执行 ;

    Looper.prepareMainLooper() 将主线程设置为 Looper 线程 , 开启 Looper , 用于配合 H 处理消息 ;

    thread.attach(false, startSeq) 绑定 ActivityThread ;

    在方法最后 Looper.loop(); 开始无限循环 , 处理 Handler 消息 ;

    /**
     * 管理应用程序进程中主线程的执行、调度和执行活动、广播以及活动管理器请求的其他操作。
     *
     * {@hide}
     */
    public final class ActivityThread extends ClientTransactionHandler {
        public static void main(String[] args) {
    
    		// 将主线程设置为 Looper 线程 , 开启 Looper , 用于配合 H 处理消息 
            Looper.prepareMainLooper();
    
    		// 创建 ActivityThread 实例对象 
            ActivityThread thread = new ActivityThread();
            // 绑定
            thread.attach(false, startSeq);
    	
    		// 开始无限循环 , 处理 Handler 消息 
            Looper.loop();
    
            throw new RuntimeException("Main thread loop unexpectedly exited");
        }
    }
    

    完整代码参考 /frameworks/base/core/java/android/app/ActivityThread.java





    二、ActivityThread 绑定 ApplicationThread



    ActivityThread 中的 void attach(boolean system, long startSeq) 方法 , 主要是通过 Binder 机制获取 AMS , 并调用 AMS 的 attachApplication 方法 , 为 ActivityThread 绑定 ApplicationThread ;

    /**
     * 管理应用程序进程中主线程的执行、调度和执行活动、广播以及活动管理器请求的其他操作。
     *
     * {@hide}
     */
    public final class ActivityThread extends ClientTransactionHandler {
    
        private void attach(boolean system, long startSeq) {
            sCurrentActivityThread = this;
            mSystemThread = system;
            if (!system) {
                RuntimeInit.setApplicationObject(mAppThread.asBinder());
                // 通过 Binder 机制获取 AMS 
                final IActivityManager mgr = ActivityManager.getService();
                try {
                	// 调用 AMS 的 attachApplication 方法 , 为 ActivityThread 绑定 ApplicationThread 
                    mgr.attachApplication(mAppThread, startSeq);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
            }
        }
    
    }
    

    完整代码参考 /frameworks/base/core/java/android/app/ActivityThread.java





    三、AMS attachApplication -> attachApplicationLocked 绑定 ApplicationThread



    在 AMS 中的 attachApplication 方法中 , 调用了 attachApplicationLocked 方法 ,

    attachApplicationLocked 方法中 , 有调用了 ActivityThread 的 bindApplication 方法 , 为 ActivityThread 绑定了 ApplicationThread ;

    public class ActivityManagerService extends IActivityManager.Stub
            implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    
        @Override
        public final void attachApplication(IApplicationThread thread) {
            synchronized (this) {
                int callingPid = Binder.getCallingPid();
                final long origId = Binder.clearCallingIdentity();
                attachApplicationLocked(thread, callingPid);
                Binder.restoreCallingIdentity(origId);
            }
        }
    
    
    	// 为 ApplicationThread 绑定 Application 主方法
        private final boolean attachApplicationLocked(IApplicationThread thread,
                int pid) {
            try {
                checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
                mStackSupervisor.mActivityMetricsLogger.notifyBindApplication(app);
    			// 在此处为 ActivityThread 绑定 Application , 此时又回到 ActivityThread
                if (app.instr != null) {
                    thread.bindApplication(processName, appInfo, providers,
                            app.instr.mClass,
                            profilerInfo, app.instr.mArguments,
                            app.instr.mWatcher,
                            app.instr.mUiAutomationConnection, testMode,
                            mBinderTransactionTrackingEnabled, enableTrackAllocation,
                            isRestrictedBackupMode || !normalMode, app.persistent,
                            new Configuration(getGlobalConfiguration()), app.compat,
                            getCommonServicesLocked(app.isolated),
                            mCoreSettingsObserver.getCoreSettingsLocked(),
                            buildSerial);
                } else {
                    thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                            null, null, null, testMode,
                            mBinderTransactionTrackingEnabled, enableTrackAllocation,
                            isRestrictedBackupMode || !normalMode, app.persistent,
                            new Configuration(getGlobalConfiguration()), app.compat,
                            getCommonServicesLocked(app.isolated),
                            mCoreSettingsObserver.getCoreSettingsLocked(),
                            buildSerial);
                }
            } catch (Exception e) {
            }
    
            return true;
        }
    
    }
    

    ActivityManagerService 完整源码参考 : frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java





    四、ApplicationThread.bindApplication 绑定 ApplicationThread



    再次回到 ActivityThread 内部类 ApplicationThread 中 , 调用 ApplicationThread 类的 bindApplication 方法 , 即可为 ActivityThread 绑定 ApplicationThread , 在所有数据就位后 , 发送了一个 H.BIND_APPLICATION 消息 ;

    /**
     * 管理应用程序进程中主线程的执行、调度和执行活动、广播以及活动管理器请求的其他操作。
     *
     * {@hide}
     */
    public final class ActivityThread extends ClientTransactionHandler {
        private class ApplicationThread extends IApplicationThread.Stub {
    		// 为 ActivityThread 绑定 Application 
            public final void bindApplication(String processName, ApplicationInfo appInfo,
                    List<ProviderInfo> providers, ComponentName instrumentationName,
                    ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                    IInstrumentationWatcher instrumentationWatcher,
                    IUiAutomationConnection instrumentationUiConnection, int debugMode,
                    boolean enableBinderTracking, boolean trackAllocation,
                    boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                    CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
                    String buildSerial, boolean autofillCompatibilityEnabled) {
    
                // 此处在所有数据就位后 , 发送了一个 H.BIND_APPLICATION 消息
                sendMessage(H.BIND_APPLICATION, data);
            }
    	}
    }
    

    完整代码参考 /frameworks/base/core/java/android/app/ActivityThread.java





    五、ActivityThread.H 处理 BIND_APPLICATION 消息



    ActivityThread.ApplicationThread.bindApplication 中 , 发送了一条 BIND_APPLICATION 消息 , 110 110 110 ;

    ActivityThread.H 中的 handleMessage 方法中 , 处理 110 110 110 事件的分支中, 调用了 handleBindApplication 方法 , 处理绑定 ApplicationThread 相关逻辑 ;

    /**
     * 管理应用程序进程中主线程的执行、调度和执行活动、广播以及活动管理器请求的其他操作。
     *
     * {@hide}
     */
    public final class ActivityThread extends ClientTransactionHandler {
        class H extends Handler {
            public static final int BIND_APPLICATION        = 110;
    
            public void handleMessage(Message msg) {
                if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
                switch (msg.what) {
                    case BIND_APPLICATION:
                        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                        AppBindData data = (AppBindData)msg.obj;
                        // 处理绑定 Application 相关逻辑
                        handleBindApplication(data);
                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                        break;
                }
                Object obj = msg.obj;
                if (obj instanceof SomeArgs) {
                    ((SomeArgs) obj).recycle();
                }
            }
        }
    }
    

    完整代码参考 /frameworks/base/core/java/android/app/ActivityThread.java





    六、ActivityThread.handleBindApplication 处理绑定问题



    ActivityThread.handleBindApplication 方法中 , 通过调用 data.info.makeApplication(data.restrictedBackupMode, null) 方法 , 创建 Application 实例对象 ;

    data.infoLoadedApk 类型 ;

    /**
     * 管理应用程序进程中主线程的执行、调度和执行活动、广播以及活动管理器请求的其他操作。
     *
     * {@hide}
     */
    public final class ActivityThread extends ClientTransactionHandler {
        private void handleBindApplication(AppBindData data) {
            // 将UI线程注册为运行时的敏感线程。
            VMRuntime.registerSensitiveThread();
            if (data.trackAllocation) {
                DdmVmInternal.enableRecentAllocations(true);
            }
    
            // 记录进程开始时间
            Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
    
            // 允许在应用程序和提供程序安装期间访问磁盘。
            // 这可能会阻止处理有序的广播,但稍后的处理可能最终会执行相同的磁盘访问。
            Application app;
            final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
            final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
            try {
                // 如果要启动应用程序进行完全备份或恢复,请使用基本应用程序类在受限环境中启动。
                app = data.info.makeApplication(data.restrictedBackupMode, null);
    
                // Propagate autofill compat state
                app.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);
    
                mInitialApplication = app;
            } 
        }
    }
    

    完整代码参考 /frameworks/base/core/java/android/app/ActivityThread.java





    七、LoadedApk.makeApplication 创建 Application 对象



    调用 LoadedApkmakeApplication 方法 , 创建 Application 实例 , 在该方法中通过调用 InstrumentationnewApplication 方法 , 创建 Application 实例对象

    /**
     * 本地状态维护了当前加载的.apk. 
     * Local state maintained about a currently loaded .apk.
     * @hide
     */
    public final class LoadedApk {
    
    	// 创建 Application 实例对象 
        public Application makeApplication(boolean forceDefaultAppClass,
                Instrumentation instrumentation) {
            // 如果当前存在 Application , 直接返回 
            if (mApplication != null) {
                return mApplication;
            }
    
            try {
                ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
                // 通过调用 Instrumentation 的 newApplication 方法 , 创建 Application 实例对象
                app = mActivityThread.mInstrumentation.newApplication(
                        cl, appClass, appContext);
                appContext.setOuterContext(app);
            } catch (Exception e) {
            }
            mActivityThread.mAllApplications.add(app);
            mApplication = app;
    
            return app;
        }
    }
    

    完整代码参考 /frameworks/base/core/java/android/app/LoadedApk.java ;





    八、Instrumentation.newApplication 创建 Application 对象



    LoadedApkmakeApplication 方法 中 , 调用了 InstrumentationnewApplication 方法创建 Application 实例对象 ;

    /**
     * 用于实现应用程序检测代码的基类。
     * 当在启用检测的情况下运行时,该类将在任何应用程序代码之前为您实例化,
     * 从而允许您监视系统与应用程序之间的所有交互。
     * 通过AndroidManifest.xml的&amp;lt;仪器仪表&amp;gt;标签。
     */
    public class Instrumentation {
    
        /**
         * 执行进程{@link Application}对象的实例化。默认实现提供正常的系统行为。
         *
         * @param cl 用来实例化对象的类加载器。
         * @param className 实现应用程序对象的类的名称。
         * @param context 用于初始化应用程序的上下文
         *
         * @return 新实例化的应用程序对象。
         */
        public Application newApplication(ClassLoader cl, String className, Context context)
                throws InstantiationException, IllegalAccessException,
                ClassNotFoundException {
            Application app = getFactory(context.getPackageName())
                    .instantiateApplication(cl, className);
            app.attach(context);
            return app;
        }
    	
    }
    

    完整代码参考 /frameworks/base/core/java/android/app/Instrumentation.java ;





    九、AppComponentFactory.instantiateApplicationCompat 创建 Application 对象



    InstrumentationnewApplication 方法中 , 调用了 AppComponentFactoryinstantiateApplicationCompat 方法 , 创建 Application , (Application) cl.loadClass(className).getDeclaredConstructor().newInstance(); , 此处通过反射创建 Application 实例对象 ;

    /**
     * 使用androidx库的{@link android.app.AppComponentFactory}版本。
     *
     * 注意:这只适用于API 28+,不支持AppComponentFactory功能。
     */
    @RequiresApi(28)
    public class AppComponentFactory extends android.app.AppComponentFactory {
    
       /**
        * 允许应用程序重写应用程序对象的创建。这可以用于对这些类执行依赖项注入或类装入器更改等操作。
        * <p>
        * 此方法仅用于提供用于实例化的挂钩。它不提供对应用程序对象的早期访问。
        * 返回的对象尚未初始化为上下文,不应用于与其他android API交互。
        *
        * @param cl        用于实例化的默认类加载器。
        * @param className 要实例化的类。
        */
        public @NonNull Application instantiateApplicationCompat(@NonNull ClassLoader cl,
                @NonNull String className)
                throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            try {
                return (Application) cl.loadClass(className).getDeclaredConstructor().newInstance();
            } catch (InvocationTargetException | NoSuchMethodException e) {
                throw new RuntimeException("Couldn't call constructor", e);
            }
        }
    
    }
    

    完整代码参考 /frameworks/support/compat/src/main/java/androidx/core/app/AppComponentFactory.java ;

    展开全文
  • 在看ActivityThread源码的时候,看到有博客提到它承担着整个应用的运转以及生命周期。于是很好奇想一探究竟,跟着跟着大概就把应用启动过程过程了解了一下。这篇文章主要是介绍ActivityThread中有关于应用启动过程...
  • 创建Activity,调用onCreate、onResume方法等,学习这块的源码便于理解创建的次序和Activity的生命周期 核心类及功能如下: android.app.ActivityThread This manages the execution of the main thread in an ...
  • Activity 启动源码分析 ( ActivityThread 流程分析 一 ) 分析了从 ActivityThread 的 main() 函数启动 , ApplicationThread 绑定 , Application 创建 , 下面继续分析后续内容 ; 一、ActivityManagerService....
  • 由之前的源码 我们知道ActivityThread 的创建是在SystemServe中开始的 SystemServer.java run 方法 private void run() { try { Looper.prepareMainLooper(); Looper.getMainLooper().setSlowLogThresholdMs( ...
  • 前言 本文分析了Hander几个重要类以及他们之间的关系。...源码分析 ActivityThread中也使用到了Looper循环,那么看下它里面是怎么使用。 先看下ActivityThread的main函数里面: public static vo...
  • 1. ActivityThread功能  它管理应用进程的主线程的执行(相当于普通Java程序的main入口函数),并根据AMS的要求负责调度和执行activities、broadcasts和其它操作。  在Android系统中,在默认情况下,一个应用程序内...
  • 这里会从ActivityThread开始分析,也有必要过一下,最后会整个流程会走一遍,主线一定要走~~ 开始: core/java/android/app/ActivityThread.java 1: ActivityThread.java 这个java文件并没有构造方法,有的是...
  • 一、Handler、Looper、MessageQueue、HandlerThread、ActivityThread、Message结构 1、Message:消息;其中包含了消息ID,消息对象以及处理的数据等,由MessageQueue统一列队管理,终由Handler处理 2、Message...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 9,653
精华内容 3,861
关键字:

activitythread源码分析