android12 应用启动流程(一)

这篇文章将大致得介绍下应用得一个启动流程,旨在大致理解,具体细节后续文章在做介绍

应用启动过程中得核心要点

  1. 四个进程,launcher、app、zygote、system-server(ams)
  2. 进程间通信,binder
  3. 线程间通信,Handler
    掌握以上四点,看启动流程基本就比较舒畅了

应用启动简介

基于sdk32分析,也就是android 12,大致流程如下:


未命名文件.png

部分参考:(12条消息) 【framework】应用进程启动流程_handleprocessstartedlocked_little_fat_sheep的博客-CSDN博客

要点记录

ActivityThread main方法

public static void main(String[] args) {
       Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

       // Install selective syscall interception
       AndroidOs.install();

       // CloseGuard defaults to true and can be quite spammy.  We
       // disable it here, but selectively enable it later (via
       // StrictMode) on debug builds, but using DropBox, not logs.
       CloseGuard.setEnabled(false);

       Environment.initForCurrentUser();

       // Make sure TrustedCertificateStore looks in the right place for CA certificates
       final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
       TrustedCertificateStore.setDefaultUserDirectory(configDir);

       // Call per-process mainline module initialization.
       initializeMainlineModules();

       Process.setArgV0("<pre-initialized>");
       //Looper 准备,非常重要
       Looper.prepareMainLooper();

       // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
       // It will be in the format "seq=114"
       long startSeq = 0;
       if (args != null) {
           for (int i = args.length - 1; i >= 0; --i) {
               if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                   startSeq = Long.parseLong(
                           args[i].substring(PROC_START_SEQ_IDENT.length()));
               }
           }
       }
       //实例一个ActivityThread,并进行attach
       ActivityThread thread = new ActivityThread();
       thread.attach(false, startSeq);

       if (sMainThreadHandler == null) {
           sMainThreadHandler = thread.getHandler();
       }

       if (false) {
           Looper.myLooper().setMessageLogging(new
                   LogPrinter(Log.DEBUG, "ActivityThread"));
       }

       // End of event ActivityThreadMain.
       Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
       //进行looper循环取消息处理
       Looper.loop();

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

如何调用Handle***Activity

调用AMS的attachApplication,进行bindApplication之后会进行activity的启动,

ActivityManagerService.java -- attachApplicationLocked
//进行application初始化,告诉应用进程应用信息,创建application和上下文等,
//调用application的oncreate
 thread.bindApplication(processName, appInfo, providerList, null, profilerInfo,

//进行activity的处理,该方法之后会有service、broadcast、backup agent等初始化
// See if the top visible activity is waiting to run in this process...
        if (normalMode) {
            try {
                didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
        }
ActivityTaskManagerService.java 
//进行application初始化,告诉应用进程应用信息,创建application和上下文等,
 @HotPath(caller = HotPath.PROCESS_CHANGE)
        @Override
        public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
            synchronized (mGlobalLockWithoutBoost) {
                if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
                    Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
                }
                try {
                    return mRootWindowContainer.attachApplication(wpc);
                } finally {
                    Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
                }
            }
        }
RootWindowContainer.java 
 boolean attachApplication(WindowProcessController app) throws RemoteException {
        boolean didSomething = false;
        for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
            mTmpRemoteException = null;
            mTmpBoolean = false; // Set to true if an activity was started.
            final DisplayContent display = getChildAt(displayNdx);
            display.forAllRootTasks(rootTask -> {
                if (mTmpRemoteException != null) {
                    return;
                }

                if (rootTask.getVisibility(null /* starting */)
                        == TASK_FRAGMENT_VISIBILITY_INVISIBLE) {
                    return;
                }
//这里进行启动
                final PooledFunction c = PooledLambda.obtainFunction(
                        RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this,
                        PooledLambda.__(ActivityRecord.class), app,
                        rootTask.topRunningActivity());
                rootTask.forAllActivities(c);
                c.recycle();
            });
            if (mTmpRemoteException != null) {
                throw mTmpRemoteException;
            }
            didSomething |= mTmpBoolean;
        }
//这个地方注意,如果创建成功 mTmpBoolean为true,那么就不会更新visible
        if (!didSomething) {
            ensureActivitiesVisible(null, 0, false /* preserve_windows */);
        }
        return didSomething;
    }

    private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,
            WindowProcessController app, ActivityRecord top) {
        if (r.finishing || !r.showToCurrentUser() || !r.visibleIgnoringKeyguard || r.app != null
                || app.mUid != r.info.applicationInfo.uid || !app.mName.equals(r.processName)) {
            return false;
        }

        try {
//进行启动
            if (mTaskSupervisor.realStartActivityLocked(r, app,
                    top == r && r.isFocusable() /*andResume*/, true /*checkConfig*/)) {
                mTmpBoolean = true;
            }
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception in new application when starting activity "
                    + top.intent.getComponent().flattenToShortString(), e);
            mTmpRemoteException = e;
            return true;
        }
        return false;
    }
ActivityTaskSupervisor.java
 boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
                                       ....................省略代码.......................
//这里就是进行HandleLaunchActivity,主要依靠这个LaunchActivityItem的callback
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.getFilteredReferrer(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;
//这里进行了lifecycle状态设置,后面解析的时候会进行更新
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(isTransitionForward);
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // Schedule transaction. 执行事务,下个代码块看下具体流程
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
....................省略代码.......................
mService.getLifecycleManager()最终获取的是ClientLifecycleManager

 void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
//可以明显看到,这个是目标app的binder代理,这个时候看下transaction的处理
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        if (!(client instanceof Binder)) {
            // If client is not an instance of Binder - it's a remote call and at this point it is
            // safe to recycle the object. All objects used for local calls will be recycled after
            // the transaction is executed on client in ActivityThread.
            transaction.recycle();
        }
    }


**ClientTransaction.java**
    /** Get the target client of the transaction. */
      public IApplicationThread getClient() {
                  return mClient;
              }
//可以看到,跨进程调用的是目标app的scheduleTransaction,
//也就是activityThread的方法
    public void schedule() throws RemoteException {
                  mClient.scheduleTransaction(this);
              }

AvtivityTHread.java
        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
//调用父类ClientTransactionHandler的scheduleTransaction
            ActivityThread.this.scheduleTransaction(transaction);
        }
//ClientTransactionHandler中, 可以看到内部还是handler处理
void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

//handler 处理EXECUTE_TRANSACTION
case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        // Client transactions inside system process are recycled on the client side
                        // instead of ClientLifecycleManager to avoid being cleared before this
                        // message is handled.
                        transaction.recycle();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;

这里就是transactionExecutor处理
  public void execute(ClientTransaction transaction) {
         ..................省略代码.......................
        if (DEBUG_RESOLVER) Slog.d(TAG, transactionToString(transaction, mTransactionHandler));

//解析transaction,也就是之前add的callback---LaunchActivityItem,进行handlelaunchActivity
        executeCallbacks(transaction);
//解析lifecycleState,循环处理,正常就是走到resume,
//中间会处理StartActivityItem最终是ResumeActivityItem,
//每个Item都对应着Handle***Activity,最终调用我们写的on***生命周期函数,
//至此流程打通
        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }

以上流程解决了应用启动如何创建进程以及进入到onresume的过程

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,793评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,567评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,342评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,825评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,814评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,680评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,033评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,687评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,175评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,668评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,775评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,419评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,020评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,206评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,092评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,510评论 2 343

推荐阅读更多精彩内容