2020-12-15

本文详细阐述了Android应用从点击图标到启动Activity的完整流程,包括创建进程、绑定Application和启动Activity三个主要步骤。涉及ActivityManagerService、Zygote、ActivityThread、LoadedApk等关键组件的作用和交互,深入理解Android系统的内部工作机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 创建进程

ActivityManagerService调用startProcessLocked()创建新的进程,.
该方法会通过前面讲到的socket通道传递参数给Zygote进程. 
Zygote孵化自身, 并调用ZygoteInit.main()方法来实例化ActivityThread对象,
并最终返回新进程的pid.

ActivityThread随后依次调用Looper.prepareLoop()和
Looper.loop()来开启消息循环.

在这里插入图片描述

2. 绑定Application

将进程和指定的Application绑定起来. 
这个是通过ActivityThread对象中调用bindApplication()方法完成的. 
该方法发送一个BIND_APPLICATION的消息到消息队列中, 
最终通过handleBindApplication()方法处理该消息. 
然后调用makeApplication()方法来加载App的classes到内存中.

在这里插入图片描述

3. 启动Activity

经过前两个步骤之后, 系统已经拥有该application的进程了.
接下来就是从刚才创建的application进程中,启动一个新的activity了.

实际调用方法是realStartActivity(), 
它会调用application线程对象中的sheduleLaunchActivity()方法
发送一个LAUNCH_ACTIVITY消息到消息队列中, 
通过 handleLaunchActivity()来处理该消息.

在这里插入图片描述

LoadedApk 代表给加载的应用

LoadedApk ==》 makeApplication?
./frameworks/base/core/java/android/app/LoadedApk.java

可以将自己的dex文件加入进去执行,此时就在目标进程了。

桌面点击应用图标,整个执行过程

Launcher进程
Activity.java
startActivity(Intent intent)
  startActivity(intent, null)
    startActivityForResult(intent, -1);
      startActivityForResult(intent, requestCode, null);
        Instrumentation.java
        execStartActivity(this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);---Binder IPC--->startActivity
 
SystemServer进程
ActivityManagerService.java
startActivity(whoThread, who.getBasePackageName(), intent,intent.resolveTypeIfNeeded(who.getContentResolver()),token, target, requestCode, 0, null, options);
  startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,resultWho, requestCode, startFlags, profilerInfo, bOptions,UserHandle.getCallingUserId());
    startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,true /*validateIncomingUser*/);
      ActivityStarter.java
      startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,mRequest.ignoreTargetSecurity, mRequest.componentSpecified,mRequest.outActivity, mRequest.inTask, mRequest.reason,mRequest.allowPendingRemoteAnimationRegistryLookup)
        startActivity(caller, intent, ephemeralIntent, resolvedType,aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,inTask, allowPendingRemoteAnimationRegistryLookup)
          startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,true /* doResume */, checkedOptions, inTask, outActivity)
            startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, doResume, options, inTask, outActivity);
              ActivityStackSupervisor.java
              resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,mOptions);
                ActivityStack.java
                resumeTopActivityUncheckedLocked(target, targetOptions);
                  resumeTopActivityInnerLocked(prev, options);
                    startPausingLocked(userLeaving, false, next, false);
                      ClientLifecycleManager.java
                      scheduleTransaction(prev.app.thread, prev.appToken,PauseActivityItem.obtain(prev.finishing, userLeaving,prev.configChangeFlags, pauseImmediately));
                        ClientTransaction.java
                        schedule();---Binder IPC--->scheduleTransaction
 
Launcher进程
IApplicationThread.java
scheduleTransaction(this);
  ActivityThread.java
    scheduleTransaction(transaction);
      sendMessage(EXECUTE_TRANSACTION)->handleMessage
        TransactionExecutor.java
        execute(transaction);
          executeCallbacks(transaction);
          executeLifecycleState(transaction);
            PauseActivityItem.java
            execute(mTransactionHandler, token, mPendingActions);
              ActivityThread.java
              handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,"PAUSE_ACTIVITY_ITEM");
            postExecute(mTransactionHandler, token, mPendingActions);---Binder IPC--->activityPaused
 
SystemServer进程
 ActivityManagerService.java
 activityPaused(token);
  ActivityStack.java
  activityPausedLocked(token, false);
    completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
      ActivityStackSupervisor.java
      resumeFocusedStackTopActivityLocked(topStack, prev, null);
        ActivityStack.java
        resumeTopActivityUncheckedLocked(target, targetOptions);
          ActivityStackSupervisor.java
          startSpecificActivityLocked(next, true, true);
            (如果进程存在:ActivityStackSupervisor::realStartActivityLocked)
            (如果进程不存在:创建进程-》startProcessLocked )
            ActivityManagerService.java
            startProcessLocked(r.processName, r.info.applicationInfo, true, 0,"activity", r.intent.getComponent(), false, false, true,(null != r.launchedFromPackage ? r.launchedFromPackage : "NA"));
 
应用进程
 一些列调用到ActivityThread.java的main方法,我们称之为应用程序的入口
  attach(false, startSeq);
  attachApplication(mAppThread, startSeq);---Binder IPC--->attachApplicationLocked
              
SystemServer进程
 ActivityManagerService.java
 attachApplicationLocked(thread, callingPid, callingUid, startSeq);//am_proc_bound
  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, isAutofillCompatEnabled);
  ActivityStackSupervisor.java
   attachApplicationLocked 
    realStartActivityLocked(activity, app,top == activity /* andResume */, true /* checkConfig */)//am_restart_activity
      ClientLifecycleManager.java
        scheduleTransaction(clientTransaction);
          ClientTransaction.java
            schedule();---Binder IPC--->scheduleTransaction
 
应用进程
IApplicationThread.java
scheduleTransaction(this);
  ActivityThread.java
    scheduleTransaction(transaction);
      sendMessage(EXECUTE_TRANSACTION)->handleMessage
        TransactionExecutor.java
        execute(transaction);
          executeCallbacks(transaction);
            LaunchActivityItem.java
            execute(mTransactionHandler, token, mPendingActions);
              ActivityThread.java
              handleLaunchActivity(r, pendingActions, null /* customIntent */);
          executeLifecycleState(transaction);
            ResumeActivityItem.java
            execute(mTransactionHandler, token, mPendingActions);
              ActivityThread.java
              handleResumeActivity(token, true /* finalStateRequest */, mIsForward,"RESUME_ACTIVITY");
            postExecute(mTransactionHandler, token, mPendingActions);---Binder IPC--->activityResumed
 
SystemServer进程
ActivityManagerService.java
activityResumed(token);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值