OpenHarmony——FormManager模块源代码分析 原创 精华

发布于 2022-5-20 12:53
浏览
1收藏

作者:成飞

卡片服务简介

服务卡片(以下简称“卡片”)是FA的一种界面展示形式,将FA的重要信息或操作前置到卡片,以达到服务直达,减少体验层级的目的。

基本概念

卡片提供方

服务卡片(以下简称“卡片”)是FA的一种界面展示形式,将FA的重要信息或操作前置到卡片,以达到服务直达,减少体验层级的目的。

卡片提供方是覆写了卡片相关回调函数的FormAbility。

卡片使用方

显示卡片内容的宿主应用,控制卡片在宿主中展示的位置。主要为用户开发的js,hml等前台界面。

卡片管理服务

用于管理系统中所添加卡片的常驻代理服务,包括卡片对象的管理与使用,以及卡片周期性刷新等。

说明:卡片使用方和提供方不要求常驻运行,在需要添加/删除/请求更新卡片时,卡片管理服务会拉起卡片提供方获取卡片信息

运作机制

OpenHarmony——FormManager模块源代码分析-开源基础软件社区

NAPI接口

Class API 描述
formBindingData createFormBindingData 创建一个FormBindingData对象。
FormExtension(Stage模型用) onCreate 卡片提供方接收创建卡片的通知接口。
onCastToNormal 卡片提供方接收临时卡片转常态卡片的通知接口。
onUpdate 卡片提供方接收更新卡片的通知接口。获取最新数据后调用FormExtensionContext的updateForm接口刷新卡片数据。
onVisibilityChange 卡片提供方接收修改可见性的通知接口。
onEvent 卡片提供方接收处理卡片事件的通知接口。
onDestroy 卡片提供方接收销毁卡片的通知接口。
LifecycleForm(FA模型用) onCreate 卡片提供方接收创建卡片的通知接口。
onCastToNormal 卡片提供方接收临时卡片转常态卡片的通知接口。
onUpdate 卡片提供方接收更新卡片的通知接口。
onVisibilityChange 卡片提供方接收修改可见性的通知接口。
onEvent 卡片提供方接收处理卡片事件的通知接口。
onDestroy 卡片提供方接收销毁卡片的通知接口。
onAcquireFormState 卡片提供方接收查询卡片状态的通知接口。
FormHost deleteForm 删除指定的卡片。调用此方法后,应用程序将无法使用该卡片,卡片管理器服务不再保留有关该卡片的信息。
releaseForm 释放指定的卡片。调用此方法后,应用程序将无法使用该卡片,但卡片管理器服务仍然保留有关该卡片的缓存信息和存储信息。
requestForm 请求卡片更新。
castTempForm 将指定的临时卡片转换为普通卡片。
notifyVisibleForms 向卡片框架发送通知以使指定的卡片可见。该方法调用成功后,会调用onVisibilityChange通知卡片提供方。
notifyInvisibleForms 向卡片框架发送通知以使指定的卡片不可见。该方法调用成功后,会调用onVisibilityChange通知卡片提供方
enableFormsUpdate 向卡片框架发送通知以使指定的卡片可以更新。该方法调用成功后,卡片刷新状态设置为使能,卡片可以接收来自卡片提供方的更新。
disableFormsUpdate 向卡片框架发送通知以使指定的卡片不可以更新。该方法调用成功后,卡片刷新状态设置为去使能,卡片不可以接收来自卡片提供方的更新。
isSystemReady 检查系统是否准备好。
getAllFormsInfo 获取设备上所有应用提供的卡片信息。
getFormsInfo 获取设备上指定应用程序提供的卡片信息。
deleteInvalidForms 根据列表删除应用程序的无效卡片。
acquireFormState 获取卡片状态
on(“formUninstall”) 订阅卡片卸载事件。
off(“formUninstall”) 取消订阅卡片卸载事件。
notifyFormsVisible 通知卡片是否可见。
notifyFormsEnableUpdate 通知卡片是否启用更新状态。
FormProvider setFormNextRefreshTime 设置指定卡片的下一次更新时间。
updateForm 更新指定的卡片。

