OpenHarmony开发者论坛

标题: 跟着源码学习OpenHarmony应用启动流程-Application&Ability初始化 [打印本页]

作者: 鸿蒙小语哥    时间: 2024-8-28 11:43
标题: 跟着源码学习OpenHarmony应用启动流程-Application&Ability初始化
[md]#### 一、引言

本文基于OpenAtom OpenHarmony(以下简称“OpenHarmony”) v4.0 Release版本的源码,对应用进程初始化后MainThread初始化及调用AttachApplication、LaunchApplication、LaunchAbility的过程做了分析和总结,该流程贯穿了应用程序的用户进程和系统服务进程。

#### 二、启动框架与核心类简介

##### 2.1 启动框架须知

如下图所示,OpenHarmony应用冷启动过程大致分为四个阶段:应用进程创建&初始化、Application&Ability初始化、Ability/AbilityStage生命周期、加载绘制首页。

![](https://forums-obs.openharmony.c ... cb8cgmw1eqgaajb.png)

##### 2.2 应用启动流程的核心类须知

* AppMgrService是应用管理服务主线程类,实现了IPC调用IAppMgr的接口,并通过AMSEventHandler将进程内各类事件及任务发送到主线程。
* AppRunningManager记录了应用的信息、应用的运行状态、进程信息等,内部持有了模块运行信息列表,应用第一次启动时,会先创建。
* AppSpawn是app孵化器,通过监听本地socket,接收客户端的请求消息。创建Ability应用所在进程,为Ability应用设置相应的权限,并预加载一些通用的模块。
* AbilityLoader负责注册和加载开发者Ability模块。开发者开发的Ability先调用AbilityLoader的注册接口注册到框架中,接着Ability启动时会被实例化。
* AbilityManager负责AbilityKit和Ability管理服务进行IPC的通信。
* MainThread是应用进程的核心类。应用进程内各类事件及任务通过MainThread中mainHandler投递到主线程并调用MainThread中的方法执行。
* AbilityThread是应用线程的核心类,是操作各种Ability生命周期及方法的入口。

#### **三、源码分析**

##### 3.1.主线程初始化

通过IPC机制,AMS调用AttachApplication,再回调AMS端
foundation\\ability\\ability\_runtime\\frameworks\\native\\appkit\\app\\main\_thread.cpp

1. void MainThread::Start()
2. {
3. ```
    sptr<MainThread> thread = sptr<MainThread>(new (std::nothrow) MainThread());
   ```
4. ```
    ......
   ```
5. ```
    thread->Init(runner);
   ```
6. ```
    thread->Attach();  }
   ```
7.
8. void MainThread::Init()
9. {
10. ```
    auto task = [weak]() {
    ```
11. ```
        auto appThread = weak.promote();
    ```
12. ```
        appThread->SetRunnerStarted(true);
    ```
13. ```
    };
    ```
14. ```
    if (!mainHandler\_-&gtostTask(task)) {
    ```
15. ```
        HILOG\_ERROR("MainThread::Init PostTask task failed");
    ```
16. ```
    }
    ```
17. ```
    watchdog\_->Init(mainHandler\_);
    ```
18. ```
    extensionConfigMgr\_->Init();
    ```
19. }
20.
21. void MainThread::Attach()
22. {
23. ```
    if (!ConnectToAppMgr()) {
    ```
24. ```
        return;
    ```
25. ```
    }
    ```
26. ```
    mainThreadState\_ = MainThreadState::ATTACH;
    ```
27. }
28.
29. bool MainThread::ConnectToAppMgr()
30. {
31. ```
    auto object = OHOS:elayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(APP\_MGR\_SERVICE\_ID);
    ```
32. ```
    appMgr\_ = iface\_cast<IAppMgr>(object);
    ```
33. ```
    appMgr\_->AttachApplication(this);
    ```
34. }
35.

*复制代码*

客户端发送 attach application 请求

foundation\ability\ability_runtime\interfaces\inner_api\app_manager\src\appmgr\app_mgr_proxy.cpp

1. AppMgrProxy::AttachApplication(const sptr<IRemoteObject> &obj)
2. {
3. ```
   sptr<IRemoteObject> remote = Remote();
   ```
4. ```
   remote->SendRequest(static\_cast<uint32\_t>(IAppMgr::Message::APP\_ATTACH\_APPLICATION), ...);
   ```
5. }
6.

*复制代码*

服务端收到 attach application 请求

foundation\ability\ability_runtime\interfaces\inner_api\app_manager\src\appmgr\app_mgr_stub.cpp

1. int32\_t AppMgrStub::HandleAttachApplication(MessageParcel &data, MessageParcel &reply)
2. {
3. ```
   sptr<IRemoteObject> client = data.ReadRemoteObject();
   ```
4. ```
   AttachApplication(client);
   ```
5. }
6.

*复制代码*

foundation\ability\ability_runtime\services\appmgr\src\app_mgr_service.cpp

1. void AppMgrService::AttachApplication(const sptr<IRemoteObject> &app)
2. {
3. pid\_t pid = IPCSkeleton::GetCallingPid();
4. ```
   AddAppDeathRecipient(pid);
   ```
5. ```
   std::function<void()> attachApplicationFunc =
   ```
6. ```
       std::bind(&AppMgrServiceInner::AttachApplication, appMgrServiceInner\_, pid, iface\_cast<IAppScheduler>(app));
   ```
7. ```
   taskHandler\_->SubmitTask(attachApplicationFunc, TASK\_ATTACH\_APPLICATION);
   ```
8. }
9.

*复制代码*

函数处理逻辑回到服务层

foundation\ability\ability_runtime\services\appmgr\src/app_mgr_service_inner.cpp

1. void AppMgrServiceInner::AttachApplication(const pid\_t pid, const sptr<IAppScheduler> &appScheduler)
2. {
3. ```
   ......
   ```
4. ```
   appRecord->SetApplicationClient(appScheduler);
   ```
5. ```
   appRecord->RegisterAppDeathRecipient();
   ```
6. ```
   if (appRecord->GetState() == ApplicationState::APP\_STATE\_CREATE) {
   ```
7. ```
       LaunchApplication(appRecord);
   ```
8. ```
   }
   ```
9. ```
   eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
   ```
10. ```
    eventInfo.processName = appRecord->GetProcessName();
    ```
11. ```
    AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP\_ATTACH, HiSysEventType::BEHAVIOR, eventInfo);
    ```
12. }<div class="document"><div class="section"><p class="paragraph text-align-type-left" style="margin: 3pt 0pt; font-family: 等线; font-size: 12pt;"><span data-font-family="default" style="font-size: 11pt; letter-spacing: 0pt; vertical-align: baseline;">
13. </span></p></div></div>void AppMgrServiceInner:aunchApplication(const std::shared\_ptr<AppRunningRecord> &appRecord)
14. {
15. ```
    appRecord->LaunchApplication(\*configuration\_);
    ```
16. ```
    appRecord->SetState(ApplicationState::APP\_STATE\_READY);
    ```
17. ```
    appRecord->SetRestartResidentProcCount(restartResidentProcCount);
    ```
18. ```
    ......
    ```
19. ```
    appRecord->LaunchPendingAbilities();
    ```
20. ```
    AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP\_LAUNCH, HiSysEventType::BEHAVIOR, eventInfo);
    ```
21. }
22.

*复制代码*

**2.应用初始化,通过AppRunningRecord调用LaunchApplication**应用第一次启动时,会先创建AppRunningRecord

foundation\ability\ability_runtime\services\appmgr\src\app_running_record.cpp

1. void AppRunningRecord:aunchApplication(const Configuration &config)
2. {
3. ```
   appLifeCycleDeal\_->GetApplicationClient()
   ```
4. ```
   ......
   ```
5. ```
   launchData.SetProcessInfo(processInfo);
   ```
6. ```
   launchData.SetRecordId(appRecordId\_);
   ```
7. ```
   launchData.SetUId(mainUid\_);
   ```
8. ```
   launchData.SetUserTestInfo(userTestRecord\_);
   ```
9. ```
   launchData.SetAppIndex(appIndex\_);
   ```
10. ```
    appLifeCycleDeal\_->LaunchApplication(launchData, config);
    ```
11. }
12.

*复制代码*

foundation\ability\ability_runtime\services\appmgr\src\app_lifecycle_deal.cpp

1. void AppLifeCycleDeal:aunchAbility(const std::shared\_ptr<AbilityRunningRecord> &ability)
2. {
3. ```
   appThread\_->ScheduleLaunchApplication(launchData, config);
   ```
4. }
5.

*复制代码*

处理启动应用(加载依赖库、初始化资源管理器等)等逻辑

foundation\ability\ability_runtime\frameworks\native\appkit\app\main_thread.cpp

1. void MainThread::ScheduleLaunchApplication(const AppLaunchData &data, const Configuration &config)
2. {
3. ```
   appThread->HandleLaunchApplication(data, config);
   ```
4. }
5.
6. void MainThread::HandleLaunchApplication(const AppLaunchData &data, const Configuration &config)
7. {
8. ```
   if (!InitCreate(contextDeal, appInfo, processInfo)) {
   ```
9. ```
       return;
   ```
10. ```
    }
    ```
11. ```
    if (IsNeedLoadLibrary(bundleName)) {
    ```
12. ```
        ChangeToLocalPath(bundleName, appInfo.moduleSourceDirs, localPaths);
    ```
13. ```
        LoadAbilityLibrary(localPaths);
    ```
14. ```
        LoadNativeLiabrary(bundleInfo, appInfo.nativeLibraryPath);
    ```
15. ```
    }
    ```
16. ```
    if (appInfo.needAppDetail) {
    ```
17. ```
        LoadAppDetailAbilityLibrary(appInfo.appDetailAbilityLibraryPath);
    ```
18. ```
    }
    ```
19. ```
    LoadAppLibrary();
    ```
20. ```
    if (isStageBased) {
    ```
21. ```
        AppRecovery::GetInstance().InitApplicationInfo(GetMainHandler(), GetApplicationInfo());
    ```
22. ```
    }
    ```
23. ```
    // create contextImpl
    ```
24. ```
    ......
    ```
25. ```
    if (isStageBased) {
    ```
26. ```
        // Create runtime
    ```
27. ```
        ......
    ```
28. ```
        application\_->SetRuntime(std::move(runtime));
    ```
29. ```
        AbilityLoader::GetInstance().RegisterAbility("Ability", [application = application\_]() {
    ```
30. ```
            return Ability::Create(application->GetRuntime());
    ```
31. ```
        });
    ```
32. ```
    LoadAllExtensions(jsEngine);
    ```
33. ```
    contextDeal->initResourceManager(resourceManager);
    ```
34. ```
    contextDeal->SetApplicationContext(application\_);
    ```
35. ```
    application\_->AttachBaseContext(contextDeal);
    ```
36. ```
    application\_->SetAbilityRecordMgr(abilityRecordMgr\_);
    ```
37. ```
    application\_->SetConfiguration(config);
    ```
38. ```
    contextImpl->SetConfiguration(application\_->GetConfiguration());
    ```
39.
40. ```
    applicationImpl\_->SetRecordId(appLaunchData.GetRecordId());
    ```
41. ```
    applicationImpl\_->SetApplication(application\_);
    ```
42. ```
    mainThreadState\_ = MainThreadState::READY;
    ```
43. ```
    ......
    ```
44. ```
    applicationImpl\_-&gterformAppReady()
    ```
45. ```
    nwebMgr-&gtreStartNWebSpawnProcess();
    ```
46. ```
    ......
    ```
47. ```
    // init resourceManager.
    ```
48. ```
    ......
    ```
49. }
50.

*复制代码*

**3. 通过RunningRecord调用LaunchPendingAbilities,最终创建Ability**foundation\ability\ability_runtime\services\appmgr\src/module_running_record.cpp

1. void ModuleRunningRecord:aunchPendingAbilities()
2. {
3. ```
   for (const auto &item : abilities\_) {
   ```
4. ```
       const auto &ability = item.second;
   ```
5. ```
       if (ability->GetState() == AbilityState::ABILITY\_STATE\_CREATE && ability->GetToken() &&
   ```
6. ```
           appLifeCycleDeal\_->GetApplicationClient()) {
   ```
7. ```
           appLifeCycleDeal\_->LaunchAbility(ability);
   ```
8. ```
           ability->SetState(AbilityState::ABILITY\_STATE\_READY);
   ```
9. ```
       }
   ```
10. ```
    }
    ```
11. }
12. void ModuleRunningRecord:aunchAbility(const std::shared\_ptr<AbilityRunningRecord> &ability)
13. {
14. ```
    appLifeCycleDeal\_->LaunchAbility(ability);
    ```
15. ```
    ability->SetState(AbilityState::ABILITY\_STATE\_READY);
    ```
16. }
17.

*复制代码*

通过IPC调用ScheduleLaunchAbility函数

foundation\ability\ability_runtime\services\appmgr\src/app_lifecycle_deal.cpp

1. AppLifeCycleDeal:aunchAbility(const std::shared\_ptr<AbilityRunningRecord> &ability)
2. {
3. ```
   if (appThread\_ && ability) {
   ```
4. ```
       appThread\_->ScheduleLaunchAbility(\*(ability->GetAbilityInfo()), ability->GetToken(),
   ```
5. ```
           ability->GetWant());
   ```
6. ```
   }
   ```
7. }
8.

*复制代码*

foundation\ability\ability_runtime\frameworks\native\appkit\app\main_thread.cpp

1. MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr<IRemoteObject> &token, const std::shared\_ptr[AAFwk::Want](AAFwk::Want) &want)
2. {
3. ```
   auto task = [weak, abilityRecord]() {
   ```
4. ```
       ...
   ```
5. ```
       auto appThread = weak.promote();
   ```
6. ```
       appThread->HandleLaunchAbility(abilityRecord);
   ```
7. ```
   };
   ```
8. ```
   mainHandler\_-&gtostTask(task);
   ```
9. }
10. MainThread::HandleLaunchAbility(const std::shared\_ptr<AbilityLocalRecord> &abilityRecord)
11. {
12. ```
    abilityRecordMgr\_->SetToken(abilityToken);
    ```
13. ```
    abilityRecordMgr\_->AddAbilityRecord(abilityToken, abilityRecord);
    ```
14. ```
    //创建AbilityStage
    ```
15. ```
    std::shared\_ptr<AbilityRuntime::Context> stageContext = application\_->AddAbilityStage(abilityRecord);
    ```
16. ```
    //启动Ability线程
    ```
17. ```
    AbilityThread::AbilityThreadMain(application\_, abilityRecord, stageContext);
    ```
18. }

*复制代码*

foundation\ability\ability_runtime\frameworks\native\appkit\app\ohos_application.cpp

1. bool OHOSApplication::AddAbilityStage(const AppExecFwk::HapModuleInfo &hapModuleInfo)
2. {
3. ```
    ......
   ```
4. ```
   auto stageContext = std::make\_shared<AbilityRuntime::ContextImpl>();
   ```
5. ```
   stageContext->SetParentContext(abilityRuntimeContext\_);
   ```
6. ```
   stageContext->InitHapModuleInfo(hapModuleInfo);
   ```
7. ```
   stageContext->SetConfiguration(GetConfiguration());
   ```
8. ```
   auto abilityStage = AbilityRuntime::AbilityStage::Create(runtime\_, \*moduleInfo);
   ```
9. ```
   abilityStage->Init(stageContext);
   ```
10. ```
    Want want;
    ```
11. ```
    abilityStage->OnCreate(want);
    ```
12. ```
    abilityStages\_[hapModuleInfo.moduleName] = abilityStage;
    ```
13. ```
    return true;
    ```
14. }
15.

*复制代码*

foundation\ability\ability_runtime\frameworks\native\appkit\ability_runtime\app\ability_stage.cpp

1. std::shared\_ptr<AbilityStage> AbilityStage::Create(
2. ```
   const std::unique\_ptr<Runtime>& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo)
   ```
3. {
4. ```
   ......
   ```
5. ```
   switch (runtime->GetLanguage()) {
   ```
6. ```
       case Runtime:anguage::JS:
   ```
7. ```
           return JsAbilityStage::Create(runtime, hapModuleInfo);
   ```
8. ```
       default:
   ```
9. ```
           return std::make\_shared<AbilityStage>();
   ```
10. ```
    }
    ```
11. }
12.
13. void AbilityStage::AddAbility(const sptr<IRemoteObject> &token,
14. ```
    const std::shared\_ptr<AppExecFwk::AbilityLocalRecord> &abilityRecord)
    ```
15. {
16. ```
    ......
    ```
17. ```
    abilityRecords\_[token] = abilityRecord;
    ```
18. }
19.

*复制代码*

foundation\ability\ability_runtime\frameworks\native\appkit\ability_runtime\app\ability_stage.cpp

1. td::shared\_ptr<AbilityStage> JsAbilityStage::Create(){
2. ```
   auto& jsRuntime = static\_cast<JsRuntime&>(\*runtime);
   ```
3. ```
   std::string srcPath(hapModuleInfo.name);
   ```
4. ```
   std::string moduleName(hapModuleInfo.moduleName);
   ```
5. ```
   moduleName.append("::").append("AbilityStage");
   ```
6. ```
   ......
   ```
7. ```
   //srcPath.append("/assets/js/");
   ```
8. ```
   //srcPath.append("AbilityStage.abc");
   ```
9. ```
   srcPath.append(hapModuleInfo.srcPath);
   ```
10. ```
    srcPath.append("/AbilityStage.abc");
    ```
11. ```
    auto moduleObj = jsRuntime.LoadModule(moduleName, srcPath, hapModuleInfo.hapPath,
    ```
12. ```
        hapModuleInfo.compileMode == AppExecFwk::CompileMode::ES\_MODULE, commonChunkFlag);
    ```
13. ```
    return std::make\_shared<JsAbilityStage>(jsRuntime, std::move(moduleObj));
    ```
14. }
15.
16. void JsAbilityStage::Init(const std::shared\_ptr<Context> &context)
17. {
18. ```
    AbilityStage::Init(context);
    ```
19. }
20.
21. void JsAbilityStage::OnCreate(const AAFwk::Want &want) const
22. {
23. ```
    AbilityStage::OnCreate(want);
    ```
24. ```
    ......
    ```
25. ```
    auto& nativeEngine = jsRuntime\_.GetNativeEngine();
    ```
26. ```
    NativeValue\* value = jsAbilityStageObj\_->Get();
    ```
27. ```
    nativeEngine.CallFunction(value, methodOnCreate, nullptr, 0);
    ```
28. }
29. //AbilityStage
30. void AbilityStage::Init(const std::shared\_ptr<Context>& context){
31. ```
    context\_ = context;
    ```
32. }
33. void AbilityStage::OnCreate(const AAFwk::Want &want) cons{
34. ```
    HILOG\_DEBUG("AbilityStage OnCreate come.");
    ```
35. }
36.

*复制代码*

foundation\ability\ability_runtime\frameworks\native\ability\native\ability_thread.cpp

至此,关于应用启动过程中application和ability初始化梳理清楚,OpenHarmony的源码关键Api和源码路径也都列举了出来,有疑问可自行获取源码加深理解。

四、总结-时序图
本文基于以上源码分析进行了总结,绘制了时序图,如下图所示。

![](https://forums-obs.openharmony.c ... czcdh29h28ce8vp.png)
[/md]




欢迎光临 OpenHarmony开发者论坛 (https://forums.openharmony.cn/) Powered by Discuz! X3.5