带你装杯带你废,带你霍霍源代码~ 大家好我是控哥,本期给大家带来的是:OpenHarmony中的ServiceManager。

intmain(int argc, char *argv[]){// 1. 创建SystemAbilityManager单例sptr<SystemAbilityManager> manager = SystemAbilityManager::GetInstance();// 2. 初始化Samgr核心模块manager->Init();// 3. 将Samgr自身注册为IPC上下文对象sptr<IRemoteObject> serv = manager->AsObject();IPCSkeleton::SetContextObject(serv);// 4. 将Samgr自己加入能力映射表(saId=0)manager->AddSamgrToAbilityMap();// 5. 设置启动完成参数SetParameter("bootevent.samgr.ready", "true");// 6. 启动DFX定时上报manager->StartDfxTimer();// 7. 进入IPC工作线程循环IPCSkeleton::JoinWorkThread();return -1;}
void SystemAbilityManager::Init(){// 1. 初始化死亡通知接收者abilityDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityDeathRecipient());systemProcessDeath_ = sptr<IRemoteObject::DeathRecipient>(new SystemProcessDeathRecipient());// ...// 2. 创建工作线程handlerworkHandler_ = make_shared<FFRTHandler>("workHandler");// 3. 创建设备状态收集管理器collectManager_ = sptr<DeviceStatusCollectManager>(new DeviceStatusCollectManager());// 4. 创建SA状态调度器abilityStateScheduler_ = std::make_shared<SystemAbilityStateScheduler>();// 5. 初始化SA配置文件(核心步骤)InitSaProfile();// 6. 创建DFX上报定时器reportEventTimer_ = std::make_unique<Utils::Timer>("DfxReporter", -1);// 7. 触发按需加载优化OndemandLoadForPerf();// 8. 注册SA状态监听器SamgrUtil::InvalidateSACache();SamgrUtil::RegisterSAListener();}
voidSystemAbilityManager::InitSaProfile(){// 1. 获取所有profile配置文件(按优先级排序)std::vector<std::string> fileNames;SamgrUtil::GetFilesByPriority(PREFIX, fileNames); // PREFIX="profile"// 2. 解析所有profile文件auto parser = std::make_shared<ParseUtil>();for (const auto& file : fileNames) {if (file.find(".json") == std::string::npos ||file.find("_trust.json") != std::string::npos) {continue;}parser->ParseSaProfiles(file); // 解析每个SA配置}// 3. 获取解析结果并初始化状态调度器std::list<SaProfile> saInfos = parser->GetAllSaProfiles();abilityStateScheduler_->Init(saInfos); // 初始化SA状态上下文collectManager_->Init(saInfos); // 初始化事件收集器// 4. 构建SA配置映射表,标记按需加载SAfor (const auto& saInfo : saInfos) {SamgrUtil::FilterCommonSaProfile(saInfo, saProfileMap_[saInfo.saId]);if (!saInfo.runOnCreate) {onDemandSaIdsSet_.insert(saInfo.saId); // 标记为按需加载}}}
bool ParseUtil::ParseSaProfiles(const string& profilePath){string realPath = GetRealPath(profilePath);if(!CheckPathExist(realPath.c_str())) {return false;}if(Endswith(realPath, ".json")) {return ParseJsonFile(realPath); // 解析JSON格式配置}return false;}
{"process": "my_service","systemability": [{"name": 1001,"libpath": "/system/lib/libmy_service.z.so","run-on-create": true,"auto-restart": true,"distributed": false,"bootphase": "BootStartPhase","start-on-demand": { ... },"stop-on-demand": { ... }}]}
字段 | 含义 |
| SA所属进程名 |
| SA ID(唯一标识) |
| SA动态库路径 |
| 是否开机自动启动 |
| 崩溃后是否自动重启 |
| 是否支持跨设备调用 |
| 启动阶段(BootStart/CoreStart/Other) |
| 按需启动触发条件 |
| 按需停止触发条件 |
void SystemAbilityStateScheduler::Init(const std::list<SaProfile>& saProfiles){// 1. 初始化进程和SA状态上下文InitStateContext(saProfiles);// 2. 创建状态机和事件处理器stateMachine_ = std::make_shared<SystemAbilityStateMachine>(listener);stateEventHandler_ = std::make_shared<SystemAbilityEventHandler>(stateMachine_);processHandler_ = std::make_shared<FFRTHandler>("ProcessHandler");}
voidSystemAbilityStateScheduler::InitStateContext(const std::list<SaProfile>& saProfiles){for (auto& saProfile : saProfiles) {// 创建进程上下文if (processContextMap_.count(saProfile.process) == 0) {auto processContext = std::make_shared<SystemProcessContext>();processContext->processName = saProfile.process;processContextMap_[saProfile.process] = processContext;}// 创建SA上下文auto abilityContext = std::make_shared<SystemAbilityContext>();abilityContext->systemAbilityId = saProfile.saId;abilityContext->isAutoRestart = saProfile.autoRestart;abilityContext->delayUnloadTime = saProfile.stopOnDemand.delayTime;abilityContext->ownProcessContext = processContextMap_[saProfile.process];abilityContextMap_[saProfile.saId] = abilityContext;}}

int32_tSystemAbilityManager::AddSystemProcess(const u16string& procName,const sptr<IRemoteObject>& procObject){// 1. 参数校验if (procName.empty() || procObject == nullptr) {return ERR_INVALID_VALUE;}// 2. 将进程加入进程映射表{lock_guard<samgr::mutex> autoLock(systemProcessMapLock_);systemProcessMap_[procName] = procObject;}// 3. 注册进程死亡通知if (systemProcessDeath_ != nullptr) {procObject->AddDeathRecipient(systemProcessDeath_);}// 4. 记录进程启动耗时int64_t duration = GetTickCount() - iterStarting->second;// 5. 通知状态调度器进程已启动ProcessInfo processInfo = {procName, callingPid, callingUid};abilityStateScheduler_->SendProcessStateEvent(processInfo,ProcessStateEvent::PROCESS_STARTED_EVENT);return ERR_OK;}
int32_tSystemAbilityManager::AddSystemAbility(int32_t systemAbilityId,const sptr<IRemoteObject>& ability, const SAExtraProp& extraProp){// 1. 参数校验if (!CheckInputSysAbilityId(systemAbilityId) || ability == nullptr) {return ERR_INVALID_VALUE;}// 2. 刷新监听器状态RefreshListenerState(systemAbilityId);// 3. 一致性校验:isDistributed必须与profile一致if (extraProp.isDistributed != IsDistributedSystemAbility(systemAbilityId)) {return ERR_INVALID_VALUE;}// 4. 将SA加入能力映射表{unique_lock<samgr::shared_mutex> writeLock(abilityMapLock_);SAInfo saInfo = { ability, extraProp.isDistributed };abilityMap_[systemAbilityId] = std::move(saInfo);}// 5. 取消加载超时检查RemoveCheckLoadedMsg(systemAbilityId);// 6. 如果是分布式SA,注册到DBinderRegisterDistribute(systemAbilityId, extraProp.isDistributed);// 7. 注册SA死亡通知if (abilityDeath_ != nullptr) {ability->AddDeathRecipient(abilityDeath_);}// 8. 更新状态调度器abilityStateScheduler_->UpdateLimitDelayUnloadTime(systemAbilityId);abilityStateScheduler_->SendAbilityStateEvent(systemAbilityId,AbilityStateEvent::ABILITY_LOAD_SUCCESS_EVENT);// 9. 通知所有订阅者SendSystemAbilityAddedMsg(systemAbilityId, ability);return ERR_OK;}

sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId){return CheckSystemAbility(systemAbilityId);}
sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId){// 1. 参数校验if (!CheckInputSysAbilityId(systemAbilityId)) {return nullptr;}// 2. 更新SA使用频率UpdateSaFreMap(IPCSkeleton::GetCallingUid(), systemAbilityId);// 3. 从abilityMap_查找shared_lock<samgr::shared_mutex> readLock(abilityMapLock_);auto iter = abilityMap_.find(systemAbilityId);if (iter != abilityMap_.end()) {return iter->second.remoteObj; // 找到直接返回}// 4. 未找到返回nullptrreturn nullptr;}
sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId, bool& isExist){if (!CheckInputSysAbilityId(systemAbilityId)) {return nullptr;}// 1. 检查是否正在卸载if (abilityStateScheduler_->IsSystemAbilityUnloading(systemAbilityId)) {return nullptr;}// 2. 先尝试直接获取sptr<IRemoteObject> abilityProxy = CheckSystemAbility(systemAbilityId);if (abilityProxy != nullptr) {isExist = true;return abilityProxy;}// 3. 如果未找到,触发按需加载abilityStateScheduler_->HandleLoadAbilityEvent(systemAbilityId, isExist);return nullptr;}
int32_t SystemAbilityStateScheduler::HandleLoadAbilityEvent(int32_t systemAbilityId, bool& isExist){std::shared_ptr<SystemAbilityContext> abilityContext;if(!GetSystemAbilityContext(systemAbilityId, abilityContext)) {isExist = false;return ERR_INVALID_VALUE;}// 检查进程状态if(abilityContext->ownProcessContext->state == SystemProcessState::NOT_STARTED) {isExist = false;return ERR_INVALID_VALUE;}// 如果进程已启动且SA未加载,触发按需加载if(abilityContext->ownProcessContext->state == SystemProcessState::STARTED &&abilityContext->state == SystemAbilityState::NOT_LOADED) {bool result = SystemAbilityManager::GetInstance()->DoLoadOnDemandAbility(systemAbilityId, isExist);if(result) {return stateMachine_->AbilityStateTransitionLocked(abilityContext,SystemAbilityState::LOADING);}}return ERR_OK;}
boolSystemAbilityManager::DoLoadOnDemandAbility(int32_t systemAbilityId, bool& isExist){// 1. 再次检查是否已存在sptr<IRemoteObject> abilityProxy = CheckSystemAbility(systemAbilityId);if (abilityProxy != nullptr) {isExist = true;return true;}// 2. 检查是否正在启动auto iter = startingAbilityMap_.find(systemAbilityId);if (iter != startingAbilityMap_.end() && iter->second.state == AbilityState::STARTING) {isExist = true;return true;}// 3. 查找按需加载映射auto onDemandIter = onDemandAbilityMap_.find(systemAbilityId);if (onDemandIter == onDemandAbilityMap_.end()) {isExist = false;return false;}// 4. 记录启动事件并启动SAauto& abilityItem = startingAbilityMap_[systemAbilityId];abilityItem.event = {INTERFACE_CALL, "get", ""};// 5. 调用启动逻辑return StartOnDemandAbilityLocked(systemAbilityId, isExist) == ERR_OK;}
int32_tSystemAbilityManager::StartOnDemandAbilityInner(const std::u16string& procName,int32_t systemAbilityId, AbilityItem& abilityItem){// 1. 获取进程的ILocalAbilityManager代理sptr<ILocalAbilityManager> procObject =iface_cast<ILocalAbilityManager>(GetSystemProcess(procName));if (procObject == nullptr) {return ERR_INVALID_VALUE;}// 2. 通过IPC调用进程内的StartAbilityprocObject->StartAbility(systemAbilityId, eventStr);// 3. 更新状态abilityItem.state = AbilityState::STARTING;return ERR_OK;}

// 服务注册单例获取sptr<IServiceRegistry> ServiceRegistry::GetInstance(){static sptr<IServiceRegistry> registryInstance;std::lock_guard<std::mutex> lock(serviceRegistryLock_);if (registryInstance == nullptr) {// 获取Samgr的IPC上下文对象sptr<IRemoteObject> registryObject = IPCSkeleton::GetContextObject();registryInstance = iface_cast<IServiceRegistry>(registryObject);}return registryInstance;}// 获取服务(带重试机制)sptr<IRemoteObject> ServiceRegistryProxy::GetService(const std::u16string& name){sptr<IRemoteObject> service = CheckService(name);if (service != nullptr) {return service;}// 最多重试10次,每次间隔1秒int32_t retry = RETRY_TIMES;while (retry--) {sleep(SLEEP_TIME);service = CheckService(name);if (service != nullptr) {return service;}}return nullptr;}
SystemAbilityManagerClient& SystemAbilityManagerClient::GetInstance(){static auto instance = new SystemAbilityManagerClient();return *instance;}sptr<ISystemAbilityManager> SystemAbilityManagerClient::GetSystemAbilityManager(){std::lock_guard<std::mutex> lock(systemAbilityManagerLock_);if (systemAbilityManager_ != nullptr) {return systemAbilityManager_;}// 获取Samgr的IPC上下文对象sptr<IRemoteObject> registryObject = IPCSkeleton::GetContextObject();systemAbilityManager_ = iface_cast<ISystemAbilityManager>(registryObject);return systemAbilityManager_;}
// 1. 获取Samgr代理sptr<ISystemAbilityManager> samgr =SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();// 2. 获取目标SA(同步阻塞方式)sptr<IRemoteObject> saProxy = samgr->GetSystemAbility(SA_ID);// 3. 转换为具体接口代理sptr<IMyService> myService = iface_cast<IMyService>(saProxy);// 4. 调用服务方法myService->DoSomething();
// 1. 实现加载回调class MyLoadCallback : public ISystemAbilityLoadCallback {voidOnLoadSystemAbilitySuccess(int32_t systemAbilityId,const sptr<IRemoteObject>& remoteObject) override {// 加载成功,使用服务}voidOnLoadSystemAbilityFail(int32_t systemAbilityId)override{// 加载失败处理}};// 2. 异步加载sptr<ISystemAbilityLoadCallback> callback = new MyLoadCallback();samgr->LoadSystemAbility(SA_ID, callback);
int32_tSystemAbilityManager::SubscribeSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityStatusChange>& listener){// 1. 参数校验if (!CheckInputSysAbilityId(systemAbilityId) || listener == nullptr) {return ERR_INVALID_VALUE;}// 2. 检查是否已订阅{lock_guard<samgr::mutex> autoLock(listenerMapLock_);auto& listeners = listenerMap_[systemAbilityId];for (const auto& itemListener : listeners) {if (listener->AsObject() == itemListener.listener->AsObject()) {return ERR_OK; // 已存在}}// 3. 检查订阅数量限制(每个进程最多256个)if (subscribeCountMap_[callingPid] >= MAX_SUBSCRIBE_COUNT) {return ERR_PERMISSION_DENIED;}// 4. 添加监听器并注册死亡通知listeners.emplace_back(listener, callingPid);listener->AsObject()->AddDeathRecipient(abilityStatusDeath_);}// 5. 如果SA已存在,立即通知CheckListenerNotify(systemAbilityId, listener);return ERR_OK;}
struct SAInfo {sptr<IRemoteObject> remoteObj; // SA的远程对象代理bool isDistributed; // 是否分布式能力};
struct SaProfile {std::u16string process; // 所属进程名int32_t saId; // SA IDstd::string libPath; // 动态库路径bool runOnCreate; // 开机自动启动bool autoRestart; // 自动重启bool distributed; // 分布式uint32_t bootPhase; // 启动阶段StartOnDemand startOnDemand; // 按需启动配置StopOnDemand stopOnDemand; // 按需停止配置// ...};
struct SystemAbilityContext {int32_t systemAbilityId; // SA IDSystemAbilityState state; // 当前状态bool isAutoRestart; // 是否自动重启int32_t delayUnloadTime; // 延迟卸载时间std::shared_ptr<SystemProcessContext> ownProcessContext; // 所属进程// ...};
enum SystemAbilityState {NOT_LOADED, // 未加载LOADING, // 加载中LOADED, // 已加载UNLOADABLE, // 可卸载(空闲)UNLOADING // 卸载中};
阶段 | 文件 | 核心函数 |
Samgr启动 | [main.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/main.cpp) |
|
核心初始化 | [system_ability_manager.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/system_ability_manager.cpp#L150-L171) |
|
配置加载 | [system_ability_manager.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/system_ability_manager.cpp#L308-L343) |
|
配置解析 | [parse_util.cpp](foundation/systemabilitymgr/samgr/services/common/src/parse_util.cpp#L235-L250) |
|
状态初始化 | [system_ability_state_scheduler.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/schedule/system_ability_state_scheduler.cpp#L102-L130) |
|
进程注册 | [system_ability_manager.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/system_ability_manager.cpp#L1096-L1137) |
|
SA注册 | [system_ability_manager.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/system_ability_manager.cpp#L1039-L1084) |
|
服务发现 | [system_ability_manager.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/system_ability_manager.cpp#L519-L536) |
|
按需加载 | [system_ability_manager.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/system_ability_manager.cpp#L735-L756) |
|
SA启动 | [system_ability_manager.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/system_ability_manager.cpp#L615-L635) |
|
服务订阅 | [system_ability_manager.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/system_ability_manager.cpp#L904-L938) |
|
客户端接口 | [service_registry.cpp](foundation/systemabilitymgr/samgr/services/samgr/native/source/service_registry.cpp#L173-L195) |
|
设计点 | 说明 |
单例模式 | SystemAbilityManager是全局单例,通过 |
IPC通信 | 基于Binder机制,Samgr作为服务端,其他进程作为客户端 |
状态机管理 | SA生命周期由SystemAbilityStateScheduler统一调度 |
按需加载 | 通过 |
死亡通知 | 注册DeathRecipient监听SA/进程死亡,自动清理资源 |
分布式支持 | 通过DBinder实现跨设备SA调用 |
并发安全 | 使用shared_mutex、lock_guard等保证线程安全 |
安卓小众宝藏 APP!灵动岛 + 流动文字表白墙,每天零钱可直接提现
灵动岛美化 安卓专属灵动常驻窗口,听歌、电量、网速等自定义样式,手机瞬间变精致,操作便利不卡顿。
全屏流动文字表白墙:三连击灵动岛可进入设置全屏滚动流动文字,不单用于告白,留联系电话、展示标语、心愿短句都适配,字体配色滚动速度随心调,摆摊、告白都好用。
无门槛赚钱提现:日常使用就能攒红包,无最低提现门槛,无提现上限,每日均可微信提现,亲测不到一个月累计微信到账 118.86 元。零碎时间买点零食,美汁儿汁儿~
实测零碎时间看广告,每小时红包预计可以拿到手5块,真实靠谱。
填写邀请码 CEAF62A3,双方解锁红包福利,我升级 VIP,你额外多拿收益。 安装包很小,下载无捆绑,感兴趣直接点链接体验:
下载入口:
https://qcnvld5ujs4p.feishu.cn/file/PwlwbwRfSoIPYlxSAfFcaAqMnmd