接口回调时机如下图

OpenHarmony——FormManager模块源代码分析-开源基础软件社区

说明:开发者仅需作为卡片提供方进行服务卡片内容的开发,卡片使用方和卡片代理服务由系统自动处理

卡片代理服务类图

OpenHarmony——FormManager模块源代码分析-开源基础软件社区

关键类:FormMgrService是卡片代理服务的主类。处理来自卡片使用方的请求。

​ FormProviderMgr是卡片提供方的代理服务。负责连接卡片提供方的FormAbility并进行相关的回调。

​ FormMgrAdapter及FormTaskMgr负责代理服务进程内的各任务的处理。

总结:卡片使用方通过IFormMgr调用卡片代理服务(FormMgrService)的接口,代理服务进程内,通过FormMgrAdapter及FormTaskMgr处理来各请求任务,并通过卡片提供方的代理服务(FormProviderMgr)拉起卡片提供方的服务。

源码分析(以删除卡片为例)

1. 卡片使用方调用卡片代理服务的DeleteForm接口

foundation\aafwk\standard\services\formmgr\src\form_mgr_service.cpp

/**
 * @brief Delete forms with formIds, send formIds to form manager service.
 * @param formId The Id of the forms to delete.
 * @param callerToken Caller ability token.
 * @return Returns ERR_OK on success, others on failure.
 */
int FormMgrService::DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
{
    ErrCode ret = CheckFormPermission();
    if (ret != ERR_OK) {
        HILOG_ERROR("%{public}s fail, delete form permission denied", __func__);
        return ret;
    }

    return FormMgrAdapter::GetInstance().DeleteForm(formId, callerToken); //调用FormMgrAdapter的DeleteForm方法
}

foundation\aafwk\standard\services\formmgr\src\form_mgr_adapter.cpp

/**
 * @brief Delete forms with formIds, send formIds to form manager service.
 * @param formId The Id of the forms to delete.
 * @param callerToken Caller ability token.
 * @return Returns ERR_OK on success, others on failure.
 */
int FormMgrAdapter::DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
{
    if (formId <= 0 || callerToken == nullptr) {
        HILOG_ERROR("%{public}s, deleteForm invalid param", __func__);
        return ERR_APPEXECFWK_FORM_INVALID_PARAM;
    }
    int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
    if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) {
        // delete temp form if receive delete form call
        return HandleDeleteTempForm(matchedFormId, callerToken);
    }
    return HandleDeleteForm(matchedFormId, callerToken); //调用同文件中的handleDeleteForm删除Form
}

/**
 * @brief Handle delete form.
 * @param formId The form id.
 * @param callerToken Caller ability token.
 * @return Returns ERR_OK on success, others on failure.
 */
ErrCode FormMgrAdapter::HandleDeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
{
    FormRecord dbRecord;
    if (FormDbCache::GetInstance().GetDBRecord(formId, dbRecord) != ERR_OK) {
        HILOG_ERROR("%{public}s, not exist such db form:%{public}" PRId64 "", __func__, formId);
        return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
    }

    int callingUid = IPCSkeleton::GetCallingUid();
    int32_t userId = GetCurrentUserId(callingUid);
    bool isSelfDbFormId = (userId == dbRecord.userId) && ((std::find(dbRecord.formUserUids.begin(),
    dbRecord.formUserUids.end(), callingUid) != dbRecord.formUserUids.end()) ? true : false);
    if (!isSelfDbFormId) {
        HILOG_ERROR(
            "%{public}s, not self form:%{public}" PRId64 ", callingUid:%{public}d", __func__, formId, callingUid);
        return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
    }

    if (ErrCode result = HandleDeleteFormCache(dbRecord, callingUid, formId); result != ERR_OK) { //删除缓存中的卡片
        return result;
    }

    if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, formId)) {  //删除卡片使用方的记录
        HILOG_ERROR("%{public}s, failed to remove host record", __func__);
        return ERR_APPEXECFWK_FORM_COMMON_CODE;
    }

    return ERR_OK;
}
/**
 * @brief Handle delete form cache.
 * @param dbRecord Form storage information.
 * @param uid calling user id.
 * @param formId The form id.
 * @return Returns ERR_OK on success, others on failure.
 */
