Activity相关初始化-Android12

Posted xhBruce

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Activity相关初始化-Android12相关的知识,希望对你有一定的参考价值。

Activity相关初始化-android12

android12-release

了解Activity启动流程:AMS:startActivity桌面启动应用应用内部启动startActivity-Android12


1. ProcessState

zygote fork新的App进程池,就是Binder线程池;反射调用到ActivityThread.main()

ActivityThread应用进程

frameworks/base/cmds/app_process/app_main.cpp

2. ActivityThread

  • thread.attach()到系统进程mgr.attachApplication()
  • Looper.loop() 主线程进入循环状态,(这里注意ActivityThread充当线程角色,并没有继承Thread,实际是zygote fork Binder线程

frameworks/base/core/java/android/app/ActivityThread.java

    public static void main(String[] args) 
        // ... ...
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        if (sMainThreadHandler == null) 
            sMainThreadHandler = thread.getHandler();
        
        // ... ...
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    

3. Instrumentation

  • Instrumentation是App process和AMS之间沟通桥梁
  • data.info.makeApplication() Application初始化

frameworks/base/core/java/android/app/ActivityThread.java

private void handleBindApplication(AppBindData data) 
    // ... ...
    if (ii != null) 
        initInstrumentation(ii, data, appContext);
     else 
        mInstrumentation = new Instrumentation();
        mInstrumentation.basicInit(this);
    
    // ... ...
        app = data.info.makeApplication(data.restrictedBackupMode, null);
    // ... ...

4. Application

  • makeApplication 单例模式,只初始化一次
  • appClass = "android.app.Application" 反射调用
  • instrumentation.callApplicationOnCreate(app) 通知

frameworks/base/core/java/android/app/LoadedApk.java

    public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) 
        if (mApplication != null) 
            return mApplication;
        

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");

        Application app = null;

        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) 
            appClass = "android.app.Application";
        

        try 
            final java.lang.ClassLoader cl = getClassLoader();
            if (!mPackageName.equals("android")) 
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
                        "initializeJavaContextClassLoader");
                initializeJavaContextClassLoader();
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            

            // Rewrite the R 'constants' for all library apks.
            SparseArray<String> packageIdentifiers = getAssets().getAssignedPackageIdentifiers(
                    false, false);
            for (int i = 0, n = packageIdentifiers.size(); i < n; i++) 
                final int id = packageIdentifiers.keyAt(i);
                if (id == 0x01 || id == 0x7f) 
                    continue;
                

                rewriteRValues(cl, packageIdentifiers.valueAt(i), id);
            

            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            // The network security config needs to be aware of multiple
            // applications in the same process to handle discrepancies
            NetworkSecurityConfigProvider.handleNewApplication(appContext);
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
         catch (Exception e) 
            if (!mActivityThread.mInstrumentation.onException(app, e)) 
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                throw new RuntimeException(
                    "Unable to instantiate application " + appClass
                    + " package " + mPackageName + ": " + e.toString(), e);
            
        
        mActivityThread.mAllApplications.add(app);
        mApplication = app;

        if (instrumentation != null) 
            try 
                instrumentation.callApplicationOnCreate(app);
             catch (Exception e) 
                if (!instrumentation.onException(app, e)) 
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    throw new RuntimeException(
                        "Unable to create application " + app.getClass().getName()
                        + ": " + e.toString(), e);
                
            
        

        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

        return app;
    

5. Activity

  • 启动时调用performLaunchActivityactivity.attach()初始化各种参数,如mUiThreadmMainThreadmInstrumentationmApplicationmWindow
  • Application app = r.packageInfo.makeApplication(false, mInstrumentation) 已经初始化了
  • 初始化activity = mInstrumentation.newActivity()
  • mInstrumentation.callActivityOnCreate() 通知onCreate
  • activity.attach() 处理WMS、mUiThread等相关信息
  • r.setState(ON_CREATE)设置ActivityClientRecord 状态ON_CREATE

frameworks/base/core/java/android/app/ActivityThread.java

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) 
        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) 
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        

        ComponentName component = r.intent.getComponent();
        if (component == null) 
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        

        if (r.activityInfo.targetActivity != null) 
            component = new ComponentName(r.activityInfo.packageName,
                    r.activityInfo.targetActivity);
        

        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try 
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess(isProtectedComponent(r.activityInfo),
                    appContext.getAttributionSource());
            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 
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());

            if (activity != null) 
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config =
                        new Configuration(mConfigurationController.getCompatConfiguration());
                if (r.overrideConfig != null) 
                    config.updateFrom(r.overrideConfig);
                
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                Window window = null;
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) 
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = 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);
                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, r.shareableActivityToken);

                if (customIntent != null) 
                    activity.mIntent = customIntent;
                
                r.lastNonConfigurationInstances = null;
                checkAndBlockForNetworkAccess();
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) 
                    activity.setTheme(theme);
                

                if (r.mActivityOptions != null) 
                    activity.mPendingOptions = r.mActivityOptions;
                    r.mActivityOptions = null;
                
                activity.mLaunchedFromBubble = r.mLaunchedFromBubble;
                activity.mCalled = false;
                if (r.isPersistable()) 
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                 else 
                    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;
                mLastReportedWindowingMode.put(activity.getActivityToken(),
                        config.windowConfiguration.getWindowingMode());
            
            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);
            

         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;
    

6. ClientTransaction / ClientTransactionItem / ClientTransactionHandler

  • Android P 上新增: Android P Basic lifecycle transaction containers--设计模式体现之策略模式;ActivityThread继承ClientTransactionHandler
  • ActivityLifecycleItem 生命周期各阶段处理,实际通过ClientTransactionHandler调用到ActivityThread里面处理
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(
        proc.getThread(), r.appToken);

final boolean isTransitionForward = r.isTransitionForward();
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,
        r.takeOptions(), isTransitionForward,
        proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,
        r.createFixedRotationAdjustmentsIfNeeded(), r.shareableActivityToken,
        r.getLaunchedFromBubble()));

// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) 
    lifecycleItem = ResumeActivityItem.obtain(isTransitionForward);
 else 
    lifecycleItem = PauseActivityItem.obtain();

clientTransaction.setLifecycleStateRequest(lifecycleItem);

// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);

以上是关于Activity相关初始化-Android12的主要内容,如果未能解决你的问题,请参考以下文章

Android - Activity 和 Fragment 初始化

Android学习之Activity的使用

如何构建Android MVVM 应用框架

Android 12 Window ViewRootImpl Activity的关系

安卓studio 怎么搭建mvvm

2017.12.18 Android开发之消息队列(实现子线程修改UI组件)