ErrCode FormMgrAdapter::HandleDeleteFormCache(FormRecord &dbRecord, const int uid, const int64_t formId)
{
    HILOG_DEBUG("%{public}s, delete formDBRecords, formId: %{public}" PRId64 "", __func__, formId);
    auto iter = std::find(dbRecord.formUserUids.begin(), dbRecord.formUserUids.end(), uid);
    if (iter != dbRecord.formUserUids.end()) {
        dbRecord.formUserUids.erase(iter);
    }

    ErrCode result = ERR_OK;
    if (dbRecord.formUserUids.empty()) {
        result = FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, dbRecord); //通知卡片提供方删除卡片
        if (result != ERR_OK) {
            HILOG_ERROR("%{public}s, failed to notify provider form delete", __func__);
            return result;
        }
        if (!FormDataMgr::GetInstance().DeleteFormRecord(formId)) {
            HILOG_ERROR("%{public}s, failed to remove cache data", __func__);
            return ERR_APPEXECFWK_FORM_COMMON_CODE;
        }
        if (result = FormDbCache::GetInstance().DeleteFormInfo(formId); result != ERR_OK) {
            HILOG_ERROR("%{public}s, failed to remove db data", __func__);
            return result;
        }

        int32_t matchCount = FormDbCache::GetInstance().GetMatchCount(dbRecord.bundleName, dbRecord.moduleName);
        if (matchCount == 0) {
            FormBmsHelper::GetInstance().NotifyModuleRemovable(dbRecord.bundleName, dbRecord.moduleName);
        }

        if (!FormCacheMgr::GetInstance().DeleteData(formId)) {
            HILOG_ERROR("%{public}s, failed to remove cache data", __func__);
            return ERR_APPEXECFWK_FORM_COMMON_CODE;
        }
        if (!FormTimerMgr::GetInstance().RemoveFormTimer(formId)) {
            HILOG_ERROR("%{public}s, remove timer error", __func__);
            return ERR_APPEXECFWK_FORM_COMMON_CODE;
        }
        return ERR_OK;
    }

    if (result = FormDbCache::GetInstance().UpdateDBRecord(formId, dbRecord); result != ERR_OK) {
        return result;
    }

    HILOG_DEBUG("%{public}s, dbRecord.formUserUids size: %{public}zu", __func__, dbRecord.formUserUids.size());
    FormBmsHelper::GetInstance().NotifyModuleNotRemovable(dbRecord.bundleName, dbRecord.moduleName);
    if (!FormDataMgr::GetInstance().DeleteFormUserUid(formId, uid)) {
        HILOG_ERROR("%{public}s, failed to remove form user uid", __func__);
        return ERR_APPEXECFWK_FORM_COMMON_CODE;
    }

    return result;
}
2. 卡片提供方的代理服务处理删除卡片的通知

foundation\aafwk\standard\services\formmgr\src\form_provider_mgr.cpp

/**
 * @brief Notify provider form delete.
 * @param formId The form id.
 * @param record Form information.
 * @return Function result and has other host flag.
 */
ErrCode FormProviderMgr::NotifyProviderFormDelete(const int64_t formId, const FormRecord &formRecord)
{
    if (formRecord.abilityName.empty()) {
        HILOG_ERROR("%{public}s, formRecord.abilityName is empty.", __func__);
        return ERR_APPEXECFWK_FORM_INVALID_PARAM;
    }

    if (formRecord.bundleName.empty()) {
        HILOG_ERROR("%{public}s, formRecord.bundleName is empty.", __func__);
        return ERR_APPEXECFWK_FORM_INVALID_PARAM;
    }

    HILOG_DEBUG("%{public}s, connectAbility,bundleName:%{public}s, abilityName:%{public}s",
        __func__, formRecord.bundleName.c_str(), formRecord.abilityName.c_str());
    sptr<IAbilityConnection> formDeleteConnection = new FormDeleteConnection(formId,
        formRecord.bundleName, formRecord.abilityName); //构建FormDeleteConnection的连接类
    Want want;
    want.SetElementName(formRecord.bundleName, formRecord.abilityName);
    want.SetFlags(Want::FLAG_ABILITY_FORM_ENABLED);

    ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formDeleteConnection);//fromDeleteConnection中定义connetServiceAbility的回调函数。connect之后会调用
    if (errorCode != ERR_OK) {
        HILOG_ERROR("%{public}s, ConnectServiceAbility failed.", __func__);
        return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
    }
    return ERR_OK;
}

3. 执行FormDeleteConnection连接类的回调。

foundation\aafwk\standard\services\formmgr\src\form_delete_connection.cpp 中的回调

/**
 * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect.
 * @param element service ability's ElementName.
 * @param remoteObject the session proxy of service ability.
 * @param resultCode ERR_OK on success, others on failure.
 */
void FormDeleteConnection::OnAbilityConnectDone(
    const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode)
{
    HILOG_INFO("%{public}s called.", __func__);
    if (resultCode != ERR_OK) {
        HILOG_ERROR("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d",
           __func__, element.GetAbilityName().c_str(), formId_, resultCode);
        return;
    }
    FormSupplyCallback::GetInstance()->AddConnection(this);

    Want want;
    want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId());
    HILOG_DEBUG("%{public}s, connectId :%{public}ld", __func__, this->GetConnectId());
    FormTaskMgr::GetInstance().PostDeleteTask(formId_, want, remoteObject); //调用FormTaskMgr的PostDeleteTask
}

foundation\aafwk\standard\services\formmgr\src\form_task_mgr.cpp中的 PostDeleteTask

/**
 * @brief Delete form data from form provider(task).
 * @param formId The Id of the form.
 * @param want The want of the request.
 * @param remoteObject Form provider proxy object.
 */
void FormTaskMgr::PostDeleteTask(const int64_t formId, const Want &want, const sptr<IRemoteObject> &remoteObject)
{
    if (eventHandler_ == nullptr) {
        HILOG_ERROR("%{public}s fail, eventhandler invalidate", __func__);
        return;
    }
    std::function<void()> notifyFormDeleteFunc = std::bind(&FormTaskMgr::NotifyFormDelete,
        this, formId, want, remoteObject);
    eventHandler_->PostTask(notifyFormDeleteFunc, FORM_TASK_DELAY_TIME); //压入任务NotifyFormDelete
}

foundation\aafwk\standard\services\formmgr\src\form_task_mgr.cpp的NotifyFormDelete任务

/**
 * @brief Notify form provider for delete form.
 *
 * @param formId The Id of the from.
 * @param want The want of the form.
 * @param remoteObject Form provider proxy object.
 * @return none.
 */
void FormTaskMgr::NotifyFormDelete(const int64_t formId, const Want &want, const sptr<IRemoteObject> &remoteObject)
{
    FormMgrAdapter::GetInstance().NotifyFormDelete(formId, want, remoteObject);//调用FormMgrAdapter的NotifyFormDelete函数
}

foundation\aafwk\standard\services\formmgr\src\fomr_mgr_adapter.cpp的NotifyFormDelete函数

/**
 * @brief Notify form provider for delete form.
 *
 * @param formId The Id of the from.
 * @param want The want of the form.
 * @param remoteObject Form provider proxy object.
 * @return none.
 */
void FormMgrAdapter::NotifyFormDelete(const int64_t formId, const Want &want, const sptr<IRemoteObject> &remoteObject)
{
    HILOG_INFO("%{public}s called.", __func__);

    long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0);
    sptr<IFormProvider> formProviderProxy = iface_cast<IFormProvider>(remoteObject);
    if (formProviderProxy == nullptr) {
        FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
        HILOG_ERROR("%{public}s fail, Failed to get formProviderProxy", __func__);
        return;
    }
    int error = formProviderProxy->NotifyFormDelete(formId, want, FormSupplyCallback::GetInstance()); //通过Proxy调用卡片提供方的NotifyFormDelete方法
    if (error != ERR_OK) {
        FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
        HILOG_ERROR("%{public}s fail, Failed to get acquire provider form info", __func__);
    }
}
4. 卡片提供方删除卡片(Stage模型的情况)

foundation\aafwk\standard\frameworks\kits\ability\native\src\form_runtime\form_extension_provider_client.cpp

int FormExtensionProviderClient::NotifyFormDelete(const int64_t formId, const Want &want,
    const sptr<IRemoteObject> &callerToken)
{
    HILOG_INFO("%{public}s called.", __func__);
    std::pair<int, int> errorCode = CheckParam(want, callerToken);
    if (errorCode.first != ERR_OK) {
        HILOG_ERROR("%{public}s CheckParam failed", __func__);
        return errorCode.second;
    }

    std::shared_ptr<EventHandler> mainHandler = std::make_shared<EventHandler>(EventRunner::GetMainEventRunner());
    std::function<void()> notifyFormExtensionDeleteFunc = [client = sptr<FormExtensionProviderClient>(this),
        formId, want, callerToken]() {
        client->NotifyFormExtensionDelete(formId, want, callerToken);
    };
    mainHandler->PostSyncTask(notifyFormExtensionDeleteFunc);   //压入任务NotifyFormExtensionDelete
    return ERR_OK;
}


NotifyFormExtensionDelete任务

void FormExtensionProviderClient::NotifyFormExtensionDelete(const int64_t formId, const Want &want,
    const sptr<IRemoteObject> &callerToken)
{
    HILOG_INFO("%{public}s called.", __func__);
    int errorCode = ERR_OK;
    std::shared_ptr<FormExtension> ownerFormExtension = GetOwner();
    if (ownerFormExtension == nullptr) {
        HILOG_ERROR("%{public}s error, ownerFormExtension is nullptr.", __func__);
        errorCode = ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY;
    } else {
        ownerFormExtension->OnDestroy(formId); //执行FormExtension的OnDestory
    }

    HandleResultCode(errorCode, want, callerToken);
    HILOG_INFO("%{public}s called end.", __func__);
}

用户编写的FormAbility的onDestory被调用。

export default class FormAbility extends FormExtension {
    onCreate(want) {
        Logger.log(`FormAbility onCreate, want: ${JSON.stringify(want)}`);

        // get form info
        let formId = want.parameters[FORM_PARAM_IDENTITY_KEY];
        let formName = want.parameters[FORM_PARAM_NAME_KEY];
        let tempFlag = want.parameters[FORM_PARAM_TEMPORARY_KEY];
        storeFormInfo(formId, formName, tempFlag);

        let obj = {
            "temperature": getTemperature(formId, 0).toString(),
            "time": getTime()
        };
        let formData = formBindingData.createFormBindingData(obj);
        return formData;
    }

   ....

    onDestroy(formId) {
        Logger.log(`FormAbility onDestroy, formId = ${formId}`);
        deleteFormInfo(formId);
    }

  ...
};
4. 卡片提供方删除卡片(FA模型的情况)

foundation\aafwk\standard\frameworks\kits\ability\native\src\form_provider_client.cpp

int FormExtensionProviderClient::NotifyFormDelete(const int64_t formId, const Want &want,
    const sptr<IRemoteObject> &callerToken)
{
    HILOG_INFO("%{public}s called.", __func__);
    // The error code for business operation.
    int errorCode = ERR_OK;
    do {
        HILOG_INFO("%{public}s called.", __func__);
        std::shared_ptr<Ability> ownerAbility = GetOwner();
        if (ownerAbility == nullptr) {
            HILOG_ERROR("%{public}s error, ownerAbility is nullptr.", __func__);
            errorCode = ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY;
            break;
        }
        if (!CheckIsSystemApp()) {
            HILOG_WARN("%{public}s caller permission denied", __func__);
            errorCode = ERR_APPEXECFWK_FORM_PERMISSION_DENY;
            break;
        }

        HILOG_INFO("%{public}s come, %{public}s", __func__, ownerAbility->GetAbilityName().c_str());
        ownerAbility->OnDelete(formId); // Ability的OnDelete函数被调用。
    } while (false);
   ....
}


由ace层调用用户的onDestroy方法。

foundation\ace\ace_engine\adapter\ohos\entrance\ace_form_ability.cpp

void AceFormAbility::OnDelete(const int64_t formId)
{
    LOGI("AceFormAbility::OnDelete called: %{public}s", std::to_string(formId).c_str());
    Platform::PaContainer::OnDelete(instanceId_, formId);
}

foundaton\ace\ace_engine\adapter\ohos\entrance\pa_engine\jsi\jsi_pa_engine.cpp

void JsiPaEngine::OnDelete(const int64_t formId)
{
    LOGI("JsiPaEngine OnDelete");
    ACE_DCHECK(engineInstance_);
    shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
    const std::vector<shared_ptr<JsValue>>& argv = { runtime->NewString(std::to_string(formId)) };
    auto func = GetPaFunc("onDestroy");
    CallFunc(func, argv);
}

用户的OnDestory方法被调用。

import formBindingData from '@ohos.application.formBindingData';
import formInfo from '@ohos.application.formInfo';

export default {
    onCreate(want) {
        // Called to return a FormBindingData object.
        let formData = {};
        return formBindingData.createFormBindingData(formData);
    },

   ....

    onDestroy(formId) {  //onDestory函数被调用
        // Called to notify the form provider that a specified form has been destroyed.
    },

 ....
};

命令工具(fm)

fm help

命令 描述
fm help 显示fm命令帮助信息

fm query

命令 描述
fm query -s 查询form 信息
fm query -n <bundle-name> 根据bundle name查询form信息
fm query -i <form-id> 根据form id查询form信息
示例:
fm query -n com.example.myapplication

处理fm query命令的接口及出力内容格式

命令 FormMgrService 出力内容的格式(参考FormDumpMgr类)
fm query -s DumpStorageFormInfos DumpStorageFormInfos
fm query -n <bundle-name> DumpFormInfoByBundleName DumpFormInfos
fm query -i <form-id> DumpFormInfoByFormId DumpFormInfo + DumpFormHostInfo

fm query -s 源码解析

foundation\aafwk\standard\tools\fm\src\fms_command.cpp的QueryStorageFormInfo函数

/**
 * @brief Query all of form storage infos.
 * @return Returns ERR_OK on success, others on failure.
 */
int32_t FormMgrShellCommand::QueryStorageFormInfos()
{
    HILOG_INFO("%{public}s start", __func__);

    int errCode = ConnectFms();
    if (errCode != OHOS::ERR_OK) {
        return errCode;
    }

    std::string formInfos;
    MessageParcel data;
    if (!WriteInterfaceToken(data)) {
        HILOG_ERROR("%{public}s, failed to write interface token", __func__);
        return ERR_APPEXECFWK_PARCEL_ERROR;
    }

    int result = GetStringInfo(IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS, data, formInfos); //发送FORM_MGR_STORAGE_FORM_INFOS消息给FormMgr
    if (result == ERR_OK) {
        resultReceiver_= formInfos;
    } else {
        HILOG_ERROR("'fm query' failed to query form info.");
    }
    HILOG_INFO("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str());

    return result;
}

foundation\aafwk\standard\interfaces\innerkits\form_manager\src\form_mgr_stub.cpp消息与函数映射

memberFuncMap_[static_cast<uint32_t>(IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS)] =
    &FormMgrStub::HandleDumpStorageFormInfos; 
memberFuncMap_[static_cast<uint32_t>(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_NAME)] =
   &FormMgrStub::HandleDumpFormInfoByBundleName;
memberFuncMap_[static_cast<uint32_t>(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID)] =
   &FormMgrStub::HandleDumpFormInfoByFormId;

foundation\aafwk\standard\interfaces\innerkits\form_manager\src\form_mgr_stub.cpp

/**
 * @brief Handle DumpStorageFormInfos message.
 * @param data input param.
 * @param reply output param.
 * @return Returns ERR_OK on success, others on failure.
 */
int32_t FormMgrStub::HandleDumpStorageFormInfos(MessageParcel &data, MessageParcel &reply)
{
    std::string formInfos;
    int32_t result = DumpStorageFormInfos(formInfos); //调用FormMgrService的DumpSotrageFormInfo
    reply.WriteInt32(result);
    if (result == ERR_OK) {
        std::vector<std::string> dumpInfos;
        SplitString(formInfos, dumpInfos);
        if (!reply.WriteStringVector(dumpInfos)) {
            HILOG_ERROR("%{public}s, failed to WriteStringVector<dumpInfos>", __func__);
            return ERR_APPEXECFWK_PARCEL_ERROR;
        }
    }

    return result;
}

foundation\aafwk\standard\services\formmgr\src\form_mgr_service.cpp的DumpStorageFormInfos

/**
 * @brief Dump all of form storage infos.
 * @param formInfos All of form storage infos.
 * @return Returns ERR_OK on success, others on failure.
 */
int FormMgrService::DumpStorageFormInfos(std::string &formInfos)
{
    return FormMgrAdapter::GetInstance().DumpStorageFormInfos(formInfos);//调用FormMgrAdapter的DumpStorageFormInfos
}

foundation\aafwk\standard\services\formmgr\src\form_mgr_adapter.cpp的DumpStorageFormInfos

/**
 * @brief Dump all of form storage infos.
 * @param formInfos All of form storage infos.
 * @return Returns ERR_OK on success, others on failure.
 */
int FormMgrAdapter::DumpStorageFormInfos(std::string &formInfos) const
{
    std::vector<FormDBInfo> formDBInfos;
    FormDbCache::GetInstance().GetAllFormInfo(formDBInfos);
    if (formDBInfos.size() > 0) {
        std::sort(formDBInfos.begin(), formDBInfos.end(),
        [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool {
            return formDBInfoA.formId < formDBInfoB.formId;
        });
        FormDumpMgr::GetInstance().DumpStorageFormInfos(formDBInfos, formInfos); //调用FormDumpMgr类出力信息
        return ERR_OK;
    } else {
        return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
    }
}

foundation\aafwk\standard\services\formmgr\src\form_dump_mgr.cpp的DumpStorageFormInfos

/**
 * @brief Dump all of form storage infos.
 * @param storageInfos Form storage infos
 * @param formInfos Form storage dump info.
 */
void FormDumpMgr::DumpStorageFormInfos(const std::vector<FormDBInfo> &storageInfos, std::string &formInfos) const
{
    for (const auto &info : storageInfos) {
        formInfos += "  FormId #" + std::to_string(info.formId);
        formInfos += "    formName [" + info.formName + "]";
        formInfos += "    userId [" + std::to_string(info.userId) + "]";
        formInfos += "    bundleName [" + info.bundleName + "]";
        formInfos += "    moduleName [" + info.moduleName + "]";
        formInfos += "    abilityName [" + info.abilityName + "]";
        formInfos += "    formUserUids [";
        for (auto &uId : info.formUserUids) {
            formInfos += "      Uid [" + std::to_string(uId) + "]";
        }
        formInfos += "]" + LINE_SEPARATOR;
    }
}

更多原创内容请关注:深开鸿技术团队

入门到精通、技巧到案例,系统化分享HarmonyOS开发技术,欢迎投稿和订阅,让我们一起携手前行共建鸿蒙生态。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
已于2022-6-10 12:26:55修改
1
收藏 1
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