diff --git a/.gitattributes b/.gitattributes index 51c63e295..8b1378917 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,15 +1 @@ -*.tgz filter=lfs diff=lfs merge=lfs -text -*.trp filter=lfs diff=lfs merge=lfs -text -*.apk filter=lfs diff=lfs merge=lfs -text -*.jar filter=lfs diff=lfs merge=lfs -text -*.mp4 filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.asm filter=lfs diff=lfs merge=lfs -text -*.8svn filter=lfs diff=lfs merge=lfs -text -*.9svn filter=lfs diff=lfs merge=lfs -text -*.dylib filter=lfs diff=lfs merge=lfs -text -*.exe filter=lfs diff=lfs merge=lfs -text -*.a filter=lfs diff=lfs merge=lfs -text -*.so filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.dll filter=lfs diff=lfs merge=lfs -text + diff --git a/interfaces/innerkits/appexecfwk_base/BUILD.gn b/interfaces/innerkits/appexecfwk_base/BUILD.gn index 314eb351d..7269c8d08 100644 --- a/interfaces/innerkits/appexecfwk_base/BUILD.gn +++ b/interfaces/innerkits/appexecfwk_base/BUILD.gn @@ -33,6 +33,7 @@ ohos_shared_library("appexecfwk_base") { "src/compatible_ability_info.cpp", "src/compatible_application_info.cpp", "src/element_name.cpp", + "src/extension_info.cpp", "src/form_info.cpp", "src/form_js_info.cpp", "src/form_provider_data.cpp", diff --git a/interfaces/innerkits/appexecfwk_base/include/ability_info.h b/interfaces/innerkits/appexecfwk_base/include/ability_info.h index 977316bd9..1d0a56499 100644 --- a/interfaces/innerkits/appexecfwk_base/include/ability_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/ability_info.h @@ -208,6 +208,9 @@ struct AbilityInfo : public Parcelable { bool grantPermission = false; bool directLaunch = true; AbilitySubType subType = AbilitySubType::UNSPECIFIED; + // new version fields + std::string srcEntrance; + std::vector metadata; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; diff --git a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h index 462701942..f4066c8ca 100644 --- a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h +++ b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h @@ -117,6 +117,10 @@ enum { ERR_APPEXECFWK_RECOVER_GET_BUNDLEPATH_ERROR = APPEXECFWK_BUNDLEMGR_ERR_OFFSET + 0x0201, // 8520193 ERR_APPEXECFWK_RECOVER_INVALID_BUNDLE_NAME, + + ERR_APPEXECFWK_USER_NOT_EXIST = APPEXECFWK_BUNDLEMGR_ERR_OFFSET + 0x0301, + ERR_APPEXECFWK_USER_CREATE_FALIED, + ERR_APPEXECFWK_USER_REMOVE_FALIED, }; // Error code for FormMgr diff --git a/interfaces/innerkits/appexecfwk_base/include/extension_info.h b/interfaces/innerkits/appexecfwk_base/include/extension_info.h new file mode 100644 index 000000000..876f7aef0 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/extension_info.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_EXTENSION_INFO_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_EXTENSION_INFO_H + +#include + +#include "parcel.h" +#include "application_info.h" + +namespace OHOS { +namespace AppExecFwk { +struct ExtensionInfo { + std::string bundleName; + std::string moduleName; + std::string name; + std::string srcEntrance; + std::string icon; + int32_t iconId = 0; + std::string label; + int32_t labelId = 0; + std::string description; + int32_t descriptionId = 0; + std::string type; + std::vector permissions; + bool visible = false; + std::vector metadata; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_EXTENSION_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/include/form_info.h b/interfaces/innerkits/appexecfwk_base/include/form_info.h index 3e2fb15e8..c2cc90be9 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_info.h @@ -38,7 +38,7 @@ struct FormCustomizeData { }; struct FormWindow { - int32_t designWidth; + int32_t designWidth = 0; bool autoDesignWidth = false; }; @@ -73,6 +73,9 @@ struct FormInfo : public Parcelable { bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; static FormInfo *Unmarshalling(Parcel &parcel); + +private: + bool ReadCustomizeData(Parcel &parcel); }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/include/form_js_info.h b/interfaces/innerkits/appexecfwk_base/include/form_js_info.h index eb6d2e884..a6c71cb99 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_js_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_js_info.h @@ -19,6 +19,7 @@ #include #include "form_provider_data.h" +#include "form_info.h" #include "parcel.h" namespace OHOS { @@ -41,6 +42,12 @@ struct FormJsInfo : public Parcelable { std::string cssPath; std::string jsPath; std::string fileReousePath; + std::string formSrc; + FormWindow formWindow; + uint32_t versionCode = 0; + std::string versionName; + uint32_t compatibleVersion = 0; + std::string icon; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; diff --git a/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h b/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h index e23be6810..503a0c733 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h @@ -151,12 +151,12 @@ public: private: bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const; - + private: nlohmann::json jsonFormProviderData_; std::map, int32_t>> imageDataMap_; std::map rawImageBytesMap_; - int32_t imageDataState_; + int32_t imageDataState_ = 0; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp index 28fbcb0f7..995410084 100644 --- a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp @@ -77,6 +77,11 @@ const std::string JSON_KEY_ICON_ID = "iconId"; const std::string JSON_KEY_FORM_ENABLED = "formEnabled"; const std::string JSON_KEY_SRC_PATH = "srcPath"; const std::string JSON_KEY_SRC_LANGUAGE = "srcLanguage"; +const std::string META_DATA = "metadata"; +const std::string META_DATA_NAME = "name"; +const std::string META_DATA_VALUE = "value"; +const std::string META_DATA_RESOURCE = "resource"; +const std::string SRC_ENTRANCE = "srcEntrance"; } // namespace bool AbilityInfo::ReadFromParcel(Parcel &parcel) @@ -298,6 +303,15 @@ void to_json(nlohmann::json &jsonObject, const MetaData &metaData) }; } +void to_json(nlohmann::json &jsonObject, const Metadata &metadata) +{ + jsonObject = nlohmann::json { + {META_DATA_NAME, metadata.name}, + {META_DATA_VALUE, metadata.value}, + {META_DATA_RESOURCE, metadata.resource} + }; +} + void to_json(nlohmann::json &jsonObject, const AbilityInfo &abilityInfo) { jsonObject = nlohmann::json { @@ -345,6 +359,8 @@ void to_json(nlohmann::json &jsonObject, const AbilityInfo &abilityInfo) {JSON_KEY_LIB_PATH, abilityInfo.libPath}, {JSON_KEY_META_DATA, abilityInfo.metaData}, {JSON_KEY_FORM_ENABLED, abilityInfo.formEnabled}, + {SRC_ENTRANCE, abilityInfo.srcEntrance}, + {META_DATA, abilityInfo.metadata} }; } @@ -392,6 +408,39 @@ void from_json(const nlohmann::json &jsonObject, MetaData &metaData) ArrayType::OBJECT); } +void from_json(const nlohmann::json &jsonObject, Metadata &metadata) +{ + const auto &jsonObjectEnd = jsonObject.end(); + int32_t parseResult = ERR_OK; + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + META_DATA_NAME, + metadata.name, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + META_DATA_VALUE, + metadata.value, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + META_DATA_RESOURCE, + metadata.resource, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + if (parseResult != ERR_OK) { + APP_LOGE("read Ability Metadata from database error, error code : %{public}d", parseResult); + } +} + void from_json(const nlohmann::json &jsonObject, AbilityInfo &abilityInfo) { const auto &jsonObjectEnd = jsonObject.end(); @@ -748,6 +797,25 @@ void from_json(const nlohmann::json &jsonObject, AbilityInfo &abilityInfo) false, parseResult, ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + SRC_ENTRANCE, + abilityInfo.srcEntrance, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + META_DATA, + abilityInfo.metadata, + JsonType::ARRAY, + false, + parseResult, + ArrayType::OBJECT); + if (parseResult != ERR_OK) { + APP_LOGE("read Ability from database error, error code : %{public}d", parseResult); + } } void AbilityInfo::ConvertToCompatiableAbilityInfo(CompatibleAbilityInfo& compatibleAbilityInfo) const diff --git a/interfaces/innerkits/appexecfwk_base/src/extension_info.cpp b/interfaces/innerkits/appexecfwk_base/src/extension_info.cpp new file mode 100644 index 000000000..4c0d7590e --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/extension_info.cpp @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "extension_info.h" + +#include +#include +#include + +#include "bundle_constants.h" +#include "json_util.h" +#include "nlohmann/json.hpp" +#include "parcel_macro.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string BUNDLE_NAME = "bundleName"; +const std::string MODULE_NAME = "moduleName"; +const std::string NAME = "name"; +const std::string SRC_ENTRANCE = "srcEntrance"; +const std::string ICON = "icon"; +const std::string ICON_ID = "iconId"; +const std::string LABEL = "label"; +const std::string LABEL_ID = "labelId"; +const std::string DESCRIPTION = "description"; +const std::string DESCRIPTION_ID = "descriptionId"; +const std::string TYPE = "type"; +const std::string PERMISSIONS = "permissions"; +const std::string VISIBLE = "visible"; +const std::string META_DATA = "metadata"; +}; // namespace + +void to_json(nlohmann::json &jsonObject, const ExtensionInfo &extensionInfo) +{ + APP_LOGD("write ExtensionInfo to database"); + jsonObject = nlohmann::json { + {BUNDLE_NAME, extensionInfo.bundleName}, + {MODULE_NAME, extensionInfo.moduleName}, + {NAME, extensionInfo.name}, + {SRC_ENTRANCE, extensionInfo.srcEntrance}, + {ICON, extensionInfo.icon}, + {ICON_ID, extensionInfo.iconId}, + {LABEL, extensionInfo.label}, + {LABEL_ID, extensionInfo.labelId}, + {DESCRIPTION, extensionInfo.description}, + {DESCRIPTION_ID, extensionInfo.descriptionId}, + {TYPE, extensionInfo.type}, + {PERMISSIONS, extensionInfo.permissions}, + {VISIBLE, extensionInfo.visible}, + {META_DATA, extensionInfo.metadata} + }; +} + +void from_json(const nlohmann::json &jsonObject, ExtensionInfo &extensionInfo) +{ + APP_LOGD("read ExtensionInfo from database"); + const auto &jsonObjectEnd = jsonObject.end(); + int32_t parseResult = ERR_OK; + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + BUNDLE_NAME, + extensionInfo.bundleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + MODULE_NAME, + extensionInfo.moduleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + NAME, + extensionInfo.name, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + SRC_ENTRANCE, + extensionInfo.srcEntrance, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + ICON, + extensionInfo.icon, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + ICON_ID, + extensionInfo.iconId, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + LABEL, + extensionInfo.label, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + LABEL_ID, + extensionInfo.labelId, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + DESCRIPTION, + extensionInfo.description, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + DESCRIPTION_ID, + extensionInfo.descriptionId, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + TYPE, + extensionInfo.type, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + PERMISSIONS, + extensionInfo.permissions, + JsonType::ARRAY, + false, + parseResult, + ArrayType::STRING); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + VISIBLE, + extensionInfo.visible, + JsonType::BOOLEAN, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + META_DATA, + extensionInfo.metadata, + JsonType::ARRAY, + false, + parseResult, + ArrayType::OBJECT); + if (parseResult != ERR_OK) { + APP_LOGE("read ExtensionInfo from database error, error code : %{public}d", parseResult); + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp index eee27bb63..34774b156 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp @@ -15,17 +15,17 @@ #include "form_info.h" +#include #include +#include #include -#include -#include + +#include "app_log_wrapper.h" +#include "bundle_constants.h" #include "json_serializer.h" #include "nlohmann/json.hpp" -#include "string_ex.h" #include "parcel_macro.h" -#include "app_log_wrapper.h" -#include "nlohmann/json.hpp" -#include "bundle_constants.h" +#include "string_ex.h" namespace OHOS { namespace AppExecFwk { @@ -125,7 +125,10 @@ bool FormInfo::ReadFromParcel(Parcel &parcel) portraitLayouts.emplace_back(Str16ToStr8(parcel.ReadString16())); } - ReadFromParcelCustomizeData(customizeDatas, parcel); + if (!ReadCustomizeData(parcel)) { + return false; + } + window.designWidth = parcel.ReadInt32(); window.autoDesignWidth = parcel.ReadBool(); return true; @@ -200,7 +203,7 @@ void to_json(nlohmann::json &jsonObject, const FormCustomizeData &customizeDatas jsonObject = nlohmann::json{ {JSON_KEY_NAME, customizeDatas.name}, {JSON_KEY_VALUE, customizeDatas.value} - }; + }; } void to_json(nlohmann::json &jsonObject, const FormWindow &formWindow) diff --git a/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp index 0b02ae316..14fa30ff8 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp @@ -29,6 +29,15 @@ bool FormJsInfo::ReadFromParcel(Parcel &parcel) jsFormCodePath = Str16ToStr8(parcel.ReadString16()); formData = Str16ToStr8(parcel.ReadString16()); + formSrc = Str16ToStr8(parcel.ReadString16()); + formWindow.designWidth = parcel.ReadInt32(); + formWindow.autoDesignWidth = parcel.ReadBool(); + + versionCode = parcel.ReadUint32(); + versionName = Str16ToStr8(parcel.ReadString16()); + compatibleVersion = parcel.ReadUint32(); + icon = Str16ToStr8(parcel.ReadString16()); + auto bindingData = parcel.ReadParcelable(); if (nullptr == bindingData){ return false; @@ -80,6 +89,35 @@ bool FormJsInfo::Marshalling(Parcel &parcel) const return false; } + // write formSrc + if (!parcel.WriteString16(Str8ToStr16(formSrc))) { + return false; + } + + // write formWindow + if (!parcel.WriteInt32(formWindow.designWidth)) { + return false; + } + if (!parcel.WriteBool(formWindow.autoDesignWidth)) { + return false; + } + + // write version + if (!parcel.WriteUint32(versionCode)) { + return false; + } + if (!parcel.WriteString16(Str8ToStr16(versionName))) { + return false; + } + if (!parcel.WriteUint32(compatibleVersion)) { + return false; + } + + // write icon + if (!parcel.WriteString16(Str8ToStr16(icon))) { + return false; + } + // write formProviderData if (!parcel.WriteParcelable(&formProviderData)) { return false; diff --git a/interfaces/innerkits/appexecfwk_core/BUILD.gn b/interfaces/innerkits/appexecfwk_core/BUILD.gn index 9b357ecd6..83004cca8 100644 --- a/interfaces/innerkits/appexecfwk_core/BUILD.gn +++ b/interfaces/innerkits/appexecfwk_core/BUILD.gn @@ -44,6 +44,7 @@ ohos_shared_library("appexecfwk_core") { ] sources = [ + "src/appmgr/ability_state_data.cpp", "src/appmgr/ams_mgr_proxy.cpp", "src/appmgr/ams_mgr_stub.cpp", "src/appmgr/app_launch_data.cpp", @@ -58,9 +59,13 @@ ohos_shared_library("appexecfwk_core") { "src/appmgr/app_service_manager.cpp", "src/appmgr/app_state_callback_host.cpp", "src/appmgr/app_state_callback_proxy.cpp", + "src/appmgr/app_state_data.cpp", "src/appmgr/app_task_info.cpp", "src/appmgr/configuration.cpp", + "src/appmgr/application_state_observer_proxy.cpp", + "src/appmgr/application_state_observer_stub.cpp", "src/appmgr/priority_object.cpp", + "src/appmgr/process_data.cpp", "src/appmgr/process_info.cpp", "src/appmgr/profile.cpp", "src/bundlemgr/bundle_installer_proxy.cpp", diff --git a/interfaces/innerkits/appexecfwk_core/appexecfwk_headers.gni b/interfaces/innerkits/appexecfwk_core/appexecfwk_headers.gni index 0be383b05..220c197d0 100644 --- a/interfaces/innerkits/appexecfwk_core/appexecfwk_headers.gni +++ b/interfaces/innerkits/appexecfwk_core/appexecfwk_headers.gni @@ -17,6 +17,8 @@ appexecfwk_headers = { "appmgr/iapp_state_callback.h", "appmgr/app_state_callback_host.h", "appmgr/app_mgr_constants.h", + "appmgr/iapplication_state_observer.h", + "appmgr/application_state_observer_stub.h", "bundlemgr/bundle_installer_interface.h", "bundlemgr/bundle_mgr_interface.h", "bundlemgr/bundle_status_callback_interface.h", diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/ability_state_data.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/ability_state_data.h new file mode 100644 index 000000000..742d8b09a --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/ability_state_data.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_STATE_DATA_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_STATE_DATA_H + +#include + +#include "parcel.h" + +#include "app_mgr_constants.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +struct AbilityStateData : public Parcelable { + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static AbilityStateData *Unmarshalling(Parcel &parcel); + + std::string bundleName; + std::string abilityName; + int32_t abilityState = 0; + pid_t pid = 0; + int32_t uid = 0; + sptr token; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_STATE_DATA_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_interface.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_interface.h index 292360be2..59903aaf4 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_interface.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_interface.h @@ -59,6 +59,15 @@ public: */ virtual void UpdateAbilityState(const sptr &token, const AbilityState state) = 0; + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state) = 0; + /** * RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback. * @@ -134,6 +143,7 @@ public: LOAD_ABILITY = 0, TERMINATE_ABILITY, UPDATE_ABILITY_STATE, + UPDATE_EXTENSION_STATE, REGISTER_APP_STATE_CALLBACK, RESET, ABILITY_BEHAVIOR_ANALYSIS, diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_proxy.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_proxy.h index 1182d8257..7650b1596 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_proxy.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_proxy.h @@ -56,6 +56,15 @@ public: */ virtual void UpdateAbilityState(const sptr &token, const AbilityState state) override; + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state) override; + /** * RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback. * diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_stub.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_stub.h index 5d4123a11..493625502 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_stub.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_stub.h @@ -33,10 +33,19 @@ public: virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state) override; private: int32_t HandleLoadAbility(MessageParcel &data, MessageParcel &reply); int32_t HandleTerminateAbility(MessageParcel &data, MessageParcel &reply); int32_t HandleUpdateAbilityState(MessageParcel &data, MessageParcel &reply); + int32_t HandleUpdateExtensionState(MessageParcel &data, MessageParcel &reply); int32_t HandleRegisterAppStateCallback(MessageParcel &data, MessageParcel &reply); int32_t HandleReset(MessageParcel &data, MessageParcel &reply); int32_t HandleAbilityBehaviorAnalysis(MessageParcel &data, MessageParcel &reply); diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_client.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_client.h index d8a60d0a9..6c4db9280 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_client.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_client.h @@ -64,6 +64,15 @@ public: */ virtual AppMgrResultCode UpdateAbilityState(const sptr &token, const AbilityState state); + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual AppMgrResultCode UpdateExtensionState(const sptr &token, const ExtensionState state); + /** * Register Application state callback. * diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h index a23c835dc..41a79a0f0 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h @@ -44,6 +44,14 @@ enum class AbilityState { ABILITY_STATE_END, }; +enum class ExtensionState { + EXTENSION_STATE_CREATE = 0, + EXTENSION_STATE_READY, + EXTENSION_STATE_CONNECTED, + EXTENSION_STATE_DISCONNECTED, + EXTENSION_STATE_TERMINATED, +}; + enum AppMgrResultCode { RESULT_OK = 0, ERROR_SERVICE_NOT_READY, diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_interface.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_interface.h index b5d357d54..ad422e7af 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_interface.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_interface.h @@ -26,6 +26,7 @@ #include "ams_mgr_interface.h" #include "running_process_info.h" #include "system_memory_attr.h" +#include "iapplication_state_observer.h" namespace OHOS { namespace AppExecFwk { @@ -155,6 +156,27 @@ public: */ virtual void StartupResidentProcess() = 0; + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t RegisterApplicationStateObserver(const sptr &observer) = 0; + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) = 0; + + /** + * Get foreground applications. + * @param list, foreground apps. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetForegroundApplications(std::vector &list) = 0; + enum class Message { APP_ATTACH_APPLICATION = 0, APP_APPLICATION_FOREGROUNDED, @@ -171,6 +193,9 @@ public: APP_GET_SYSTEM_MEMORY_ATTR, APP_ADD_ABILITY_STAGE_INFO_DONE, STARTUP_RESIDENT_PROCESS, + REGISTER_APPLICATION_STATE_OBSERVER, + UNREGISTER_APPLICATION_STATE_OBSERVER, + GET_FOREGROUND_APPLICATIONS, }; }; } // namespace AppExecFwk diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_proxy.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_proxy.h index 5adbb893a..452c34dd4 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_proxy.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_proxy.h @@ -149,6 +149,27 @@ public: */ virtual void StartupResidentProcess() override; + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t RegisterApplicationStateObserver(const sptr &observer) override; + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) override; + + /** + * Get foreground applications. + * @param list, foreground apps. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetForegroundApplications(std::vector &list) override; + private: bool SendTransactCmd(IAppMgr::Message code, MessageParcel &data, MessageParcel &reply); bool WriteInterfaceToken(MessageParcel &data); diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_stub.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_stub.h index 33de6259f..5376be22d 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_stub.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_stub.h @@ -33,6 +33,27 @@ public: virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t RegisterApplicationStateObserver(const sptr &observer) override; + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) override; + + /** + * Get foreground applications. + * @param list, foreground apps. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetForegroundApplications(std::vector &list) override; + private: int32_t HandleAttachApplication(MessageParcel &data, MessageParcel &reply); int32_t HandleApplicationForegrounded(MessageParcel &data, MessageParcel &reply); @@ -49,6 +70,9 @@ private: int32_t HandleGetSystemMemoryAttr(MessageParcel &data, MessageParcel &reply); int32_t HandleAddAbilityStageDone(MessageParcel &data, MessageParcel &reply); int32_t HandleStartupResidentProcess(MessageParcel &data, MessageParcel &reply); + int32_t HandleRegisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply); + int32_t HandleUnregisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetForegroundApplications(MessageParcel &data, MessageParcel &reply); using AppMgrFunc = int32_t (AppMgrStub::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_data.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_data.h new file mode 100644 index 000000000..15b26f765 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_data.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_DATA_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_DATA_H + +#include + +#include "parcel.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +struct AppStateData : public Parcelable { + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static AppStateData *Unmarshalling(Parcel &parcel); + + std::string bundleName; + int32_t uid = 0; + int32_t state = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_DATA_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/application_state_observer_proxy.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/application_state_observer_proxy.h new file mode 100644 index 000000000..a54e2d0e8 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/application_state_observer_proxy.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_PROXY_H + +#include "iremote_proxy.h" + +#include "app_mgr_constants.h" +#include "iapplication_state_observer.h" + +namespace OHOS { +namespace AppExecFwk { +class ApplicationStateObserverProxy : public IRemoteProxy { +public: + explicit ApplicationStateObserverProxy(const sptr &impl); + virtual ~ApplicationStateObserverProxy() = default; + + /** + * Application foreground state changed callback. + * + * @param appStateData Application Process data. + */ + virtual void OnForegroundApplicationChanged(const AppStateData &appStateData) override; + + /** + * Will be called when the ability state changes. + * + * @param abilityStateData Ability state data. + */ + virtual void OnAbilityStateChanged(const AbilityStateData &abilityStateData) override; + + /** + * Will be called when the extension state changes. + * + * @param abilityStateData Extension state data. + */ + virtual void OnExtensionStateChanged(const AbilityStateData &abilityStateData) override; + + /** + * Will be called when the process start. + * + * @param processData Process data. + */ + virtual void OnProcessCreated(const ProcessData &processData) override; + + /** + * Will be called when the process die. + * + * @param processData Process data. + */ + virtual void OnProcessDied(const ProcessData &processData) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/application_state_observer_stub.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/application_state_observer_stub.h new file mode 100644 index 000000000..ff20b9fed --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/application_state_observer_stub.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_STUB_H + +#include + +#include "iremote_stub.h" +#include "nocopyable.h" +#include "string_ex.h" +#include "app_mgr_constants.h" +#include "iapplication_state_observer.h" + +namespace OHOS { +namespace AppExecFwk { +class ApplicationStateObserverStub : public IRemoteStub { +public: + ApplicationStateObserverStub(); + virtual ~ApplicationStateObserverStub(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + /** + * Application foreground state changed callback. + * + * @param appStateData Application Process data. + */ + virtual void OnForegroundApplicationChanged(const AppStateData &appStateData) override; + + /** + * Will be called when the ability state changes. + * + * @param abilityStateData Ability state data. + */ + virtual void OnAbilityStateChanged(const AbilityStateData &abilityStateData) override; + + /** + * Will be called when the extension state changes. + * + * @param abilityStateData Extension state data. + */ + virtual void OnExtensionStateChanged(const AbilityStateData &abilityStateData) override; + + /** + * Will be called when the process start. + * + * @param processData Process data. + */ + virtual void OnProcessCreated(const ProcessData &processData) override; + + /** + * Will be called when the process die. + * + * @param processData Process data. + */ + virtual void OnProcessDied(const ProcessData &processData) override; + +private: + int32_t HandleOnForegroundApplicationChanged(MessageParcel &data, MessageParcel &reply); + + int32_t HandleOnAbilityStateChanged(MessageParcel &data, MessageParcel &reply); + + int32_t HandleOnExtensionStateChanged(MessageParcel &data, MessageParcel &reply); + + int32_t HandleOnProcessCreated(MessageParcel &data, MessageParcel &reply); + + int32_t HandleOnProcessDied(MessageParcel &data, MessageParcel &reply); + + using ApplicationStateObserverFunc = int32_t (ApplicationStateObserverStub::*)(MessageParcel &data, + MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(ApplicationStateObserverStub); +}; + +/** + * @class ApplicationStateObserverRecipient + * ApplicationStateObserverRecipient notices IRemoteBroker died. + */ +class ApplicationStateObserverRecipient : public IRemoteObject::DeathRecipient { +public: + using RemoteDiedHandler = std::function &)>; + ApplicationStateObserverRecipient(RemoteDiedHandler handler); + virtual ~ApplicationStateObserverRecipient(); + virtual void OnRemoteDied(const wptr &remote); + +private: + RemoteDiedHandler handler_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_STUB_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/iapplication_state_observer.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/iapplication_state_observer.h new file mode 100644 index 000000000..7e8a6a5c8 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/iapplication_state_observer.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPPLICATION_STATE_OBSERVER_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPPLICATION_STATE_OBSERVER_H + +#include "ability_state_data.h" +#include "app_state_data.h" +#include "process_data.h" +#include "iremote_broker.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +class IApplicationStateObserver : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.IApplicationStateObserver"); + + /** + * Application foreground state changed callback. + * + * @param appStateData Application state data. + */ + virtual void OnForegroundApplicationChanged(const AppStateData &appStateData) = 0; + + /** + * Will be called when the ability state changes. + * + * @param abilityStateData Ability state data. + */ + virtual void OnAbilityStateChanged(const AbilityStateData &abilityStateData) = 0; + + /** + * Will be called when the extension state changes. + * + * @param abilityStateData Extension state data. + */ + virtual void OnExtensionStateChanged(const AbilityStateData &abilityStateData) = 0; + + /** + * Will be called when the process start. + * + * @param processData Process data. + */ + virtual void OnProcessCreated(const ProcessData &processData) = 0; + + /** + * Will be called when the process die. + * + * @param processData Process data. + */ + virtual void OnProcessDied(const ProcessData &processData) = 0; + + enum class Message { + TRANSACT_ON_FOREGROUND_APPLICATION_CHANGED = 0, + TRANSACT_ON_ABILITY_STATE_CHANGED, + TRANSACT_ON_EXTENSION_STATE_CHANGED, + TRANSACT_ON_PROCESS_CREATED, + TRANSACT_ON_PROCESS_DIED, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPPLICATION_STATE_OBSERVER_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/process_data.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/process_data.h new file mode 100644 index 000000000..8122c2be2 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/process_data.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_STATE_DATA_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_STATE_DATA_H + +#include + +#include "parcel.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +struct ProcessData : public Parcelable { + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static ProcessData *Unmarshalling(Parcel &parcel); + + std::string bundleName; + int32_t pid = 0; + int32_t uid = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_STATE_DATA_H diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/ability_state_data.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/ability_state_data.cpp new file mode 100644 index 000000000..5dd13b6e2 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/ability_state_data.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ability_state_data.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +bool AbilityStateData::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteString(bundleName) && parcel.WriteString(abilityName) && + parcel.WriteInt32(abilityState) && + parcel.WriteInt32(pid) && parcel.WriteInt32(uid) && parcel.WriteParcelable(token)); +} + +bool AbilityStateData::ReadFromParcel(Parcel &parcel) +{ + bundleName = parcel.ReadString(); + + abilityName = parcel.ReadString(); + + abilityState = parcel.ReadInt32(); + + pid = parcel.ReadInt32(); + + uid = parcel.ReadInt32(); + + token = parcel.ReadParcelable(); + + return true; +} + +AbilityStateData *AbilityStateData::Unmarshalling(Parcel &parcel) +{ + AbilityStateData *abilityStateData = new (std::nothrow) AbilityStateData(); + if (abilityStateData && !abilityStateData->ReadFromParcel(parcel)) { + APP_LOGW("AbilityStateData failed, because ReadFromParcel failed"); + delete abilityStateData; + abilityStateData = nullptr; + } + return abilityStateData; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp index e95c55565..23cb1c93b 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp @@ -113,6 +113,30 @@ void AmsMgrProxy::UpdateAbilityState(const sptr &token, const Abi APP_LOGD("end"); } +void AmsMgrProxy::UpdateExtensionState(const sptr &token, const ExtensionState state) +{ + APP_LOGD("UpdateExtensionState start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + data.WriteInt32(static_cast(state)); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::UPDATE_EXTENSION_STATE), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + void AmsMgrProxy::RegisterAppStateCallback(const sptr &callback) { APP_LOGD("start"); diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp index 371e55817..75dc5d6d9 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp @@ -36,6 +36,8 @@ AmsMgrStub::AmsMgrStub() &AmsMgrStub::HandleTerminateAbility; memberFuncMap_[static_cast(IAmsMgr::Message::UPDATE_ABILITY_STATE)] = &AmsMgrStub::HandleUpdateAbilityState; + memberFuncMap_[static_cast(IAmsMgr::Message::UPDATE_EXTENSION_STATE)] = + &AmsMgrStub::HandleUpdateExtensionState; memberFuncMap_[static_cast(IAmsMgr::Message::REGISTER_APP_STATE_CALLBACK)] = &AmsMgrStub::HandleRegisterAppStateCallback; memberFuncMap_[static_cast(IAmsMgr::Message::RESET)] = &AmsMgrStub::HandleReset; @@ -117,6 +119,14 @@ ErrCode AmsMgrStub::HandleUpdateAbilityState(MessageParcel &data, MessageParcel return NO_ERROR; } +ErrCode AmsMgrStub::HandleUpdateExtensionState(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadParcelable(); + int32_t state = data.ReadInt32(); + UpdateExtensionState(token, static_cast(state)); + return NO_ERROR; +} + ErrCode AmsMgrStub::HandleRegisterAppStateCallback(MessageParcel &data, MessageParcel &reply) { BYTRACE(BYTRACE_TAG_APP); @@ -201,5 +211,8 @@ int32_t AmsMgrStub::HandlePrepareTerminate(MessageParcel &data, MessageParcel &r PrepareTerminate(token); return NO_ERROR; } + +void AmsMgrStub::UpdateExtensionState(const sptr &token, const ExtensionState state) +{} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp index 198006e7e..f2ae28cfa 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp @@ -79,6 +79,19 @@ AppMgrResultCode AppMgrClient::UpdateAbilityState(const sptr &tok return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; } +AppMgrResultCode AppMgrClient::UpdateExtensionState(const sptr &token, const ExtensionState state) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->UpdateExtensionState(token, state); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + AppMgrResultCode AppMgrClient::RegisterAppStateCallback(const sptr &callback) { sptr service = iface_cast(remote_); diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_proxy.cpp index 4c7aee19d..c6c297b91 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_proxy.cpp @@ -421,5 +421,80 @@ int AppMgrProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcel APP_LOGD("get parcelable infos success"); return NO_ERROR; } + +int AppMgrProxy::RegisterApplicationStateObserver( + const sptr &observer) +{ + APP_LOGD("RegisterApplicationStateObserver start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteParcelable(observer->AsObject())) { + APP_LOGE("observer write failed."); + return ERR_FLATTEN_OBJECT; + } + + auto error = Remote()->SendRequest(static_cast(IAppMgr::Message::REGISTER_APPLICATION_STATE_OBSERVER), + data, reply, option); + if (error != NO_ERROR) { + APP_LOGE("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AppMgrProxy::UnregisterApplicationStateObserver( + const sptr &observer) +{ + APP_LOGD("UnregisterApplicationStateObserver start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteParcelable(observer->AsObject())) { + APP_LOGE("observer write failed."); + return ERR_FLATTEN_OBJECT; + } + + auto error = Remote()->SendRequest(static_cast(IAppMgr::Message::UNREGISTER_APPLICATION_STATE_OBSERVER), + data, reply, option); + if (error != NO_ERROR) { + APP_LOGE("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AppMgrProxy::GetForegroundApplications(std::vector &list) +{ + APP_LOGD("GetForegroundApplications start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + auto error = Remote()->SendRequest(static_cast(IAppMgr::Message::GET_FOREGROUND_APPLICATIONS), + data, reply, option); + if (error != NO_ERROR) { + APP_LOGE("GetForegroundApplications fail, error: %{public}d", error); + return error; + } + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("Read Parcelable infos failed."); + return ERR_INVALID_VALUE; + } + list.emplace_back(*info); + } + return reply.ReadInt32(); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp index 97b54695c..0b04e37e5 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp @@ -60,6 +60,12 @@ AppMgrStub::AppMgrStub() &AppMgrStub::HandleAddAbilityStageDone; memberFuncMap_[static_cast(IAppMgr::Message::STARTUP_RESIDENT_PROCESS)] = &AppMgrStub::HandleStartupResidentProcess; + memberFuncMap_[static_cast(IAppMgr::Message::REGISTER_APPLICATION_STATE_OBSERVER)] = + &AppMgrStub::HandleRegisterApplicationStateObserver; + memberFuncMap_[static_cast(IAppMgr::Message::UNREGISTER_APPLICATION_STATE_OBSERVER)] = + &AppMgrStub::HandleUnregisterApplicationStateObserver; + memberFuncMap_[static_cast(IAppMgr::Message::GET_FOREGROUND_APPLICATIONS)] = + &AppMgrStub::HandleGetForegroundApplications; } AppMgrStub::~AppMgrStub() @@ -231,5 +237,53 @@ int32_t AppMgrStub::HandleStartupResidentProcess(MessageParcel &data, MessagePar StartupResidentProcess(); return NO_ERROR; } + +int32_t AppMgrStub::HandleRegisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply) +{ + auto callback = iface_cast(data.ReadParcelable()); + int32_t result = RegisterApplicationStateObserver(callback); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleUnregisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply) +{ + auto callback = iface_cast(data.ReadParcelable()); + int32_t result = UnregisterApplicationStateObserver(callback); + reply.WriteInt32(result); + return NO_ERROR; +} + + +int32_t AppMgrStub::HandleGetForegroundApplications(MessageParcel &data, MessageParcel &reply) +{ + std::vector appStateDatas; + int32_t result = GetForegroundApplications(appStateDatas); + reply.WriteInt32(appStateDatas.size()); + for (auto &it : appStateDatas) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return result; +} + +int32_t AppMgrStub::RegisterApplicationStateObserver(const sptr &observer) +{ + return NO_ERROR; +} + +int32_t AppMgrStub::UnregisterApplicationStateObserver(const sptr &observer) +{ + return NO_ERROR; +} + +int32_t AppMgrStub::GetForegroundApplications(std::vector &list) +{ + return NO_ERROR; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_data.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_data.cpp new file mode 100644 index 000000000..c32eb0f89 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_data.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_state_data.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +bool AppStateData::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteString(bundleName) && parcel.WriteInt32(uid) && parcel.WriteInt32(state)); +} + +bool AppStateData::ReadFromParcel(Parcel &parcel) +{ + bundleName = parcel.ReadString(); + uid = parcel.ReadInt32(); + state = parcel.ReadInt32(); + + return true; +} + +AppStateData *AppStateData::Unmarshalling(Parcel &parcel) +{ + AppStateData *appStateData = new (std::nothrow) AppStateData(); + if (appStateData && !appStateData->ReadFromParcel(parcel)) { + APP_LOGW("appStateData failed, because ReadFromParcel failed"); + delete appStateData; + appStateData = nullptr; + } + return appStateData; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/application_state_observer_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/application_state_observer_proxy.cpp new file mode 100644 index 000000000..b6e489f96 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/application_state_observer_proxy.cpp @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "application_state_observer_proxy.h" + +#include "ipc_types.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +ApplicationStateObserverProxy::ApplicationStateObserverProxy( + const sptr &impl) : IRemoteProxy(impl) +{} + +bool ApplicationStateObserverProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(ApplicationStateObserverProxy::GetDescriptor())) { + APP_LOGE("write interface token failed"); + return false; + } + return true; +} + +void ApplicationStateObserverProxy::OnForegroundApplicationChanged(const AppStateData &appStateData) +{ + APP_LOGD("begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&appStateData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_FOREGROUND_APPLICATION_CHANGED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void ApplicationStateObserverProxy::OnAbilityStateChanged(const AbilityStateData &abilityStateData) +{ + APP_LOGD("OnAbilityStateChanged begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&abilityStateData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_ABILITY_STATE_CHANGED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void ApplicationStateObserverProxy::OnExtensionStateChanged(const AbilityStateData &abilityStateData) +{ + APP_LOGD("OnExtensionStateChanged begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&abilityStateData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_EXTENSION_STATE_CHANGED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void ApplicationStateObserverProxy::OnProcessCreated(const ProcessData &processData) +{ + APP_LOGD("begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&processData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_PROCESS_CREATED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void ApplicationStateObserverProxy::OnProcessDied(const ProcessData &processData) +{ + APP_LOGD("begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&processData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_PROCESS_DIED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/application_state_observer_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/application_state_observer_stub.cpp new file mode 100644 index 000000000..4a94a2874 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/application_state_observer_stub.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "application_state_observer_stub.h" +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { + +ApplicationStateObserverStub::ApplicationStateObserverStub() +{ + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_FOREGROUND_APPLICATION_CHANGED)] = + &ApplicationStateObserverStub::HandleOnForegroundApplicationChanged; + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_ABILITY_STATE_CHANGED)] = + &ApplicationStateObserverStub::HandleOnAbilityStateChanged; + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_EXTENSION_STATE_CHANGED)] = + &ApplicationStateObserverStub::HandleOnExtensionStateChanged; + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_PROCESS_CREATED)] = + &ApplicationStateObserverStub::HandleOnProcessCreated; + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_PROCESS_DIED)] = + &ApplicationStateObserverStub::HandleOnProcessDied; +} + +ApplicationStateObserverStub::~ApplicationStateObserverStub() +{ + memberFuncMap_.clear(); +} + +int ApplicationStateObserverStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("ApplicationStateObserverStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = ApplicationStateObserverStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +void ApplicationStateObserverStub::OnForegroundApplicationChanged(const AppStateData &appStateData) +{} + +void ApplicationStateObserverStub::OnAbilityStateChanged(const AbilityStateData &abilityStateData) +{} + +void ApplicationStateObserverStub::OnExtensionStateChanged(const AbilityStateData &abilityStateData) +{} + +void ApplicationStateObserverStub::OnProcessCreated(const ProcessData &processData) +{} + +void ApplicationStateObserverStub::OnProcessDied(const ProcessData &processData) +{} + +int32_t ApplicationStateObserverStub::HandleOnForegroundApplicationChanged(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr processData(data.ReadParcelable()); + if (!processData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnForegroundApplicationChanged(*processData); + return NO_ERROR; +} + +int32_t ApplicationStateObserverStub::HandleOnAbilityStateChanged(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr abilityStateData(data.ReadParcelable()); + if (!abilityStateData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnAbilityStateChanged(*abilityStateData); + return NO_ERROR; +} + +int32_t ApplicationStateObserverStub::HandleOnExtensionStateChanged(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr abilityStateData(data.ReadParcelable()); + if (!abilityStateData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnExtensionStateChanged(*abilityStateData); + return NO_ERROR; +} + +int32_t ApplicationStateObserverStub::HandleOnProcessCreated(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr processData(data.ReadParcelable()); + if (!processData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnProcessCreated(*processData); + return NO_ERROR; +} + +int32_t ApplicationStateObserverStub::HandleOnProcessDied(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr processData(data.ReadParcelable()); + if (!processData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnProcessDied(*processData); + return NO_ERROR; +} + +void ApplicationStateObserverRecipient::OnRemoteDied(const wptr &__attribute__((unused)) remote) +{ + APP_LOGE("ApplicationStateObserverRecipient On remote died."); + if (handler_) { + handler_(remote); + } +} + +ApplicationStateObserverRecipient::ApplicationStateObserverRecipient(RemoteDiedHandler handler) : handler_(handler) +{} + +ApplicationStateObserverRecipient::~ApplicationStateObserverRecipient() +{} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/process_data.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/process_data.cpp new file mode 100644 index 000000000..d44edbf0e --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/process_data.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "process_data.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +bool ProcessData::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteString(bundleName) && parcel.WriteInt32(pid) && parcel.WriteInt32(uid)); +} + +bool ProcessData::ReadFromParcel(Parcel &parcel) +{ + bundleName = parcel.ReadString(); + pid = parcel.ReadInt32(); + uid = parcel.ReadInt32(); + + return true; +} + +ProcessData *ProcessData::Unmarshalling(Parcel &parcel) +{ + ProcessData *processData = new (std::nothrow) ProcessData(); + if (processData && !processData->ReadFromParcel(parcel)) { + APP_LOGW("processData failed, because ReadFromParcel failed"); + delete processData; + processData = nullptr; + } + return processData; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp index 67b77fff0..c21a1e794 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp @@ -337,9 +337,9 @@ int FormProviderProxy::FireFormEvent( MessageParcel reply; MessageOption option; int error = Remote()->SendRequest( - static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), - data, - reply, + static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_MESSAGE), + data, + reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); diff --git a/interfaces/innerkits/fmskit/native/include/form_errors.h b/interfaces/innerkits/fmskit/native/include/form_errors.h index 75d376269..a224b030c 100644 --- a/interfaces/innerkits/fmskit/native/include/form_errors.h +++ b/interfaces/innerkits/fmskit/native/include/form_errors.h @@ -46,7 +46,7 @@ private: void InitErrorMessageMap(); private: - std::map errorMessageMap_; + std::map errorMessageMap_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/kits/appkit/napi/BUILD.gn b/kits/appkit/napi/BUILD.gn index 8c9d56bb6..b64ed10a3 100644 --- a/kits/appkit/napi/BUILD.gn +++ b/kits/appkit/napi/BUILD.gn @@ -18,6 +18,7 @@ group("napi_packages") { "//foundation/appexecfwk/standard/kits/appkit/napi/ability_stage:abilitystage_napi", "//foundation/appexecfwk/standard/kits/appkit/napi/ability_stage_context:abilitystagecontext_napi", "//foundation/appexecfwk/standard/kits/appkit/napi/appMgr:napi_app_mgr", + "//foundation/appexecfwk/standard/kits/appkit/napi/app_manager:appmanager_napi", "//foundation/appexecfwk/standard/kits/appkit/napi/bundlemgr:bundle", "//foundation/appexecfwk/standard/kits/appkit/napi/context:context_napi", "//foundation/appexecfwk/standard/kits/appkit/napi/launchermgr:innerbundlemanager", diff --git a/kits/appkit/napi/app_manager/BUILD.gn b/kits/appkit/napi/app_manager/BUILD.gn new file mode 100644 index 000000000..c133dcd48 --- /dev/null +++ b/kits/appkit/napi/app_manager/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("appmanager_napi") { + include_dirs = [ + "//foundation/multimedia/image_standard/interfaces/innerkits/include", + "//foundation/appexecfwk/standard/kits/appkit/napi/app_manager", + ] + + sources = [ + "app_manager_module.cpp", + "js_app_manager.cpp", + "js_app_manager_utils.cpp", + ] + + configs = [ + "//foundation/aafwk/standard/services/common:common_config", + ] + + deps = [ + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/ace/napi:ace_napi", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:runtime", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module/application" + + subsystem_name = "appexecfwk" + part_name = "appexecfwk_standard" +} diff --git a/kits/appkit/napi/app_manager/app_manager_module.cpp b/kits/appkit/napi/app_manager/app_manager_module.cpp new file mode 100644 index 000000000..5a6c06e0d --- /dev/null +++ b/kits/appkit/napi/app_manager/app_manager_module.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_engine/native_engine.h" +#include "js_app_manager.h" + +extern "C" __attribute__((constructor)) +void NAPI_application_AppManager_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.AppManager", + .fileName = "application/appmanager_napi.so/app_manager.js", + .registerCallback = OHOS::AbilityRuntime::JsAppManagerInit, + }; + + moduleManager->Register(&newModuleInfo); +} \ No newline at end of file diff --git a/kits/appkit/napi/app_manager/js_app_manager.cpp b/kits/appkit/napi/app_manager/js_app_manager.cpp new file mode 100644 index 000000000..1442ba059 --- /dev/null +++ b/kits/appkit/napi/app_manager/js_app_manager.cpp @@ -0,0 +1,426 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "js_app_manager.h" + +#include + +#include "app_mgr_interface.h" +#include "hilog_wrapper.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi/native_api.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "js_app_manager_utils.h" +#include "event_runner.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr int32_t INDEX_ZERO = 0; +constexpr int32_t INDEX_ONE = 1; +constexpr int32_t ERROR_CODE_ONE = 1; +constexpr size_t ARGC_ZERO = 0; +constexpr size_t ARGC_ONE = 1; +constexpr size_t ARGC_TWO = 2; + +class JsAppManager final { +public: + JsAppManager(sptr appManager) : appManager_(appManager) {} + ~JsAppManager() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + HILOG_INFO("JsAbilityContext::Finalizer is called"); + std::unique_ptr(static_cast(data)); + } + + static NativeValue* RegisterApplicationStateObserver(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnRegisterApplicationStateObserver(*engine, *info) : nullptr; + } + + static NativeValue* UnregisterApplicationStateObserver(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnUnregisterApplicationStateObserver(*engine, *info) : nullptr; + } + + static NativeValue* GetForegroundApplications(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetForegroundApplications(*engine, *info) : nullptr; + } + +private: + sptr appManager_ = nullptr; + + NativeValue* OnRegisterApplicationStateObserver(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_INFO("OnRegisterApplicationStateObserver is called"); + // only support one or two params + if (info.argc != ARGC_ONE) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + // unwarp observer + sptr observer = new JSApplicationStateObserver(); + observer->SetNativeEngine(&engine); + observer->SetJsObserverObject(info.argv[0]); + int64_t observerId = serialNumber_; + observerIds_.emplace(observerId, observer); + if (serialNumber_ < INT64_MAX) { + serialNumber_++; + } else { + serialNumber_ = 0; + } + HILOG_INFO("%{public}s create observer:%{public}p", __func__, observer.GetRefPtr()); + AsyncTask::CompleteCallback complete = + [appManager = appManager_, observer](NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("RegisterApplicationStateObserver callback begin"); + int32_t err = appManager->RegisterApplicationStateObserver(observer); + if (err == 0) { + HILOG_INFO("RegisterApplicationStateObserver success err 0"); + } else { + HILOG_ERROR("RegisterApplicationStateObserver failed error:%{public}d", err); + } + }; + + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, nullptr, nullptr, std::move(complete), &result)); + return engine.CreateNumber(observerId); + } + + NativeValue* OnUnregisterApplicationStateObserver(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_INFO("OnUnregisterApplicationStateObserver is called"); + // only support one or two params + if (info.argc != ARGC_ONE && info.argc != ARGC_TWO) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + // unwrap connectId + int64_t observerId = -1; + sptr observer = nullptr; + napi_get_value_int64(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_ZERO]), &observerId); + HILOG_INFO("OnUnregisterApplicationStateObserver observer:%{public}lld", observerId); + auto item = observerIds_.find(observerId); + if (item != observerIds_.end()) { + // match id + observer = item->second; + HILOG_INFO("%{public}s find observer:%{public}p exist", __func__, item->second.GetRefPtr()); + } else { + HILOG_INFO("%{public}s not find observer exist.", __func__); + } + + AsyncTask::CompleteCallback complete = + [appManager = appManager_, observer, observerId]( + NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("OnUnregisterApplicationStateObserver begin"); + if (observer == nullptr) { + HILOG_WARN("observer nullptr"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "not found observer")); + return; + } + HILOG_INFO("observer->UnregisterApplicationStateObserver"); + int32_t err = appManager->UnregisterApplicationStateObserver(observer); + if (err == 0) { + HILOG_INFO("UnregisterApplicationStateObserver success err 0"); + task.Resolve(engine, engine.CreateUndefined()); + observerIds_.erase(observerId); + HILOG_INFO("UnregisterApplicationStateObserver erase size:%{public}zu", observerIds_.size()); + } else { + HILOG_ERROR("UnregisterApplicationStateObserver failed error:%{public}d", err); + task.Reject(engine, CreateJsError(engine, err, "UnregisterApplicationStateObserver failed")); + } + }; + + NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[INDEX_ONE]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue* OnGetForegroundApplications(NativeEngine& engine, NativeCallbackInfo& info) + { + // only support 0 or 1 params + if (info.argc != ARGC_ONE && info.argc != ARGC_ZERO) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + AsyncTask::CompleteCallback complete = + [appManager = appManager_]( + NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("OnGetForegroundApplications begin"); + std::vector list; + int32_t err = appManager->GetForegroundApplications(list); + if (err == 0) { + HILOG_INFO("OnGetForegroundApplications success err 0"); + task.Resolve(engine, CreateJsAppStateDataArray(engine, list)); + } else { + HILOG_ERROR("OnGetForegroundApplications failed error:%{public}d", err); + task.Reject(engine, CreateJsError(engine, err, "OnGetForegroundApplications failed")); + } + }; + + NativeValue* lastParam = (info.argc == ARGC_ZERO) ? nullptr : info.argv[INDEX_ZERO]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } +}; +} // namespace + +OHOS::sptr GetAppManagerInstance() +{ + OHOS::sptr systemAbilityManager = + OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + OHOS::sptr appObject = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID); + return OHOS::iface_cast(appObject); +} + +NativeValue* JsAppManagerInit(NativeEngine* engine, NativeValue* exportObj) +{ + HILOG_INFO("JsAppManagerInit is called"); + + if (engine == nullptr || exportObj == nullptr) { + HILOG_INFO("engine or exportObj null"); + return nullptr; + } + + NativeObject* object = ConvertNativeValueTo(exportObj); + if (object == nullptr) { + HILOG_INFO("object null"); + return nullptr; + } + + std::unique_ptr jsAppManager = + std::make_unique(GetAppManagerInstance()); + object->SetNativePointer(jsAppManager.release(), JsAppManager::Finalizer, nullptr); + + //make handler + handler_ = std::make_shared(AppExecFwk::EventRunner::GetMainEventRunner()); + + HILOG_INFO("JsAppManagerInit BindNativeFunction called"); + BindNativeFunction(*engine, *object, "registerApplicationStateObserver", + JsAppManager::RegisterApplicationStateObserver); + BindNativeFunction(*engine, *object, "unregisterApplicationStateObserver", + JsAppManager::UnregisterApplicationStateObserver); + BindNativeFunction(*engine, *object, "getForegroundApplications", + JsAppManager::GetForegroundApplications); + HILOG_INFO("JsAppManagerInit end"); + return engine->CreateUndefined(); +} + +void JSApplicationStateObserver::OnForegroundApplicationChanged(const AppStateData &appStateData) +{ + HILOG_DEBUG("onForegroundApplicationChanged bundleName:%{public}s, uid:%{public}d, state:%{public}d", + appStateData.bundleName.c_str(), appStateData.uid, appStateData.state); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, appStateData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnForegroundApplicationChanged(appStateData); + }; + handler_->PostTask(task, "OnForegroundApplicationChanged"); +} + +void JSApplicationStateObserver::HandleOnForegroundApplicationChanged(const AppStateData &appStateData) +{ + HILOG_DEBUG("HandleOnForegroundApplicationChanged bundleName:%{public}s, uid:%{public}d, state:%{public}d", + appStateData.bundleName.c_str(), appStateData.uid, appStateData.state); + if (engine_ == nullptr) { + HILOG_ERROR("engine_ nullptr"); + return; + } + NativeValue* argv[] = {CreateJsAppStateData(*engine_, appStateData)}; + CallJsFunction("onForegroundApplicationChanged", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::OnAbilityStateChanged(const AbilityStateData &abilityStateData) +{ + HILOG_INFO("OnAbilityStateChanged begin"); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, abilityStateData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnAbilityStateChanged(abilityStateData); + }; + handler_->PostTask(task, "OnAbilityStateChanged"); +} + +void JSApplicationStateObserver::HandleOnAbilityStateChanged(const AbilityStateData &abilityStateData) +{ + HILOG_INFO("HandleOnAbilityStateChanged begin"); + if (engine_ == nullptr) { + HILOG_ERROR("engine_ nullptr"); + return; + } + NativeValue* argv[] = {CreateJsAbilityStateData(*engine_, abilityStateData)}; + CallJsFunction("onAbilityStateChanged", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::OnExtensionStateChanged(const AbilityStateData &abilityStateData) +{ + HILOG_INFO("OnExtensionStateChanged begin"); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, abilityStateData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnExtensionStateChanged(abilityStateData); + }; + handler_->PostTask(task, "OnExtensionStateChanged"); +} + +void JSApplicationStateObserver::HandleOnExtensionStateChanged(const AbilityStateData &abilityStateData) +{ + HILOG_INFO("HandleOnExtensionStateChanged begin"); + if (engine_ == nullptr) { + HILOG_ERROR("engine_ nullptr"); + return; + } + NativeValue* argv[] = {CreateJsAbilityStateData(*engine_, abilityStateData)}; + CallJsFunction("onExtensionStateChanged", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::OnProcessCreated(const ProcessData &processData) +{ + HILOG_INFO("OnProcessCreated begin"); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, processData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnProcessCreated(processData); + }; + handler_->PostTask(task, "OnProcessCreated"); +} + +void JSApplicationStateObserver::HandleOnProcessCreated(const ProcessData &processData) +{ + HILOG_INFO("HandleOnProcessCreated begin"); + if (engine_ == nullptr) { + HILOG_ERROR("engine_ nullptr"); + return; + } + NativeValue* argv[] = {CreateJsProcessData(*engine_, processData)}; + CallJsFunction("onProcessCreated", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::OnProcessDied(const ProcessData &processData) +{ + HILOG_INFO("OnProcessDied begin"); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, processData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnProcessDied(processData); + }; + handler_->PostTask(task, "OnProcessDied"); +} + +void JSApplicationStateObserver::HandleOnProcessDied(const ProcessData &processData) +{ + HILOG_INFO("HandleOnProcessDied begin"); + if (engine_ == nullptr) { + HILOG_ERROR("engine_ nullptr"); + return; + } + NativeValue* argv[] = {CreateJsProcessData(*engine_, processData)}; + CallJsFunction("onProcessDied", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::CallJsFunction(const char* methodName, NativeValue* const* argv, size_t argc) +{ + HILOG_INFO("CallJsFunction begin, method:%{public}s", methodName); + if (jsObserverObject_ == nullptr) { + HILOG_ERROR("jsObserverObject_ nullptr"); + return; + } + NativeValue* value = jsObserverObject_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get object"); + return; + } + + NativeValue* method = obj->GetProperty(methodName); + if (method == nullptr) { + HILOG_ERROR("Failed to get from object"); + return; + } + if (engine_ == nullptr) { + HILOG_ERROR("engine_ nullptr"); + return; + } + HILOG_INFO("CallJsFunction CallFunction success"); + engine_->CallFunction(value, method, argv, argc); + HILOG_INFO("CallJsFunction end"); +} + +void JSApplicationStateObserver::SetNativeEngine(NativeEngine* engine) +{ + engine_ = engine; +} + +void JSApplicationStateObserver::SetJsObserverObject(NativeValue* jsObserverObject) +{ + jsObserverObject_ = std::unique_ptr(engine_->CreateReference(jsObserverObject, 1)); +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/kits/appkit/napi/app_manager/js_app_manager.h b/kits/appkit/napi/app_manager/js_app_manager.h new file mode 100644 index 000000000..11c001171 --- /dev/null +++ b/kits/appkit/napi/app_manager/js_app_manager.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "application_state_observer_stub.h" +#include "native_engine/native_engine.h" +#include "event_handler.h" + +#ifndef OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_H +#define OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_H + +namespace OHOS { +namespace AbilityRuntime { +using OHOS::AppExecFwk::ApplicationStateObserverStub; +using OHOS::AppExecFwk::AppStateData; +using OHOS::AppExecFwk::AbilityStateData; +using OHOS::AppExecFwk::ProcessData; +NativeValue* JsAppManagerInit(NativeEngine* engine, NativeValue* exportObj); + +class JSApplicationStateObserver : public ApplicationStateObserverStub { +public: + void OnForegroundApplicationChanged(const AppStateData &appStateData) override; + void OnAbilityStateChanged(const AbilityStateData &abilityStateData) override; + void OnExtensionStateChanged(const AbilityStateData &abilityStateData) override; + void OnProcessCreated(const ProcessData &processData) override; + void OnProcessDied(const ProcessData &processData) override; + void HandleOnForegroundApplicationChanged(const AppStateData &appStateData); + void HandleOnAbilityStateChanged(const AbilityStateData &abilityStateData); + void HandleOnExtensionStateChanged(const AbilityStateData &abilityStateData); + void HandleOnProcessCreated(const ProcessData &processData); + void HandleOnProcessDied(const ProcessData &processData); + void SetNativeEngine(NativeEngine* engine); + void SetJsObserverObject(NativeValue* jsObserverObject); + void CallJsFunction(const char* methodName, NativeValue* const* argv, size_t argc); + +private: + NativeEngine* engine_ = nullptr; + std::unique_ptr jsObserverObject_ = nullptr; +}; + +static std::map> observerIds_; +static int64_t serialNumber_ = 0; +static std::shared_ptr handler_ = nullptr; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_H \ No newline at end of file diff --git a/kits/appkit/napi/app_manager/js_app_manager_utils.cpp b/kits/appkit/napi/app_manager/js_app_manager_utils.cpp new file mode 100644 index 000000000..625bd457e --- /dev/null +++ b/kits/appkit/napi/app_manager/js_app_manager_utils.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "js_app_manager_utils.h" + +#include + +#include "hilog_wrapper.h" +#include "iapplication_state_observer.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsAppStateData(NativeEngine &engine, const AppStateData &appStateData) +{ + HILOG_INFO("%{public}s called.", __func__); + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + object->SetProperty("bundleName", CreateJsValue(engine, appStateData.bundleName)); + object->SetProperty("uid", CreateJsValue(engine, appStateData.uid)); + object->SetProperty("state", CreateJsValue(engine, appStateData.state)); + return objValue; +} + +NativeValue* CreateJsAbilityStateData(NativeEngine &engine, const AbilityStateData &abilityStateData) +{ + HILOG_INFO("%{public}s called.", __func__); + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + object->SetProperty("bundleName", CreateJsValue(engine, abilityStateData.bundleName)); + object->SetProperty("abilityName", CreateJsValue(engine, abilityStateData.abilityName)); + object->SetProperty("pid", CreateJsValue(engine, abilityStateData.pid)); + object->SetProperty("uid", CreateJsValue(engine, abilityStateData.uid)); + object->SetProperty("state", CreateJsValue(engine, abilityStateData.abilityState)); + return objValue; +} + +NativeValue* CreateJsProcessData(NativeEngine &engine, const ProcessData &processData) +{ + HILOG_INFO("%{public}s called.", __func__); + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + object->SetProperty("bundleName", CreateJsValue(engine, processData.bundleName)); + object->SetProperty("pid", CreateJsValue(engine, processData.pid)); + object->SetProperty("uid", CreateJsValue(engine, processData.uid)); + return objValue; +} + +NativeValue* CreateJsAppStateDataArray(NativeEngine &engine, std::vector &appStateDatas) +{ + NativeValue* arrayValue = engine.CreateArray(appStateDatas.size()); + NativeArray* array = ConvertNativeValueTo(arrayValue); + uint32_t index = 0; + for (const auto &appStateData : appStateDatas) { + array->SetElement(index++, CreateJsAppStateData(engine, appStateData)); + } + return arrayValue; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/kits/appkit/napi/app_manager/js_app_manager_utils.h b/kits/appkit/napi/app_manager/js_app_manager_utils.h new file mode 100644 index 000000000..12fc78b3d --- /dev/null +++ b/kits/appkit/napi/app_manager/js_app_manager_utils.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "application_state_observer_stub.h" +#include "native_engine/native_engine.h" + +#ifndef OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H +#define OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H + +namespace OHOS { +namespace AbilityRuntime { +using OHOS::AppExecFwk::AppStateData; +using OHOS::AppExecFwk::AbilityStateData; +using OHOS::AppExecFwk::ProcessData; +NativeValue* CreateJsAppStateData(NativeEngine &engine, const AppStateData &appStateData); +NativeValue* CreateJsAbilityStateData(NativeEngine &engine, const AbilityStateData &abilityStateData); +NativeValue* CreateJsProcessData(NativeEngine &engine, const ProcessData &processData); +NativeValue* CreateJsAppStateDataArray(NativeEngine &engine, std::vector &appStateDatas); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/context/js_context_utils.cpp b/kits/appkit/native/ability_runtime/context/js_context_utils.cpp index 0a9f36d0a..98e43ac54 100644 --- a/kits/appkit/native/ability_runtime/context/js_context_utils.cpp +++ b/kits/appkit/native/ability_runtime/context/js_context_utils.cpp @@ -82,7 +82,7 @@ NativeValue* JsBaseContext::OnCreateBundleContext(NativeEngine& engine, NativeCa } std::string bundleName; - if (!ConvertFormJsValue(engine, info.argv[0], bundleName)) { + if (!ConvertFromJsValue(engine, info.argv[0], bundleName)) { HILOG_ERROR("Parse bundleName failed"); return engine.CreateUndefined(); } diff --git a/kits/appkit/native/ability_runtime/extension_context.cpp b/kits/appkit/native/ability_runtime/extension_context.cpp index cd327d92b..d8f825d50 100644 --- a/kits/appkit/native/ability_runtime/extension_context.cpp +++ b/kits/appkit/native/ability_runtime/extension_context.cpp @@ -27,5 +27,10 @@ void ExtensionContext::SetToken(const sptr &token) } token_ = token; } + +sptr ExtensionContext::GetToken() const +{ + return token_; +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/extension_context.h b/kits/appkit/native/ability_runtime/extension_context.h index efcffeb48..c0288de16 100644 --- a/kits/appkit/native/ability_runtime/extension_context.h +++ b/kits/appkit/native/ability_runtime/extension_context.h @@ -37,6 +37,13 @@ public: */ void SetToken(const sptr &token); + /** + * @brief Get the token witch the app launched. + * + * @return token The token which the is launched by app. + */ + sptr GetToken() const; + protected: sptr token_; private: diff --git a/kits/appkit/native/ability_runtime/form_extension_context.cpp b/kits/appkit/native/ability_runtime/form_extension_context.cpp new file mode 100644 index 000000000..e7712ada2 --- /dev/null +++ b/kits/appkit/native/ability_runtime/form_extension_context.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "form_extension_context.h" + +#include "appexecfwk_errors.h" +#include "form_mgr.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +int FormExtensionContext::UpdateForm(const int64_t formId, const AppExecFwk::FormProviderData &formProviderData) +{ + HILOG_DEBUG("%{public}s begin.", __func__); + // check fms recover status + if (AppExecFwk::FormMgr::GetRecoverStatus() == AppExecFwk::Constants::IN_RECOVERING) { + HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__); + return ERR_APPEXECFWK_FORM_IN_RECOVER; + } + + // check formId + if (formId <= 0) { + HILOG_ERROR("%{public}s error, the passed in formId can't be negative or zero.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + // check formProviderData + if (formProviderData.GetDataString().empty()) { + HILOG_ERROR("%{public}s error, the formProviderData is null.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + // update form request to fms + return AppExecFwk::FormMgr::GetInstance().UpdateForm(formId, abilityInfo_->bundleName, formProviderData); +} + +AppExecFwk::AbilityType FormExtensionContext::GetAbilityInfoType() const +{ + std::shared_ptr info = GetAbilityInfo(); + if (info == nullptr) { + HILOG_ERROR("ServiceContext::GetAbilityInfoType info == nullptr"); + return AppExecFwk::AbilityType::UNKNOWN; + } + + return info->type; +} + +std::shared_ptr FormExtensionContext::GetAbilityInfo() const +{ + return abilityInfo_; +} + +void FormExtensionContext::SetAbilityInfo(const std::shared_ptr &abilityInfo) +{ + if (abilityInfo == nullptr) { + HILOG_ERROR("FormExtensionContext::SetAbilityInfo Info == nullptr"); + return; + } + abilityInfo_ = abilityInfo; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/form_extension_context.h b/kits/appkit/native/ability_runtime/form_extension_context.h new file mode 100644 index 000000000..88924aa10 --- /dev/null +++ b/kits/appkit/native/ability_runtime/form_extension_context.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_FORM_EXTENSION_CONTEXT_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_EXTENSION_CONTEXT_H + +#include "ability_info.h" +#include "extension_context.h" +#include "form_provider_info.h" + +namespace OHOS { +namespace AbilityRuntime { +/** + * @brief context supply for form extension + * + */ +class FormExtensionContext : public ExtensionContext { +public: + FormExtensionContext() = default; + virtual ~FormExtensionContext() = default; + + /** + * @brief Updates the content of a specified JS form. + * + * @param formId Indicates the ID of the JS form to update. + * + * @param formProviderData Indicates the {@code FormProviderData} object used to update the JS form displayed + * on the client. + * + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateForm(const int64_t formId, const AppExecFwk::FormProviderData &formProviderData); + + /** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ + std::shared_ptr GetAbilityInfo() const; + + /** + * @brief Set AbilityInfo when init. + * + */ + void SetAbilityInfo(const std::shared_ptr &abilityInfo); + +private: + /** + * @brief Get Current Ability Type + * + * @return Current Ability Type + */ + OHOS::AppExecFwk::AbilityType GetAbilityInfoType() const; + + std::shared_ptr abilityInfo_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/service_extension_context.cpp b/kits/appkit/native/ability_runtime/service_extension_context.cpp index 9c69eba18..1e8810803 100644 --- a/kits/appkit/native/ability_runtime/service_extension_context.cpp +++ b/kits/appkit/native/ability_runtime/service_extension_context.cpp @@ -15,6 +15,7 @@ #include "service_extension_context.h" +#include "ability_connection.h" #include "ability_manager_client.h" #include "hilog_wrapper.h" @@ -32,29 +33,37 @@ void ServiceExtensionContext::StartAbility(const AAFwk::Want &want) const } } -bool ServiceExtensionContext::ConnectAbility(const AAFwk::Want &want, const sptr &conn) +void ServiceExtensionContext::StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const { - HILOG_INFO("%{public}s begin.", __func__); - - ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, conn, token_); - HILOG_INFO("%{public}s end ConnectAbility, ret=%{public}d", __func__, ret); - bool value = ((ret == ERR_OK) ? true : false); - if (!value) { - HILOG_ERROR("ServiceContext::ConnectAbility ErrorCode = %{public}d", ret); + HILOG_DEBUG("%{public}s begin.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_, + ILLEGAL_REQUEST_CODE); + HILOG_DEBUG("%{public}s. End calling ams->StartAbility. ret=%{public}d", __func__, err); + if (err != ERR_OK) { + HILOG_ERROR("ServiceContext::StartAbility is failed %{public}d", err); } - HILOG_INFO("%{public}s end.", __func__); - return value; } -void ServiceExtensionContext::DisconnectAbility(const sptr &conn) +bool ServiceExtensionContext::ConnectAbility( + const AAFwk::Want &want, const std::shared_ptr &connectCallback) const { HILOG_INFO("%{public}s begin.", __func__); - ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn); - HILOG_INFO("%{public}s end ams->DisconnectAbility, ret=%{public}d", __func__, ret); + ErrCode ret = + ConnectionManager::GetInstance().ConnectAbility(token_, want, connectCallback); + HILOG_INFO("ServiceExtensionContext::ConnectAbility ErrorCode = %{public}d", ret); + return ret == ERR_OK; +} + +void ServiceExtensionContext::DisconnectAbility( + const AAFwk::Want &want, const std::shared_ptr &connectCallback) const +{ + HILOG_INFO("%{public}s begin.", __func__); + ErrCode ret = + ConnectionManager::GetInstance().DisconnectAbility(token_, want.GetElement(), connectCallback); if (ret != ERR_OK) { - HILOG_ERROR("ServiceContext::DisconnectAbility error"); + HILOG_ERROR("%{public}s end ams->DisconnectAbility error, ret=%{public}d", __func__, ret); } - HILOG_INFO("ServiceContext::DisconnectAbility end"); + HILOG_INFO("%{public}s end ams->DisconnectAbility", __func__); } void ServiceExtensionContext::TerminateAbility() diff --git a/kits/appkit/native/ability_runtime/service_extension_context.h b/kits/appkit/native/ability_runtime/service_extension_context.h index 85bb96518..db7ccd4da 100644 --- a/kits/appkit/native/ability_runtime/service_extension_context.h +++ b/kits/appkit/native/ability_runtime/service_extension_context.h @@ -18,8 +18,10 @@ #include "extension_context.h" -#include "ability_connect_callback_interface.h" +#include "ability_connect_callback.h" #include "ability_info.h" +#include "connection_manager.h" +#include "start_options.h" #include "want.h" namespace OHOS { @@ -44,6 +46,8 @@ public: */ void StartAbility(const AAFwk::Want &want) const; + void StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const; + /** * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. * @@ -53,7 +57,8 @@ public: * * @return True means success and false means failure */ - bool ConnectAbility(const AAFwk::Want &want, const sptr &conn); + bool ConnectAbility( + const AAFwk::Want &want, const std::shared_ptr &connectCallback) const; /** * @brief Disconnects the current ability from an ability @@ -61,7 +66,8 @@ public: * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. */ - void DisconnectAbility(const sptr &conn); + void DisconnectAbility( + const AAFwk::Want &want, const std::shared_ptr &connectCallback) const; /** * @brief Destroys the current ability. diff --git a/kits/appkit/native/app/include/context_deal.h b/kits/appkit/native/app/include/context_deal.h index 4771ceca0..71fcb6ee9 100755 --- a/kits/appkit/native/app/include/context_deal.h +++ b/kits/appkit/native/app/include/context_deal.h @@ -718,6 +718,13 @@ public: */ void SetRunner(const std::shared_ptr &runner); + /** + * @brief Obtains the lifecycle state info. + * + * @return Returns the lifecycle state info. + */ + AAFwk::LifeCycleStateInfo GetLifeCycleStateInfo() const; + public: static const std::string CONTEXT_DEAL_FILE_SEPARATOR; static const std::string CONTEXT_DEAL_CODE_CACHE; diff --git a/kits/appkit/native/app/include/ohos_application.h b/kits/appkit/native/app/include/ohos_application.h index 1e9ded168..aa384a4f6 100644 --- a/kits/appkit/native/app/include/ohos_application.h +++ b/kits/appkit/native/app/include/ohos_application.h @@ -20,10 +20,10 @@ #include #include -#include "application_context.h" #include "ability_lifecycle_callbacks.h" #include "ability_runtime/context/context.h" #include "ability_stage.h" +#include "application_context.h" #include "element_callback.h" namespace OHOS { diff --git a/kits/appkit/native/app/src/context_deal.cpp b/kits/appkit/native/app/src/context_deal.cpp index 39333ef01..22433ddb0 100755 --- a/kits/appkit/native/app/src/context_deal.cpp +++ b/kits/appkit/native/app/src/context_deal.cpp @@ -740,7 +740,7 @@ void ContextDeal::initResourceManager(const std::shared_ptrGetBundleInfo(abilityInfo->bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - abilityRecord->SetTargetVersion(bundleInfo.targetVersion); - APP_LOGI("MainThread::ScheduleLaunchAbility targetVersion:%{public}d", bundleInfo.targetVersion); + abilityRecord->SetCompatibleVersion(bundleInfo.compatibleVersion); + APP_LOGI("MainThread::ScheduleLaunchAbility compatibleVersion:%{public}d", bundleInfo.compatibleVersion); } auto task = [appThread = this, abilityRecord]() { appThread->HandleLaunchAbility(abilityRecord); }; @@ -741,21 +742,13 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) // Create runtime AbilityRuntime::Runtime::Options options; options.codePath = appInfo.codePath; + options.eventRunner = mainHandler_->GetEventRunner(); auto runtime = AbilityRuntime::Runtime::Create(options); if (!runtime) { APP_LOGE("OHOSApplication::OHOSApplication: Failed to create runtime"); return; } - if (runtime->GetLanguage() == AbilityRuntime::Runtime::Language::JS) { - std::unique_ptr> idleTask = std::make_unique>(); - *idleTask = [&jsRuntime = static_cast(*runtime), &idleTask = *idleTask]() { - jsRuntime.GetNativeEngine().Loop(LOOP_NOWAIT); - EventHandler::Current()->PostIdleTask(idleTask); - }; - mainHandler_->PostIdleTask(*idleTask.release()); - } - application_->SetRuntime(std::move(runtime)); AbilityLoader::GetInstance().RegisterAbility("Ability", [application = application_]() { return Ability::Create(application->GetRuntime()); @@ -763,6 +756,9 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) AbilityLoader::GetInstance().RegisterExtension("ServiceExtension", [application = application_]() { return AbilityRuntime::ServiceExtension::Create(application->GetRuntime()); }); + AbilityLoader::GetInstance().RegisterExtension("FormExtension", [application = application_]() { + return AbilityRuntime::FormExtension::Create(application->GetRuntime()); + }); } contextDeal->initResourceManager(resourceManager); diff --git a/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h b/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h index 185460c48..d1a6b166f 100644 --- a/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h +++ b/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h @@ -89,11 +89,13 @@ public: { return true; }; - virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) + virtual bool GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) { return true; }; - virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) + virtual bool GetBundleInfos( + const BundleFlag flag, std::vector &bundleInfos, int32_t userId) { return true; }; @@ -215,7 +217,8 @@ public: { return true; }; - virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) + virtual bool DumpInfos( + const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) { return true; }; @@ -296,6 +299,10 @@ public: { return true; } + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } }; class MockAbilityContextDeal : public ContextDeal { diff --git a/kits/appkit/test/Mock/include/mock_ability_mgr_service.h b/kits/appkit/test/Mock/include/mock_ability_mgr_service.h index 0b239e2e7..d61f8f6e4 100644 --- a/kits/appkit/test/Mock/include/mock_ability_mgr_service.h +++ b/kits/appkit/test/Mock/include/mock_ability_mgr_service.h @@ -36,7 +36,7 @@ public: MOCK_METHOD2(ReleaseDataAbility, int(sptr, const sptr &)); MOCK_METHOD2(AddWindowInfo, void(const sptr &token, int32_t windowToken)); MOCK_METHOD2(AttachAbilityThread, int(const sptr &scheduler, const sptr &token)); - MOCK_METHOD3(AbilityTransitionDone, int(const sptr &token, int state, const PacMap &)); + MOCK_METHOD3(AbilityTransitionDone, int(const sptr &token, int state, const PacMap &saveData)); MOCK_METHOD2( ScheduleConnectAbilityDone, int(const sptr &token, const sptr &remoteObject)); MOCK_METHOD1(ScheduleDisconnectAbilityDone, int(const sptr &token)); @@ -63,6 +63,17 @@ public: MOCK_METHOD2(UninstallApp, int(const std::string &bundleName, const int userId)); MOCK_METHOD1(TerminateAbilityByRecordId, int(const int64_t recordId)); + MOCK_METHOD1(LockMissionForCleanup, int(int32_t missionId)); + MOCK_METHOD1(UnlockMissionForCleanup, int(int32_t missionId)); + MOCK_METHOD1(RegisterMissionListener, int(const sptr &listener)); + MOCK_METHOD1(UnRegisterMissionListener, int(const sptr &listener)); + MOCK_METHOD3( + GetMissionInfos, int(const std::string& deviceId, int32_t numMax, std::vector &missionInfos)); + MOCK_METHOD3(GetMissionInfo, int(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo)); + MOCK_METHOD1(CleanMission, int(int32_t missionId)); + MOCK_METHOD0(CleanAllMissions, int()); + MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + void Wait() { sem_.Wait(); diff --git a/mgit.info b/mgit.info deleted file mode 100644 index 13e10fb47..000000000 --- a/mgit.info +++ /dev/null @@ -1 +0,0 @@ -hmf/appexecfwk/standard diff --git a/services/appmgr/include/ability_running_record.h b/services/appmgr/include/ability_running_record.h index 51803d21f..eee811ed0 100644 --- a/services/appmgr/include/ability_running_record.h +++ b/services/appmgr/include/ability_running_record.h @@ -145,6 +145,18 @@ public: */ int32_t GetConnectionState() const; + /** + * @brief Set the Terminating object. + */ + void SetTerminating(); + + /** + * @brief Whether the ability is terminating. + * + * @return Returns whether the ability is terminating. + */ + bool IsTerminating() const; + void SetEventId(const int64_t eventId); int64_t GetEventId() const; @@ -154,6 +166,7 @@ private: int32_t perceptibility_ = 0; int32_t connectionState_ = 0; int64_t eventId_ = 0; + bool isTerminating_ = false; AbilityState state_ = AbilityState::ABILITY_STATE_BEGIN; std::shared_ptr info_; sptr token_; diff --git a/services/appmgr/include/ams_mgr_scheduler.h b/services/appmgr/include/ams_mgr_scheduler.h index bed7572ea..cd12c34ce 100644 --- a/services/appmgr/include/ams_mgr_scheduler.h +++ b/services/appmgr/include/ams_mgr_scheduler.h @@ -69,6 +69,15 @@ public: */ virtual void UpdateAbilityState(const sptr &token, const AbilityState state) override; + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state) override; + /** * RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback. * diff --git a/services/appmgr/include/app_lifecycle_deal.h b/services/appmgr/include/app_lifecycle_deal.h index 99e494214..42eaffda6 100644 --- a/services/appmgr/include/app_lifecycle_deal.h +++ b/services/appmgr/include/app_lifecycle_deal.h @@ -131,7 +131,7 @@ public: sptr GetApplicationClient() const; private: - sptr appThread_; + sptr appThread_ = nullptr; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/app_mgr_service.h b/services/appmgr/include/app_mgr_service.h index 91366f9d1..5a4bc7c23 100644 --- a/services/appmgr/include/app_mgr_service.h +++ b/services/appmgr/include/app_mgr_service.h @@ -237,6 +237,27 @@ private: */ void SetInnerService(const std::shared_ptr &innerService); + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t RegisterApplicationStateObserver(const sptr &observer) override; + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) override; + + /** + * Get foreground applications. + * @param list, foreground apps. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetForegroundApplications(std::vector &list) override; + private: std::shared_ptr appMgrServiceInner_; AppMgrServiceState appMgrServiceState_; diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index fde111340..96f732eaa 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -33,6 +33,7 @@ #include "app_spawn_client.h" #include "app_task_info.h" #include "iapp_state_callback.h" +#include "iapplication_state_observer.h" #include "app_process_manager.h" #include "remote_client_manager.h" #include "app_running_manager.h" @@ -85,6 +86,24 @@ public: */ virtual void UpdateAbilityState(const sptr &token, const AbilityState state); + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state); + + /** + * StateChangedNotifyObserver, Call ability state change. + * + * @param ability, the ability info. + * @param state, the ability state. + * + * @return + */ + void StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility); + /** * RegisterAppStateCallback, register the callback. * @@ -486,6 +505,27 @@ public: bool CheckRemoteClient(); + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t RegisterApplicationStateObserver(const sptr &observer); + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t UnregisterApplicationStateObserver(const sptr &observer); + + /** + * Get Foreground Applications. + * + * @return Foreground Applications. + */ + int32_t GetForegroundApplications(std::vector &list); + private: void StartEmptyResidentProcess(const std::string &appName, const std::string &processName, @@ -671,6 +711,28 @@ private: int32_t KillApplicationByUserId(const std::string &bundleName, const int userId); + AppProcessData WrapAppProcessData(const std::shared_ptr &appRecord, + const ApplicationState state); + + AppStateData WrapAppStateData(const std::shared_ptr &appRecord, + const ApplicationState state); + + ProcessData WrapProcessData(const std::shared_ptr &appRecord); + + void AddObserverDeathRecipient(const sptr &observer); + + void RemoveObserverDeathRecipient(const sptr &observer); + + void OnObserverDied(const wptr &remote); + + void HandleObserverDiedTask(const sptr &observer); + + bool ObserverExist(const sptr &observer); + + void OnProcessCreated(const std::shared_ptr &appRecord); + + void OnProcessDied(const std::shared_ptr &appRecord); + private: /** * ClearUpApplicationData, clear the application data. @@ -696,6 +758,10 @@ private: */ void NotifyAppStatus(const std::string &bundleName, const std::string &eventData); + const std::string TASK_ON_CALLBACK_DIED = "OnCallbackDiedTask"; + std::vector> appStateObservers_; + std::map, sptr> recipientMap_; + std::recursive_mutex observerLock_; std::vector> appStateCallbacks_; std::shared_ptr appProcessManager_; std::shared_ptr remoteClientManager_; diff --git a/services/appmgr/include/app_running_manager.h b/services/appmgr/include/app_running_manager.h index d0869f0a7..9042f0666 100644 --- a/services/appmgr/include/app_running_manager.h +++ b/services/appmgr/include/app_running_manager.h @@ -25,6 +25,7 @@ #include "app_running_record.h" #include "ability_info.h" #include "application_info.h" +#include "app_state_data.h" #include "record_query_result.h" namespace OHOS { @@ -120,6 +121,13 @@ public: */ void ClearAppRunningRecordMap(); + /** + * Get Foreground Applications. + * + * @return Foreground Applications. + */ + void GetForegroundApplications(std::vector &list); + void HandleTerminateTimeOut(int64_t eventId); void HandleAbilityAttachTimeOut(const sptr &token); std::shared_ptr GetAppRunningRecord(const int64_t eventId); diff --git a/services/appmgr/include/app_running_record.h b/services/appmgr/include/app_running_record.h index e82d810c8..f4edc3356 100644 --- a/services/appmgr/include/app_running_record.h +++ b/services/appmgr/include/app_running_record.h @@ -24,6 +24,7 @@ #include "iremote_object.h" #include "ability_running_record.h" +#include "ability_state_data.h" #include "application_info.h" #include "app_death_recipient.h" #include "app_launch_data.h" @@ -382,6 +383,14 @@ public: void insertAbilityStageInfo(std::vector moduleInfos); + /** + * Notify observers when state change. + * + * @param ability, ability or extension record. + * @param state, ability or extension state. + */ + void StateChangedNotifyObserver(const std::shared_ptr &ability, int32_t state, bool isAbility); + private: // drive application state changes when ability state changes. /** @@ -429,8 +438,9 @@ private: bool isKeepAliveApp = false; // Only resident processes can be set to true, please choose carefully ApplicationState curState_ = ApplicationState::APP_STATE_CREATE; // current state of this process - std::shared_ptr appInfo_; // the application's info of this process + std::shared_ptr appInfo_ = nullptr; // the application's info of this process int32_t appRecordId_ = 0; + std::string appName_; std::string processName_; // the name of this process int32_t uid_ = 0; static int64_t appEventId_; @@ -441,10 +451,10 @@ private: std::map> abilityStage_; std::list> foregroundingAbilityTokens_; std::weak_ptr appMgrServiceInner_; - sptr appDeathRecipient_; - std::shared_ptr priorityObject_; - std::shared_ptr appLifeCycleDeal_; - std::shared_ptr eventHandler_; + sptr appDeathRecipient_ = nullptr; + std::shared_ptr priorityObject_ = nullptr; + std::shared_ptr appLifeCycleDeal_ = nullptr; + std::shared_ptr eventHandler_ = nullptr; bool isTerminating = false; }; } // namespace AppExecFwk diff --git a/services/appmgr/src/ability_running_record.cpp b/services/appmgr/src/ability_running_record.cpp index ae38b7a31..8c218661e 100644 --- a/services/appmgr/src/ability_running_record.cpp +++ b/services/appmgr/src/ability_running_record.cpp @@ -110,5 +110,15 @@ int64_t AbilityRunningRecord::GetEventId() const { return eventId_; } + +void AbilityRunningRecord::SetTerminating() +{ + isTerminating_ = true; +} + +bool AbilityRunningRecord::IsTerminating() const +{ + return isTerminating_; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp index b8fdbd83a..9f6c1e5c8 100644 --- a/services/appmgr/src/ams_mgr_scheduler.cpp +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -31,6 +31,7 @@ namespace { const std::string TASK_LOAD_ABILITY = "LoadAbilityTask"; const std::string TASK_TERMINATE_ABILITY = "TerminateAbilityTask"; const std::string TASK_UPDATE_ABILITY_STATE = "UpdateAbilityStateTask"; +const std::string TASK_UPDATE_EXTENSION_STATE = "UpdateExtensionStateTask"; const std::string TASK_REGISTER_APP_STATE_CALLBACK = "RegisterAppStateCallbackTask"; const std::string TASK_STOP_ALL_PROCESS = "StopAllProcessTask"; const std::string TASK_ABILITY_BEHAVIOR_ANALYSIS = "AbilityBehaviorAnalysisTask"; @@ -76,6 +77,16 @@ void AmsMgrScheduler::UpdateAbilityState(const sptr &token, const amsHandler_->PostTask(updateAbilityStateFunc, TASK_UPDATE_ABILITY_STATE); } +void AmsMgrScheduler::UpdateExtensionState(const sptr &token, const ExtensionState state) +{ + if (!IsReady()) { + return; + } + std::function updateExtensionStateFunc = + std::bind(&AppMgrServiceInner::UpdateExtensionState, amsMgrServiceInner_, token, state); + amsHandler_->PostTask(updateExtensionStateFunc, TASK_UPDATE_EXTENSION_STATE); +} + void AmsMgrScheduler::TerminateAbility(const sptr &token) { if (!IsReady()) { diff --git a/services/appmgr/src/app_lifecycle_deal.cpp b/services/appmgr/src/app_lifecycle_deal.cpp index dc0270120..578114e06 100644 --- a/services/appmgr/src/app_lifecycle_deal.cpp +++ b/services/appmgr/src/app_lifecycle_deal.cpp @@ -27,7 +27,9 @@ AppLifeCycleDeal::~AppLifeCycleDeal() void AppLifeCycleDeal::LaunchApplication(const AppLaunchData &launchData_) { APP_LOGI("AppLifeCycleDeal ScheduleLaunchApplication"); - appThread_->ScheduleLaunchApplication(launchData_); + if (appThread_) { + appThread_->ScheduleLaunchApplication(launchData_); + } } void AppLifeCycleDeal::AddAbilityStageInfo(const AppResidentProcessInfo &residentProcessInfo) @@ -39,7 +41,9 @@ void AppLifeCycleDeal::AddAbilityStageInfo(const AppResidentProcessInfo &residen void AppLifeCycleDeal::LaunchAbility(const std::shared_ptr &ability) { - appThread_->ScheduleLaunchAbility(*(ability->GetAbilityInfo()), ability->GetToken()); + if (appThread_) { + appThread_->ScheduleLaunchAbility(*(ability->GetAbilityInfo()), ability->GetToken()); + } } void AppLifeCycleDeal::ScheduleTerminate() diff --git a/services/appmgr/src/app_mgr_service.cpp b/services/appmgr/src/app_mgr_service.cpp index 8a7669b9d..b25333c54 100755 --- a/services/appmgr/src/app_mgr_service.cpp +++ b/services/appmgr/src/app_mgr_service.cpp @@ -337,5 +337,35 @@ void AppMgrService::AddAbilityStageDone(const int32_t recordId) std::bind(&AppMgrServiceInner::AddAbilityStageDone, appMgrServiceInner_, recordId); handler_->PostTask(addAbilityStageDone, TASK_ADD_ABILITY_STAGE_DONE); } + +int32_t AppMgrService::RegisterApplicationStateObserver(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + if (!IsReady()) { + APP_LOGE("%{public}s begin, not ready", __func__); + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->RegisterApplicationStateObserver(observer); +} + +int32_t AppMgrService::UnregisterApplicationStateObserver(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + if (!IsReady()) { + APP_LOGE("%{public}s begin, not ready", __func__); + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->UnregisterApplicationStateObserver(observer); +} + +int32_t AppMgrService::GetForegroundApplications(std::vector &list) +{ + APP_LOGI("%{public}s begin", __func__); + if (!IsReady()) { + APP_LOGE("%{public}s begin, not ready", __func__); + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->GetForegroundApplications(list); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index c49092471..3f687d221 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -20,6 +20,7 @@ #include #include "app_log_wrapper.h" +#include "application_state_observer_stub.h" #include "datetime_ex.h" #include "perf_profile.h" @@ -244,6 +245,7 @@ void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId) OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); appRunningManager_->RemoveAppRunningRecordById(recordId); RemoveAppFromRecentListById(recordId); + OnProcessDied(appRecord); APP_LOGI("application is terminated"); } @@ -603,6 +605,25 @@ void AppMgrServiceInner::UpdateAbilityState(const sptr &token, co APP_LOGD("end"); } +void AppMgrServiceInner::UpdateExtensionState(const sptr &token, const ExtensionState state) +{ + if (!token) { + APP_LOGE("token is null!"); + return; + } + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("app is not exist!"); + return; + } + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + if (!abilityRecord) { + APP_LOGE("can not find ability record!"); + return; + } + appRecord->StateChangedNotifyObserver(abilityRecord, static_cast(state), false); +} + void AppMgrServiceInner::OnStop() { appRunningManager_->ClearAppRunningRecordMap(); @@ -900,18 +921,55 @@ void AppMgrServiceInner::OnAppStateChanged( for (const auto &callback : appStateCallbacks_) { if (callback != nullptr) { - AppProcessData processData; - processData.appName = appRecord->GetName(); - processData.processName = appRecord->GetProcessName(); - processData.pid = appRecord->GetPriorityObject()->GetPid(); - processData.appState = state; - processData.uid = appRecord->GetUid(); - callback->OnAppStateChanged(processData); + callback->OnAppStateChanged(WrapAppProcessData(appRecord, state)); + } + } + + if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_BACKGROUND) { + AppStateData data = WrapAppStateData(appRecord, state); + APP_LOGD("OnForegroundApplicationChanged, size:%{public}d, name:%{public}s, uid:%{public}d, state:%{public}d", + appStateObservers_.size(), data.bundleName.c_str(), data.uid, data.state); + std::lock_guard lockNotify(observerLock_); + for (const auto &observer : appStateObservers_) { + if (observer != nullptr) { + observer->OnForegroundApplicationChanged(data); + } } } APP_LOGD("end"); } +AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr &appRecord, + const ApplicationState state) +{ + AppProcessData processData; + processData.appName = appRecord->GetName(); + processData.processName = appRecord->GetProcessName(); + processData.pid = appRecord->GetPriorityObject()->GetPid(); + processData.appState = state; + processData.uid = appRecord->GetUid(); + return processData; +} + +AppStateData AppMgrServiceInner::WrapAppStateData(const std::shared_ptr &appRecord, + const ApplicationState state) +{ + AppStateData appStateData; + appStateData.bundleName = appRecord->GetBundleName(); + appStateData.state = static_cast(state); + appStateData.uid = appRecord->GetUid(); + return appStateData; +} + +ProcessData AppMgrServiceInner::WrapProcessData(const std::shared_ptr &appRecord) +{ + ProcessData processData; + processData.bundleName = appRecord->GetBundleName(); + processData.pid = appRecord->GetPriorityObject()->GetPid(); + processData.uid = appRecord->GetUid(); + return processData; +} + void AppMgrServiceInner::OnAbilityStateChanged( const std::shared_ptr &ability, const AbilityState state) { @@ -928,6 +986,61 @@ void AppMgrServiceInner::OnAbilityStateChanged( APP_LOGD("end"); } +void AppMgrServiceInner::StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility) +{ + std::lock_guard lockNotify(observerLock_); + APP_LOGD("bundle:%{public}s, ability:%{public}s, state:%{public}d, pid:%{public}d, uid:%{public}d", + abilityStateData.bundleName.c_str(), abilityStateData.abilityName.c_str(), + abilityStateData.abilityState, abilityStateData.pid, abilityStateData.uid); + for (const auto &observer : appStateObservers_) { + if (observer != nullptr) { + if (isAbility) { + observer->OnAbilityStateChanged(abilityStateData); + } else { + observer->OnExtensionStateChanged(abilityStateData); + } + } + } +} + +void AppMgrServiceInner::OnProcessCreated(const std::shared_ptr &appRecord) +{ + APP_LOGD("OnProcessCreated begin."); + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } + ProcessData data = WrapProcessData(appRecord); + APP_LOGD("OnProcessCreated, bundle:%{public}s, pid:%{public}d, uid:%{public}d, size:%{public}d", + data.bundleName.c_str(), data.uid, data.pid, appStateObservers_.size()); + std::lock_guard lockNotify(observerLock_); + for (const auto &observer : appStateObservers_) { + if (observer != nullptr) { + observer->OnProcessCreated(data); + } + } + APP_LOGD("end"); +} + +void AppMgrServiceInner::OnProcessDied(const std::shared_ptr &appRecord) +{ + APP_LOGD("OnProcessDied begin."); + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } + ProcessData data = WrapProcessData(appRecord); + APP_LOGD("OnProcessDied, bundle:%{public}s, pid:%{public}d, uid:%{public}d, size:%{public}d", + data.bundleName.c_str(), data.uid, data.pid, appStateObservers_.size()); + std::lock_guard lockNotify(observerLock_); + for (const auto &observer : appStateObservers_) { + if (observer != nullptr) { + observer->OnProcessDied(data); + } + } + APP_LOGD("end"); +} + void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, const std::shared_ptr &appRecord, const int uid) { @@ -987,6 +1100,7 @@ void AppMgrServiceInner::StartProcess(const std::string &appName, const std::str appRecord->SetAppMgrServiceInner(weak_from_this()); OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE); AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId()); + OnProcessCreated(appRecord); PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount()); } @@ -1050,9 +1164,12 @@ void AppMgrServiceInner::OnRemoteDied(const wptr &remote) for (const auto &item : appRecord->GetAbilities()) { const auto &abilityRecord = item.second; OptimizerAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_TERMINATED); + appRecord->StateChangedNotifyObserver(abilityRecord, + static_cast(AbilityState::ABILITY_STATE_TERMINATED), true); } OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); RemoveAppFromRecentListById(appRecord->GetRecordId()); + OnProcessDied(appRecord); } if (appRecord && appRecord->IsKeepAliveApp()) { @@ -1293,6 +1410,7 @@ void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId } appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); RemoveAppFromRecentListById(appRecord->GetRecordId()); + OnProcessDied(appRecord); } void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId) @@ -1479,5 +1597,124 @@ void AppMgrServiceInner::NotifyAppStatus(const std::string &bundleName, const st EventFwk::CommonEventData commonData {want}; EventFwk::CommonEventManager::PublishCommonEvent(commonData); } + +int32_t AppMgrServiceInner::RegisterApplicationStateObserver(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + std::lock_guard lockRegister(observerLock_); + if (observer == nullptr) { + APP_LOGE("Observer nullptr"); + return ERR_INVALID_VALUE; + } + if (ObserverExist(observer)) { + APP_LOGE("Observer exist."); + return ERR_INVALID_VALUE; + } + appStateObservers_.push_back(observer); + APP_LOGI("%{public}s appStateObservers_ size:%{public}d", __func__, appStateObservers_.size()); + AddObserverDeathRecipient(observer); + return ERR_OK; +} + +int32_t AppMgrServiceInner::UnregisterApplicationStateObserver(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + std::lock_guard lockUnregister(observerLock_); + if (observer == nullptr) { + APP_LOGE("Observer nullptr"); + return ERR_INVALID_VALUE; + } + std::vector>::iterator it; + for (it = appStateObservers_.begin(); it != appStateObservers_.end(); it++) { + if ((*it)->AsObject() == observer->AsObject()) { + appStateObservers_.erase(it); + APP_LOGI("%{public}s appStateObservers_ size:%{public}d", __func__, appStateObservers_.size()); + RemoveObserverDeathRecipient(observer); + return ERR_OK; + } + } + APP_LOGE("Observer not exist."); + return ERR_INVALID_VALUE; +} + +bool AppMgrServiceInner::ObserverExist(const sptr &observer) +{ + if (observer == nullptr) { + APP_LOGE("Observer nullptr"); + return false; + } + for (int i = 0; i < appStateObservers_.size(); i++) { + if (appStateObservers_[i]->AsObject() == observer->AsObject()) { + return true; + } + } + return false; +} + +void AppMgrServiceInner::AddObserverDeathRecipient(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + if (observer == nullptr || observer->AsObject() == nullptr) { + APP_LOGE("observer nullptr."); + return; + } + auto it = recipientMap_.find(observer->AsObject()); + if (it != recipientMap_.end()) { + APP_LOGE("This death recipient has been added."); + return; + } else { + sptr deathRecipient = new ApplicationStateObserverRecipient( + std::bind(&AppMgrServiceInner::OnObserverDied, this, std::placeholders::_1)); + observer->AsObject()->AddDeathRecipient(deathRecipient); + recipientMap_.emplace(observer->AsObject(), deathRecipient); + } +} + +void AppMgrServiceInner::RemoveObserverDeathRecipient(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + if (observer == nullptr || observer->AsObject() == nullptr) { + APP_LOGE("observer nullptr."); + return; + } + auto it = recipientMap_.find(observer->AsObject()); + if (it != recipientMap_.end()) { + it->first->RemoveDeathRecipient(it->second); + recipientMap_.erase(it); + return; + } +} + +void AppMgrServiceInner::OnObserverDied(const wptr &remote) +{ + APP_LOGI("%{public}s begin", __func__); + auto object = remote.promote(); + if (object == nullptr) { + APP_LOGE("observer nullptr."); + return; + } + if (eventHandler_) { + auto task = [object, appManager = this]() {appManager->HandleObserverDiedTask(object);}; + eventHandler_->PostTask(task, TASK_ON_CALLBACK_DIED); + } +} + +void AppMgrServiceInner::HandleObserverDiedTask(const sptr &observer) +{ + APP_LOGI("Handle call back died task."); + if (observer == nullptr) { + APP_LOGE("observer nullptr."); + return; + } + sptr object = iface_cast(observer); + UnregisterApplicationStateObserver(object); +} + +int32_t AppMgrServiceInner::GetForegroundApplications(std::vector &list) +{ + APP_LOGI("%{public}s, begin.", __func__); + appRunningManager_->GetForegroundApplications(list); + return ERR_OK; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_running_manager.cpp b/services/appmgr/src/app_running_manager.cpp index d9e54d84d..a91a618fd 100644 --- a/services/appmgr/src/app_running_manager.cpp +++ b/services/appmgr/src/app_running_manager.cpp @@ -306,6 +306,11 @@ void AppRunningManager::HandleAbilityAttachTimeOut(const sptr &to return; } + std::shared_ptr abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + if (abilityRecord) { + abilityRecord->SetTerminating(); + } + if (appRecord->IsLastAbilityRecord(token)) { appRecord->SetTerminating(); } @@ -397,5 +402,22 @@ std::shared_ptr AppRunningManager::GetAppRunningRecordByBundle } return nullptr; } + +void AppRunningManager::GetForegroundApplications(std::vector &list) +{ + APP_LOGI("%{public}s, begin.", __func__); + std::lock_guard guard(lock_); + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) { + AppStateData appData; + appData.bundleName = appRecord->GetBundleName(); + appData.uid = appRecord->GetUid(); + appData.state = static_cast(ApplicationState::APP_STATE_FOREGROUND); + list.push_back(appData); + APP_LOGI("%{public}s, bundleName:%{public}s", __func__, appData.bundleName.c_str()); + } + } +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/app_running_record.cpp b/services/appmgr/src/app_running_record.cpp index ca71bfabe..55c702c4b 100644 --- a/services/appmgr/src/app_running_record.cpp +++ b/services/appmgr/src/app_running_record.cpp @@ -26,7 +26,11 @@ int64_t AppRunningRecord::appEventId_ = 0; AppRunningRecord::AppRunningRecord( const std::shared_ptr &info, const int32_t recordId, const std::string &processName) : appInfo_(info), appRecordId_(recordId), processName_(processName) -{} +{ + if (appInfo_) { + appName_ = appInfo_->name; + } +} void AppRunningRecord::SetApplicationClient(const sptr &thread) { @@ -38,12 +42,12 @@ void AppRunningRecord::SetApplicationClient(const sptr &thread) std::string AppRunningRecord::GetBundleName() const { - return appInfo_->bundleName; + return appInfo_ ? appInfo_->bundleName : ""; } bool AppRunningRecord::IsLauncherApp() const { - return appInfo_->isLauncherApp; + return appInfo_ ? appInfo_->isLauncherApp : false; } int32_t AppRunningRecord::GetRecordId() const @@ -53,7 +57,7 @@ int32_t AppRunningRecord::GetRecordId() const const std::string &AppRunningRecord::GetName() const { - return appInfo_->name; + return appName_; } bool AppRunningRecord::GetCloneInfo() const @@ -119,7 +123,7 @@ std::shared_ptr AppRunningRecord::AddAbility( std::shared_ptr AppRunningRecord::GetAbilityRunningRecord(const std::string &abilityName) const { const auto &iter = std::find_if(abilities_.begin(), abilities_.end(), [&abilityName](const auto &pair) { - return pair.second->GetName() == abilityName; + return pair.second->GetName() == abilityName && !(pair.second->IsTerminating()); }); return ((iter == abilities_.end()) ? nullptr : iter->second); } @@ -164,6 +168,10 @@ void AppRunningRecord::ScheduleAppCrash([[maybe_unused]] const std::string &desc void AppRunningRecord::LaunchApplication() { + if (appLifeCycleDeal_ == nullptr) { + APP_LOGE("appLifeCycleDeal_ is null"); + return; + } if (!appInfo_ || !appLifeCycleDeal_->GetApplicationClient()) { APP_LOGE("appInfo or appThread is null"); return; @@ -197,6 +205,10 @@ void AppRunningRecord::AddAbilityStageDone() void AppRunningRecord::LaunchAbility(const std::shared_ptr &ability) { + if (appLifeCycleDeal_ == nullptr) { + APP_LOGE("appLifeCycleDeal_ is null"); + return; + } if (!ability || !ability->GetToken()) { APP_LOGE("null abilityRecord or abilityToken"); return; @@ -222,32 +234,44 @@ void AppRunningRecord::LaunchPendingAbilities() void AppRunningRecord::ScheduleTerminate() { SendEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT); - appLifeCycleDeal_->ScheduleTerminate(); + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleTerminate(); + } } void AppRunningRecord::ScheduleForegroundRunning() { - appLifeCycleDeal_->ScheduleForegroundRunning(); + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleForegroundRunning(); + } } void AppRunningRecord::ScheduleBackgroundRunning() { - appLifeCycleDeal_->ScheduleBackgroundRunning(); + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleBackgroundRunning(); + } } void AppRunningRecord::ScheduleProcessSecurityExit() { - appLifeCycleDeal_->ScheduleProcessSecurityExit(); + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleProcessSecurityExit(); + } } void AppRunningRecord::ScheduleTrimMemory() { - appLifeCycleDeal_->ScheduleTrimMemory(priorityObject_->GetTimeLevel()); + if (appLifeCycleDeal_ && priorityObject_) { + appLifeCycleDeal_->ScheduleTrimMemory(priorityObject_->GetTimeLevel()); + } } void AppRunningRecord::LowMemoryWarning() { - appLifeCycleDeal_->LowMemoryWarning(); + if (appLifeCycleDeal_) { + appLifeCycleDeal_->LowMemoryWarning(); + } } void AppRunningRecord::OnAbilityStateChanged( @@ -266,6 +290,32 @@ void AppRunningRecord::OnAbilityStateChanged( } } +void AppRunningRecord::StateChangedNotifyObserver( + const std::shared_ptr &ability, const int32_t state, bool isAbility) +{ + if (!ability) { + APP_LOGE("ability is null"); + return; + } + AbilityStateData abilityStateData; + abilityStateData.bundleName = GetBundleName(); + abilityStateData.abilityName = ability->GetName(); + abilityStateData.pid = GetPriorityObject()->GetPid(); + abilityStateData.abilityState = state; + abilityStateData.uid = GetUid(); + abilityStateData.token = ability->GetToken(); + + if (isAbility && ability->GetAbilityInfo() != nullptr && + ability->GetAbilityInfo()->type == AbilityType::EXTENSION) { + APP_LOGI("extension type, not notify any more."); + return; + } + auto serviceInner = appMgrServiceInner_.lock(); + if (serviceInner) { + serviceInner->StateChangedNotifyObserver(abilityStateData, isAbility); + } +} + std::shared_ptr AppRunningRecord::GetAbilityRunningRecordByToken( const sptr &token) const { @@ -340,6 +390,7 @@ void AppRunningRecord::AbilityForeground(const std::shared_ptr(AbilityState::ABILITY_STATE_FOREGROUND), true); auto serviceInner = appMgrServiceInner_.lock(); if (serviceInner) { serviceInner->OnAppStateChanged(shared_from_this(), curState_); @@ -363,6 +414,7 @@ void AppRunningRecord::AbilityBackground(const std::shared_ptr(AbilityState::ABILITY_STATE_BACKGROUND), true); if (curState_ == ApplicationState::APP_STATE_FOREGROUND) { int32_t foregroundSize = 0; for (const auto &item : abilities_) { @@ -398,6 +450,7 @@ void AppRunningRecord::PopForegroundingAbilityTokens() const auto &token = foregroundingAbilityTokens_.front(); auto ability = GetAbilityRunningRecordByToken(token); OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND); + StateChangedNotifyObserver(ability, static_cast(AbilityState::ABILITY_STATE_FOREGROUND), true); foregroundingAbilityTokens_.pop_front(); } } @@ -427,7 +480,12 @@ void AppRunningRecord::TerminateAbility(const sptr &token, const } OptimizerAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_TERMINATED); - appLifeCycleDeal_->ScheduleCleanAbility(token); + StateChangedNotifyObserver(abilityRecord, static_cast(AbilityState::ABILITY_STATE_TERMINATED), true); + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleCleanAbility(token); + } else { + APP_LOGE("appLifeCycleDeal_ is null"); + } APP_LOGD("AppRunningRecord::TerminateAbility end"); } @@ -463,6 +521,10 @@ void AppRunningRecord::AbilityTerminated(const sptr &token) void AppRunningRecord::RegisterAppDeathRecipient() const { + if (appLifeCycleDeal_ == nullptr) { + APP_LOGE("appLifeCycleDeal_ is null"); + return; + } if (!appLifeCycleDeal_->GetApplicationClient()) { APP_LOGE("appThread is null"); return; @@ -475,6 +537,10 @@ void AppRunningRecord::RegisterAppDeathRecipient() const void AppRunningRecord::RemoveAppDeathRecipient() const { + if (appLifeCycleDeal_ == nullptr) { + APP_LOGE("appLifeCycleDeal_ is null"); + return; + } if (!appLifeCycleDeal_->GetApplicationClient()) { APP_LOGE("appThread is null"); return; diff --git a/services/appmgr/src/process_optimizer.cpp b/services/appmgr/src/process_optimizer.cpp index 2c58d7798..c70eab64f 100644 --- a/services/appmgr/src/process_optimizer.cpp +++ b/services/appmgr/src/process_optimizer.cpp @@ -431,7 +431,10 @@ void ProcessOptimizer::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel leve APP_LOGI("OnLowMemoryAlert level %{public}d", level); // Find the oldest background app. for (auto it(appLru_.rbegin()); it != appLru_.rend(); ++it) { - if ((*it)->GetState() == ApplicationState::APP_STATE_BACKGROUND) { + auto appRecord = (*it); + if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_BACKGROUND) { + APP_LOGI("OnLowMemoryAlert bundle:%{public}s, level:%{public}d", + appRecord->GetBundleName().c_str(), level); AppLowMemoryAlert(*it, level); break; } @@ -440,7 +443,11 @@ void ProcessOptimizer::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel leve // send pid which will be killed. std::list::iterator iter = appLru_.begin(); while (iter != appLru_.end()) { - auto priorityObject = (*iter)->GetPriorityObject(); + auto appRecord = (*iter); + if (!appRecord) { + continue; + } + auto priorityObject = appRecord->GetPriorityObject(); if (priorityObject != nullptr && priorityObject->GetCurAdj() >= G_MEMORY_LEVEL[level]) { auto pid = priorityObject->GetPid(); if (pid <= 0) { @@ -449,13 +456,12 @@ void ProcessOptimizer::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel leve continue; } - if (lmksClient_->ProcRemove(priorityObject->GetPid()) != ERR_OK) { - APP_LOGE("failed to remove pid (%{publid}d) from lmks.", priorityObject->GetPid()); - } else { - APP_LOGE("success to remove pid (%{publid}d) from lmks.", priorityObject->GetPid()); + APP_LOGI("remove pid (%{publid}d) from lmks, bundle:%{public}s", pid, appRecord->GetBundleName().c_str()); + if (lmksClient_->ProcRemove(pid) == ERR_OK) { iter = appLru_.erase(iter); continue; } + APP_LOGE("remove error, pid:%{publid}d, bundle:%{public}s", pid, appRecord->GetBundleName().c_str()); } iter++; } diff --git a/services/appmgr/test/BUILD.gn b/services/appmgr/test/BUILD.gn index 915494baf..5811e4142 100644 --- a/services/appmgr/test/BUILD.gn +++ b/services/appmgr/test/BUILD.gn @@ -82,6 +82,7 @@ ohos_source_set("appmgr_test_source") { "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", ] diff --git a/services/appmgr/test/mock/include/mock_app_mgr_service.h b/services/appmgr/test/mock/include/mock_app_mgr_service.h index 1b770baef..9c06b3b6c 100644 --- a/services/appmgr/test/mock/include/mock_app_mgr_service.h +++ b/services/appmgr/test/mock/include/mock_app_mgr_service.h @@ -46,6 +46,8 @@ public: MOCK_METHOD2(GetSystemMemoryAttr, void(SystemMemoryAttr &memoryInfo, std::string &strConfig)); MOCK_METHOD0(StartupResidentProcess, void()); MOCK_METHOD1(AddAbilityStageDone, void(const int32_t recordId)); + MOCK_METHOD1(RegisterApplicationStateObserver, int32_t(const sptr &observer)); + MOCK_METHOD1(UnregisterApplicationStateObserver, int32_t(const sptr &observer)); virtual void RegisterAppStateCallback(const sptr &callback) { diff --git a/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp b/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp index 4cc21f2da..4b7f1e954 100644 --- a/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp +++ b/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp @@ -23,6 +23,7 @@ #include "app_record_id.h" #include "mock_application.h" #include "mock_app_mgr_service.h" +#include "application_state_observer_stub.h" using namespace testing::ext; @@ -266,7 +267,6 @@ HWTEST_F(AmsIpcAppMgrInterfaceTest, GetAllRunningProcesses_010, TestSize.Level1) APP_LOGD("GetAllRunningProcesses_009 end"); } - /* * Feature: AMS * Function: IPC @@ -301,5 +301,53 @@ HWTEST_F(AmsIpcAppMgrInterfaceTest, GetSystemMemoryAttr_0100, TestSize.Level1) APP_LOGD("GetSystemMemoryAttr_0100 end"); } + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, RegisterApplicationStateObserver_001, TestSize.Level0) +{ + APP_LOGD("RegisterApplicationStateObserver_001 start"); + + sptr observer = new ApplicationStateObserverStub(); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, RegisterApplicationStateObserver(_)).Times(1).WillOnce(Return(OHOS::NO_ERROR)); + + int32_t err = appMgrClient->RegisterApplicationStateObserver(observer); + + EXPECT_EQ(OHOS::NO_ERROR, err); + + APP_LOGD("RegisterApplicationStateObserver_001 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, UnregisterApplicationStateObserver_001, TestSize.Level0) +{ + APP_LOGD("UnregisterApplicationStateObserver_001 start"); + + sptr observer = new ApplicationStateObserverStub(); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, UnregisterApplicationStateObserver(_)).Times(1).WillOnce(Return(OHOS::NO_ERROR)); + + int32_t err = appMgrClient->UnregisterApplicationStateObserver(observer); + + EXPECT_EQ(OHOS::NO_ERROR, err); + + APP_LOGD("UnregisterApplicationStateObserver_001 end"); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp index 5eaa9039a..6734c2ef1 100644 --- a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp +++ b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp @@ -23,6 +23,7 @@ #include "app_state_callback_host.h" #include "mock_ability_token.h" #include "mock_app_mgr_service_inner.h" +#include "application_state_observer_stub.h" using namespace testing; using namespace testing::ext; @@ -402,5 +403,45 @@ HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_010, TestSize.Level1) APP_LOGD("AmsMgrScheduler_010 end."); } + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsMgrSchedulerTest, RegisterApplicationStateObserver_001, TestSize.Level0) +{ + APP_LOGD("RegisterApplicationStateObserver_001 start"); + sptr observer = new ApplicationStateObserverStub(); + auto mockAppMgrServiceInner = std::make_shared(); + mockAppMgrServiceInner->RegisterApplicationStateObserver(observer); + int32_t err = mockAppMgrServiceInner->RegisterApplicationStateObserver(observer); + // repeat register return ERR_INVALID_VALUE + EXPECT_EQ(ERR_INVALID_VALUE, err); + APP_LOGD("RegisterApplicationStateObserver_001 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsMgrSchedulerTest, UnregisterApplicationStateObserver_001, TestSize.Level0) +{ + APP_LOGD("UnregisterApplicationStateObserver_001 start"); + sptr observer = new ApplicationStateObserverStub(); + auto mockAppMgrServiceInner = std::make_shared(); + int32_t err1 = mockAppMgrServiceInner->UnregisterApplicationStateObserver(observer); + // unregister not exist return ERR_INVALID_VALUE + EXPECT_EQ(ERR_INVALID_VALUE, err1); + int32_t err2 = mockAppMgrServiceInner->UnregisterApplicationStateObserver(nullptr); + // unregister null return ERR_INVALID_VALUE + EXPECT_EQ(ERR_INVALID_VALUE, err2); + APP_LOGD("UnregisterApplicationStateObserver_001 end"); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/formmgr/include/form_item_info.h b/services/formmgr/include/form_item_info.h index 3106ed83c..e4f8399ce 100644 --- a/services/formmgr/include/form_item_info.h +++ b/services/formmgr/include/form_item_info.h @@ -21,6 +21,7 @@ #include #include #include "form_record.h" +#include "form_info.h" namespace OHOS { namespace AppExecFwk { @@ -220,6 +221,67 @@ public: * @param isFormVisibleNotify visible notify or not. */ void SetFormVisibleNotify(bool isFormVisibleNotify); + /** + * @brief Get formSrc_. + * @return formSrc_. + */ + std::string GetFormSrc() const; + /** + * @brief Set value of formSrc_. + * @param formSrc form src. + */ + void SetFormSrc(const std::string &formSrc); + /** + * @brief Get formWindow_. + * @return formWindow_. + */ + FormWindow GetFormWindow() const; + /** + * @brief Set value of formWindow_. + * @param formWindow form window. + */ + void SetFormWindow(const FormWindow &formWindow); + /** + * @brief Get versionCode_. + * @return versionCode_. + */ + uint32_t GetVersionCode() const; + /** + * @brief Set value of versionCode_. + * @param versionCode bundle version code. + */ + void SetVersionCode(const uint32_t versionCode); + /** + * @brief Get versionName_. + * @return versionName_. + */ + std::string GetVersionName() const; + /** + * @brief Set value of versionName_. + * @param versionName bundle version name. + */ + void SetVersionName(const std::string &versionName); + /** + * @brief Get compatibleVersion_. + * @return compatibleVersion_. + */ + uint32_t GetCompatibleVersion() const; + /** + * @brief Set value of compatibleVersion_. + * @param compatibleVersion API compatible version. + */ + void SetCompatibleVersion(const uint32_t &compatibleVersion); + /** + * @brief Get icon_. + * @return icon_. + */ + std::string GetIcon() const; + /** + * @brief Set value of icon_. + * @param icon ability icon. + */ + void SetIcon(const std::string &icon); + private: /** * @brief Equal or not. @@ -228,7 +290,7 @@ private: * @return Equal or not */ bool IsEqual(const std::string &left, const std::string &right); - + private: int64_t formId_ = -1; std::string packageName_ = ""; @@ -244,6 +306,12 @@ private: std::vector hapSourceDirs_; bool temporaryFlag_ = false; bool formVisibleNotify_ = false; + std::string formSrc_ = ""; + FormWindow formWindow_; + uint32_t versionCode_ = 0; + std::string versionName_ = ""; + uint32_t compatibleVersion_ = 0; + std::string icon_ = ""; std::string jsComponentName_ = ""; std::string abilityModuleName_ = ""; diff --git a/services/formmgr/include/form_record.h b/services/formmgr/include/form_record.h index 78a00aea7..ffb7db76d 100644 --- a/services/formmgr/include/form_record.h +++ b/services/formmgr/include/form_record.h @@ -18,6 +18,7 @@ #include #include "form_provider_info.h" +#include "form_info.h" namespace OHOS { namespace AppExecFwk { @@ -51,6 +52,12 @@ public: bool formVisibleNotify = false; int formVisibleNotifyState = 0; int userId = 0; + std::string formSrc = ""; + FormWindow formWindow; + uint32_t versionCode = 0; + std::string versionName = ""; + uint32_t compatibleVersion = 0; + std::string icon = ""; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/formmgr/src/form_acquire_connection.cpp b/services/formmgr/src/form_acquire_connection.cpp index 3cd1770f2..c6c2eef5f 100644 --- a/services/formmgr/src/form_acquire_connection.cpp +++ b/services/formmgr/src/form_acquire_connection.cpp @@ -51,7 +51,7 @@ void FormAcquireConnection::OnAbilityConnectDone( APP_LOGI("%{public}s called.", __func__); if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", __func__, element.GetAbilityName().c_str(), formId_, resultCode); return; } @@ -59,6 +59,7 @@ void FormAcquireConnection::OnAbilityConnectDone( Want want; want.SetParams(wantParams_); FormUtil::CreateFormWant(info_.GetFormName(), info_.GetSpecificationId(), info_.IsTemporaryForm(), want); + want.SetElementName(info_.GetProviderBundleName(), info_.GetAbilityName()); if (want.GetBoolParam(Constants::RECREATE_FORM_KEY, false)) { want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); } else { diff --git a/services/formmgr/src/form_data_mgr.cpp b/services/formmgr/src/form_data_mgr.cpp index 0809a2a49..ff98d0fec 100644 --- a/services/formmgr/src/form_data_mgr.cpp +++ b/services/formmgr/src/form_data_mgr.cpp @@ -161,6 +161,13 @@ FormRecord FormDataMgr::CreateFormRecord(const FormItemInfo &formInfo, const int newRecord.formTempFlg = formInfo.IsTemporaryForm(); newRecord.formVisibleNotify = formInfo.IsFormVisibleNotify(); newRecord.jsFormCodePath = formInfo.GetHapSourceByModuleName(newRecord.moduleName); + newRecord.formSrc = formInfo.GetFormSrc(); + newRecord.formWindow = formInfo.GetFormWindow(); + newRecord.versionName = formInfo.GetVersionName(); + newRecord.versionCode = formInfo.GetVersionCode(); + newRecord.compatibleVersion = formInfo.GetCompatibleVersion(); + newRecord.icon = formInfo.GetIcon(); + newRecord.formVisibleNotifyState = 0; if (newRecord.isEnableUpdate) { ParseUpdateConfig(newRecord, formInfo); @@ -188,6 +195,12 @@ void FormDataMgr::CreateFormInfo(const int64_t formId, const FormRecord &record, formInfo.abilityName = record.abilityName; formInfo.formName = record.formName; formInfo.formTempFlg = record.formTempFlg; + formInfo.formSrc = record.formSrc; + formInfo.formWindow = record.formWindow; + formInfo.versionCode = record.versionCode; + formInfo.versionName = record.versionName; + formInfo.compatibleVersion = record.compatibleVersion; + formInfo.icon = record.icon; } /** * @brief Check temp form count is max. diff --git a/services/formmgr/src/form_dump_mgr.cpp b/services/formmgr/src/form_dump_mgr.cpp index 1961cc2ff..19fb1417b 100644 --- a/services/formmgr/src/form_dump_mgr.cpp +++ b/services/formmgr/src/form_dump_mgr.cpp @@ -134,6 +134,13 @@ void FormDumpMgr::DumpFormInfo(const FormRecord &formRecordInfo, std::string &fo formInfo += " formTempFlg [" + std::to_string(formRecordInfo.formTempFlg) + "]"; formInfo += " formVisibleNotify [" + std::to_string(formRecordInfo.formVisibleNotify) + "]"; formInfo += " formVisibleNotifyState [" + std::to_string(formRecordInfo.formVisibleNotifyState) + "]"; + formInfo += " formSrc [" + formRecordInfo.formSrc + "]"; + formInfo += " designWidth [" + std::to_string(formRecordInfo.formWindow.designWidth) + "]"; + formInfo += " autoDesignWidth [" + std::to_string(formRecordInfo.formWindow.autoDesignWidth) + "]"; + formInfo += " versionCode [" + std::to_string(formRecordInfo.versionCode) + "]"; + formInfo += " versionName [" + formRecordInfo.versionName + "]"; + formInfo += " compatibleVersion [" + std::to_string(formRecordInfo.compatibleVersion) + "]"; + formInfo += " icon [" + formRecordInfo.icon + "]"; if (formRecordInfo.hapSourceDirs.size() > 0) { formInfo += " hapSourceDirs ["; diff --git a/services/formmgr/src/form_item_info.cpp b/services/formmgr/src/form_item_info.cpp index b686c4f61..6024d0b58 100644 --- a/services/formmgr/src/form_item_info.cpp +++ b/services/formmgr/src/form_item_info.cpp @@ -1,370 +1,467 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "app_log_wrapper.h" -#include "form_item_info.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @brief Get formId_. - * @return formId_. - */ -int64_t FormItemInfo::GetFormId() const -{ - return formId_; -} -/** - * @brief Get packageName_. - * @return packageName_. - */ -std::string FormItemInfo::GetPackageName() const -{ - return packageName_; -} -/** - * @brief Get providerBundleName_. - * @return providerBundleName_. - */ -std::string FormItemInfo::GetProviderBundleName() const -{ - return providerBundleName_; -} -/** - * @brief Get hostBundleName_. - * @return hostBundleName_. - */ -std::string FormItemInfo::GetHostBundleName() const -{ - return hostBundleName_; -} -/** - * @brief Get moduleName_. - * @return moduleName_. - */ -std::string FormItemInfo::GetModuleName() const -{ - return moduleName_; -} -/** - * @brief Get abilityName_. - * @return abilityName_. - */ -std::string FormItemInfo::GetAbilityName() const -{ - return abilityName_; -} -/** - * @brief Get formName_. - * @return formName_. - */ -std::string FormItemInfo::GetFormName() const -{ - return formName_; -} -/** - * @brief Get jsComponentName_. - * @return jsComponentName_. - */ -std::string FormItemInfo::GetJsComponentName() const -{ - return jsComponentName_; -} -/** - * @brief Get abilityModuleName_. - * @return abilityModuleName_. - */ -std::string FormItemInfo::GetAbilityModuleName() const -{ - return abilityModuleName_; -} -/** - * @brief Get specificationId_. - * @return specificationId_. - */ -int FormItemInfo::GetSpecificationId() const -{ - return specificationId_; -} - -/** - * @brief Obtains the updageFlag. - * @return Returns updageFlag. - */ -bool FormItemInfo::IsEnableUpdateFlag() const -{ - return updateFlag_; -} -/** - * @brief Get updateDuration_. - * @return updateDuration_. - */ -int FormItemInfo::GetUpdateDuration() const -{ - return updateDuration_; -} -/** - * @brief Get scheduledUpdateTime_. - * @return scheduledUpdateTime_. - */ -std::string FormItemInfo::GetScheduledUpdateTime() const -{ - return scheduledUpdateTime_; -} - -/** - * @brief Get hapSourceDirs_. - * @param dirs Hap source dirs. - * @return Returns true on success, false on failure. - */ -bool FormItemInfo::GetHapSourceDirs(std::vector &dirs) const -{ - if (hapSourceDirs_.size() > 0) { - dirs.assign(hapSourceDirs_.begin(), hapSourceDirs_.end()); - return true; - } - return false; -} -/** - * @brief Set value of hapSourceDirs_. - * @param hapSourceDirs Hap source dirs. - */ -void FormItemInfo::SetHapSourceDirs(const std::vector &hapSourceDirs) -{ - hapSourceDirs_ = hapSourceDirs; -} -/** - * @brief Obtains the temporaryFlag. - * @return Returns temporaryFlag. - */ -bool FormItemInfo::IsTemporaryForm() const -{ - return temporaryFlag_; -} - -/** - * @brief Obtains the hap source by ability module name. - * @param moduleName ability module name - * @return Returns hap source. - */ -std::string FormItemInfo::GetHapSourceByModuleName(const std::string &moduleName) const -{ - auto iter = moduleInfoMap_.find(moduleName); - if (iter != moduleInfoMap_.end()) { - return iter->second; - } - return ""; -} -/** - * @brief Check if item valid or not. - * @return Valid or not - */ -bool FormItemInfo::IsValidItem() const -{ - if (providerBundleName_.empty() || moduleName_.empty() - || abilityName_.empty() || formName_.empty()) { - return false; - } - return true; -} -/** - * @brief Check if item match or not. - * @return Match or not - */ -bool FormItemInfo::IsMatch(const FormRecord &record) const -{ - APP_LOGD("match data"); - APP_LOGD("FormRecord.bundleName : %{public}s", record.bundleName.c_str()); - APP_LOGD("FormRecord.moduleName : %{public}s", record.moduleName.c_str()); - APP_LOGD("FormRecord.abilityName : %{public}s", record.abilityName.c_str()); - APP_LOGD("FormRecord.formName : %{public}s", record.formName.c_str()); - APP_LOGD("FormRecord.specification : %{public}d", record.specification); - - APP_LOGD("FormItemInfo.providerBundleName_ : %{public}s", providerBundleName_.c_str()); - APP_LOGD("FormItemInfo.moduleName : %{public}s", moduleName_.c_str()); - APP_LOGD("FormItemInfo.abilityName : %{public}s", abilityName_.c_str()); - APP_LOGD("FormItemInfo.formName : %{public}s", formName_.c_str()); - APP_LOGD("FormItemInfo.specification : %{public}d", specificationId_); - - return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) - && (record.abilityName == abilityName_) && (record.formName == formName_) - && (record.specification == specificationId_); -} -/** - * @brief Check if form config same or not. - * @return Same or not - */ -bool FormItemInfo::IsSameFormConfig(const FormRecord &record) const -{ - return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) - && (record.abilityName == abilityName_) && (record.formName == formName_); -} - -/** - * @brief Check if visible notify or not. - * @return visible notify or not - */ -bool FormItemInfo::IsFormVisibleNotify() const -{ - return formVisibleNotify_; -} -/** - * @brief Equal or not. - * @param left left string. - * @param right right string. - * @return Equal or not - */ -bool FormItemInfo::IsEqual(const std::string &left, const std::string &right) -{ - return left == right; -} -/** - * @brief Set value of formId_. - * @param formId Form Id. - */ -void FormItemInfo::SetFormId(int64_t formId) -{ - formId_ = formId; -} -/** - * @brief Set value of packageName_. - * @param packageName Package name. - */ -void FormItemInfo::SetPackageName(const std::string &packageName) -{ - packageName_ = packageName; -} -/** - * @brief Set value of providerBundleName_. - * @param providerBundleName Provider bundle Name. - */ -void FormItemInfo::SetProviderBundleName(const std::string &providerBundleName) -{ - providerBundleName_ = providerBundleName; -} -/** - * @brief Set value of hostBundleName_. - * @param hostBundleName Host bundle Name. - */ -void FormItemInfo::SetHostBundleName(const std::string &hostBundleName) -{ - hostBundleName_ = hostBundleName; -} -/** - * @brief Set value of moduleName_. - * @param moduleName Module Name. - */ -void FormItemInfo::SetModuleName(const std::string &moduleName) -{ - moduleName_ = moduleName; -} -/** - * @brief Set value of abilityName_. - * @param abilityName Ability name. - */ -void FormItemInfo::SetAbilityName(const std::string &abilityName) -{ - abilityName_ = abilityName; -} -/** - * @brief Set value of formName_. - * @param formName Form name. - */ -void FormItemInfo::SetFormName(const std::string &formName) -{ - formName_ = formName; -} -/** - * @brief Set value of jsComponentName_. - * @param jsComponentName Js component name. - */ -void FormItemInfo::SetJsComponentName(const std::string &jsComponentName) -{ - jsComponentName_ = jsComponentName; -} -/** - * @brief Set value of abilityModuleName_. - * @param abilityModuleName ability module name_. - */ -void FormItemInfo::SetAbilityModuleName(const std::string &abilityModuleName) -{ - abilityModuleName_ = abilityModuleName; -} -/** - * @brief Set value of specificationId_. - * @param specificationId Specification id. - */ -void FormItemInfo::SetSpecificationId(const int specificationId) -{ - specificationId_ = specificationId; -} -/** - * @brief Set value of updateFlag_. - * @param IsEnableUpdateFlag Enable update flag or not. - */ -void FormItemInfo::SetEnableUpdateFlag(bool IsEnableUpdateFlag) -{ - updateFlag_ = IsEnableUpdateFlag; -} -/** - * @brief Set value of updateDuration_. - * @param updateDuration Update duration. - */ -void FormItemInfo::SetUpdateDuration(int updateDuration) -{ - updateDuration_ = updateDuration; -} -/** - * @brief Set value of scheduledUpdateTime_. - * @param scheduledUpdateTime Scheduled update time. - */ -void FormItemInfo::SetScheduledUpdateTime(const std::string &scheduledUpdateTime) -{ - scheduledUpdateTime_ = scheduledUpdateTime; -} -/** - * @brief Add hap source dir. - * @param hapSourceDir Hap source dir. - */ -void FormItemInfo::AddHapSourceDirs(const std::string &hapSourceDir) -{ - hapSourceDirs_.emplace_back(hapSourceDir); -} -/** - * @brief Set value of temporaryFlag_. - * @param temporaryFlag Temporary flag. - */ -void FormItemInfo::SetTemporaryFlag(bool temporaryFlag) -{ - temporaryFlag_ = temporaryFlag; -} -/** - * @brief Add module info. - * @param moduleName Module name. - * @param moduleSourceDir Module source dir. - */ -void FormItemInfo::AddModuleInfo(const std::string &moduleName, const std::string &moduleSourceDir) -{ - moduleInfoMap_.emplace(std::make_pair(moduleName, moduleSourceDir)); -} -/** - * @brief Set value of formVisibleNotify_. - * @param isFormVisibleNotify visible notify or not. - */ -void FormItemInfo::SetFormVisibleNotify(bool isFormVisibleNotify) -{ - formVisibleNotify_ = isFormVisibleNotify; -} -} // namespace AppExecFwk +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "app_log_wrapper.h" +#include "form_item_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Get formId_. + * @return formId_. + */ +int64_t FormItemInfo::GetFormId() const +{ + return formId_; +} +/** + * @brief Get packageName_. + * @return packageName_. + */ +std::string FormItemInfo::GetPackageName() const +{ + return packageName_; +} +/** + * @brief Get providerBundleName_. + * @return providerBundleName_. + */ +std::string FormItemInfo::GetProviderBundleName() const +{ + return providerBundleName_; +} +/** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ +std::string FormItemInfo::GetHostBundleName() const +{ + return hostBundleName_; +} +/** + * @brief Get moduleName_. + * @return moduleName_. + */ +std::string FormItemInfo::GetModuleName() const +{ + return moduleName_; +} +/** + * @brief Get abilityName_. + * @return abilityName_. + */ +std::string FormItemInfo::GetAbilityName() const +{ + return abilityName_; +} +/** + * @brief Get formName_. + * @return formName_. + */ +std::string FormItemInfo::GetFormName() const +{ + return formName_; +} +/** + * @brief Get jsComponentName_. + * @return jsComponentName_. + */ +std::string FormItemInfo::GetJsComponentName() const +{ + return jsComponentName_; +} +/** + * @brief Get abilityModuleName_. + * @return abilityModuleName_. + */ +std::string FormItemInfo::GetAbilityModuleName() const +{ + return abilityModuleName_; +} +/** + * @brief Get specificationId_. + * @return specificationId_. + */ +int FormItemInfo::GetSpecificationId() const +{ + return specificationId_; +} + +/** + * @brief Obtains the updageFlag. + * @return Returns updageFlag. + */ +bool FormItemInfo::IsEnableUpdateFlag() const +{ + return updateFlag_; +} +/** + * @brief Get updateDuration_. + * @return updateDuration_. + */ +int FormItemInfo::GetUpdateDuration() const +{ + return updateDuration_; +} +/** + * @brief Get scheduledUpdateTime_. + * @return scheduledUpdateTime_. + */ +std::string FormItemInfo::GetScheduledUpdateTime() const +{ + return scheduledUpdateTime_; +} + +/** + * @brief Get hapSourceDirs_. + * @param dirs Hap source dirs. + * @return Returns true on success, false on failure. + */ +bool FormItemInfo::GetHapSourceDirs(std::vector &dirs) const +{ + if (hapSourceDirs_.size() > 0) { + dirs.assign(hapSourceDirs_.begin(), hapSourceDirs_.end()); + return true; + } + return false; +} +/** + * @brief Set value of hapSourceDirs_. + * @param hapSourceDirs Hap source dirs. + */ +void FormItemInfo::SetHapSourceDirs(const std::vector &hapSourceDirs) +{ + hapSourceDirs_ = hapSourceDirs; +} +/** + * @brief Obtains the temporaryFlag. + * @return Returns temporaryFlag. + */ +bool FormItemInfo::IsTemporaryForm() const +{ + return temporaryFlag_; +} + +/** + * @brief Obtains the hap source by ability module name. + * @param moduleName ability module name + * @return Returns hap source. + */ +std::string FormItemInfo::GetHapSourceByModuleName(const std::string &moduleName) const +{ + auto iter = moduleInfoMap_.find(moduleName); + if (iter != moduleInfoMap_.end()) { + return iter->second; + } + return ""; +} +/** + * @brief Check if item valid or not. + * @return Valid or not + */ +bool FormItemInfo::IsValidItem() const +{ + if (providerBundleName_.empty() || moduleName_.empty() + || abilityName_.empty() || formName_.empty()) { + return false; + } + return true; +} +/** + * @brief Check if item match or not. + * @return Match or not + */ +bool FormItemInfo::IsMatch(const FormRecord &record) const +{ + APP_LOGD("match data"); + APP_LOGD("FormRecord.bundleName : %{public}s", record.bundleName.c_str()); + APP_LOGD("FormRecord.moduleName : %{public}s", record.moduleName.c_str()); + APP_LOGD("FormRecord.abilityName : %{public}s", record.abilityName.c_str()); + APP_LOGD("FormRecord.formName : %{public}s", record.formName.c_str()); + APP_LOGD("FormRecord.specification : %{public}d", record.specification); + + APP_LOGD("FormItemInfo.providerBundleName_ : %{public}s", providerBundleName_.c_str()); + APP_LOGD("FormItemInfo.moduleName : %{public}s", moduleName_.c_str()); + APP_LOGD("FormItemInfo.abilityName : %{public}s", abilityName_.c_str()); + APP_LOGD("FormItemInfo.formName : %{public}s", formName_.c_str()); + APP_LOGD("FormItemInfo.specification : %{public}d", specificationId_); + + return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) + && (record.abilityName == abilityName_) && (record.formName == formName_) + && (record.specification == specificationId_); +} +/** + * @brief Check if form config same or not. + * @return Same or not + */ +bool FormItemInfo::IsSameFormConfig(const FormRecord &record) const +{ + return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) + && (record.abilityName == abilityName_) && (record.formName == formName_); +} + +/** + * @brief Check if visible notify or not. + * @return visible notify or not + */ +bool FormItemInfo::IsFormVisibleNotify() const +{ + return formVisibleNotify_; +} +/** + * @brief Equal or not. + * @param left left string. + * @param right right string. + * @return Equal or not + */ +bool FormItemInfo::IsEqual(const std::string &left, const std::string &right) +{ + return left == right; +} +/** + * @brief Set value of formId_. + * @param formId Form Id. + */ +void FormItemInfo::SetFormId(int64_t formId) +{ + formId_ = formId; +} +/** + * @brief Set value of packageName_. + * @param packageName Package name. + */ +void FormItemInfo::SetPackageName(const std::string &packageName) +{ + packageName_ = packageName; +} +/** + * @brief Set value of providerBundleName_. + * @param providerBundleName Provider bundle Name. + */ +void FormItemInfo::SetProviderBundleName(const std::string &providerBundleName) +{ + providerBundleName_ = providerBundleName; +} +/** + * @brief Set value of hostBundleName_. + * @param hostBundleName Host bundle Name. + */ +void FormItemInfo::SetHostBundleName(const std::string &hostBundleName) +{ + hostBundleName_ = hostBundleName; +} +/** + * @brief Set value of moduleName_. + * @param moduleName Module Name. + */ +void FormItemInfo::SetModuleName(const std::string &moduleName) +{ + moduleName_ = moduleName; +} +/** + * @brief Set value of abilityName_. + * @param abilityName Ability name. + */ +void FormItemInfo::SetAbilityName(const std::string &abilityName) +{ + abilityName_ = abilityName; +} +/** + * @brief Set value of formName_. + * @param formName Form name. + */ +void FormItemInfo::SetFormName(const std::string &formName) +{ + formName_ = formName; +} +/** + * @brief Set value of jsComponentName_. + * @param jsComponentName Js component name. + */ +void FormItemInfo::SetJsComponentName(const std::string &jsComponentName) +{ + jsComponentName_ = jsComponentName; +} +/** + * @brief Set value of abilityModuleName_. + * @param abilityModuleName ability module name_. + */ +void FormItemInfo::SetAbilityModuleName(const std::string &abilityModuleName) +{ + abilityModuleName_ = abilityModuleName; +} +/** + * @brief Set value of specificationId_. + * @param specificationId Specification id. + */ +void FormItemInfo::SetSpecificationId(const int specificationId) +{ + specificationId_ = specificationId; +} +/** + * @brief Set value of updateFlag_. + * @param IsEnableUpdateFlag Enable update flag or not. + */ +void FormItemInfo::SetEnableUpdateFlag(bool IsEnableUpdateFlag) +{ + updateFlag_ = IsEnableUpdateFlag; +} +/** + * @brief Set value of updateDuration_. + * @param updateDuration Update duration. + */ +void FormItemInfo::SetUpdateDuration(int updateDuration) +{ + updateDuration_ = updateDuration; +} +/** + * @brief Set value of scheduledUpdateTime_. + * @param scheduledUpdateTime Scheduled update time. + */ +void FormItemInfo::SetScheduledUpdateTime(const std::string &scheduledUpdateTime) +{ + scheduledUpdateTime_ = scheduledUpdateTime; +} +/** + * @brief Add hap source dir. + * @param hapSourceDir Hap source dir. + */ +void FormItemInfo::AddHapSourceDirs(const std::string &hapSourceDir) +{ + hapSourceDirs_.emplace_back(hapSourceDir); +} +/** + * @brief Set value of temporaryFlag_. + * @param temporaryFlag Temporary flag. + */ +void FormItemInfo::SetTemporaryFlag(bool temporaryFlag) +{ + temporaryFlag_ = temporaryFlag; +} +/** + * @brief Add module info. + * @param moduleName Module name. + * @param moduleSourceDir Module source dir. + */ +void FormItemInfo::AddModuleInfo(const std::string &moduleName, const std::string &moduleSourceDir) +{ + moduleInfoMap_.emplace(std::make_pair(moduleName, moduleSourceDir)); +} +/** + * @brief Set value of formVisibleNotify_. + * @param isFormVisibleNotify visible notify or not. + */ +void FormItemInfo::SetFormVisibleNotify(bool isFormVisibleNotify) +{ + formVisibleNotify_ = isFormVisibleNotify; +} +/** + * @brief Get formSrc_. + * @return formSrc_. + */ +std::string FormItemInfo::GetFormSrc() const +{ + return formSrc_; +} +/** + * @brief Set value of formSrc_. + * @param formSrc form src. + */ +void FormItemInfo::SetFormSrc(const std::string &formSrc) +{ + formSrc_ = formSrc; +} +/** + * @brief Get formWindow_. + * @return formWindow_. + */ +FormWindow FormItemInfo::GetFormWindow() const +{ + return formWindow_; +} +/** + * @brief Set value of formWindow_. + * @param formWindow form window. + */ +void FormItemInfo::SetFormWindow(const FormWindow &formWindow) +{ + formWindow_.autoDesignWidth = formWindow.autoDesignWidth; + formWindow_.designWidth = formWindow.designWidth; +} +/** + * @brief Get versionCode_. + * @return versionCode_. + */ +uint32_t FormItemInfo::GetVersionCode() const +{ + return versionCode_; +} +/** + * @brief Set value of versionCode_. + * @param versionCode bundle version code. + */ +void FormItemInfo::SetVersionCode(const uint32_t versionCode) +{ + versionCode_ = versionCode; +} +/** + * @brief Get versionName_. + * @return versionName_. + */ +std::string FormItemInfo::GetVersionName() const +{ + return versionName_; +} +/** + * @brief Set value of versionName_. + * @param versionName bundle version name. + */ +void FormItemInfo::SetVersionName(const std::string &versionName) +{ + versionName_ = versionName; +} +/** + * @brief Get compatibleVersion_. + * @return compatibleVersion_. + */ +uint32_t FormItemInfo::GetCompatibleVersion() const +{ + return compatibleVersion_; +} +/** + * @brief Set value of compatibleVersion_. + * @param compatibleVersion bundle version name. + */ +void FormItemInfo::SetCompatibleVersion(const uint32_t &compatibleVersion) +{ + compatibleVersion_ = compatibleVersion; +} +/** + * @brief Get icon_. + * @return icon_. + */ +std::string FormItemInfo::GetIcon() const +{ + return icon_; +} +/** + * @brief Set value of icon_. + * @param icon bundle version name. + */ +void FormItemInfo::SetIcon(const std::string &icon) +{ + icon_ = icon; +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_mgr_adapter.cpp b/services/formmgr/src/form_mgr_adapter.cpp index fc60372f5..a795673c6 100644 --- a/services/formmgr/src/form_mgr_adapter.cpp +++ b/services/formmgr/src/form_mgr_adapter.cpp @@ -394,12 +394,6 @@ int FormMgrAdapter::UpdateForm(const int64_t formId, return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } - // check then form under current user - if (!FormDataMgr::GetInstance().IsCallingUidValid(formRecord.formUserUids)) { - APP_LOGE("%{public}s error, not under current user, formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; - } - // check bundleName match if (formRecord.bundleName.compare(bundleName) != 0) { APP_LOGE("%{public}s error, not match bundleName:%{public}s.", __func__, bundleName.c_str()); @@ -1144,10 +1138,14 @@ bool FormMgrAdapter::IsDimensionValid(const FormInfo &formInfo, int dimensionId) * @param formInfo Form info. * @param itemInfo Form configure info. */ -ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, +ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, const FormInfo &formInfo, FormItemInfo &itemInfo) { itemInfo.SetProviderBundleName(bundleInfo.name); + itemInfo.SetVersionCode(bundleInfo.versionCode); + itemInfo.SetVersionName(bundleInfo.versionName); + itemInfo.SetCompatibleVersion(bundleInfo.compatibleVersion); + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("GetFormInfo, failed to get IBundleMgr."); @@ -1159,6 +1157,9 @@ ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; } itemInfo.SetHostBundleName(hostBundleName); + std::string icon = iBundleMgr->GetAbilityIcon(bundleInfo.name, formInfo.abilityName); + itemInfo.SetIcon(icon); + itemInfo.SetAbilityName(formInfo.abilityName); itemInfo.SetModuleName(formInfo.moduleName); // formInfo.moduleName: bundleMagr do not set itemInfo.SetFormName(formInfo.name); @@ -1167,6 +1168,8 @@ ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, itemInfo.SetScheduledUpdateTime(formInfo.scheduledUpateTime); itemInfo.SetJsComponentName(formInfo.jsComponentName); itemInfo.SetFormVisibleNotify(formInfo.formVisibleNotify); + itemInfo.SetFormSrc(formInfo.src); + itemInfo.SetFormWindow(formInfo.window); for (const auto &abilityInfo : bundleInfo.abilityInfos) { if (abilityInfo.name == formInfo.abilityName) { @@ -1176,7 +1179,7 @@ ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, APP_LOGI("%{public}s moduleInfos size: %{public}zu", __func__, bundleInfo.applicationInfo.moduleInfos.size()); for (const auto &item : bundleInfo.applicationInfo.moduleInfos) { - APP_LOGI("%{public}s moduleInfos, moduleName: %{public}s, moduleSourceDir: %{public}s", __func__, + APP_LOGI("%{public}s moduleInfos, moduleName: %{public}s, moduleSourceDir: %{public}s", __func__, item.moduleName.c_str(), item.moduleSourceDir.c_str()); if (formInfo.moduleName == item.moduleName) { itemInfo.AddHapSourceDirs(item.moduleSourceDir); diff --git a/services/formmgr/src/form_task_mgr.cpp b/services/formmgr/src/form_task_mgr.cpp index cbaa7fa32..c350cb1d6 100644 --- a/services/formmgr/src/form_task_mgr.cpp +++ b/services/formmgr/src/form_task_mgr.cpp @@ -500,7 +500,9 @@ FormJsInfo FormTaskMgr::CreateFormJsInfo(const int64_t formId, const FormRecord form.jsFormCodePath = record.jsFormCodePath; form.formData = record.formProviderInfo.GetFormDataString(); form.formProviderData = record.formProviderInfo.GetFormData(); - APP_LOGI("%{public}s end, jsPath: %{public}s, data: %{public}s", __func__, + form.formSrc = record.formSrc; + form.formWindow = record.formWindow; + APP_LOGI("%{public}s end, jsPath: %{public}s, data: %{public}s", __func__, form.jsFormCodePath.c_str(), form.formData.c_str()); return form; } diff --git a/services/formmgr/test/mock/include/mock_ability_manager.h b/services/formmgr/test/mock/include/mock_ability_manager.h index 41b7dc6f6..0781f3c90 100644 --- a/services/formmgr/test/mock/include/mock_ability_manager.h +++ b/services/formmgr/test/mock/include/mock_ability_manager.h @@ -268,6 +268,53 @@ public: { return 0; } + + virtual int LockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int UnlockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int RegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int UnRegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax, + std::vector &missionInfos) override + { + return 0; + } + + virtual int GetMissionInfo(const std::string& deviceId, int32_t missionId, + MissionInfo &missionInfo) override + { + return 0; + } + + virtual int CleanMission(int32_t missionId) override + { + return 0; + } + + virtual int CleanAllMissions() override + { + return 0; + } + + virtual int MoveMissionToFront(int32_t missionId) override + { + return 0; + } }; class MockAbilityMgrStub : public IRemoteStub { @@ -597,6 +644,52 @@ public: return 0; } + virtual int LockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int UnlockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int RegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int UnRegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax, + std::vector &missionInfos) override + { + return 0; + } + + virtual int GetMissionInfo(const std::string& deviceId, int32_t missionId, + MissionInfo &missionInfo) override + { + return 0; + } + + virtual int CleanMission(int32_t missionId) override + { + return 0; + } + + virtual int CleanAllMissions() override + { + return 0; + } + + virtual int MoveMissionToFront(int32_t missionId) override + { + return 0; + } private: Semaphore sem_; }; diff --git a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn index 337e84522..85496ad4b 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn @@ -66,6 +66,7 @@ ohos_unittest("FmsFormMgrAddFormTest") { #"${services_path}/bundlemgr:bms_target", "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", diff --git a/services/test/mock/include/mock_ability_mgr_host.h b/services/test/mock/include/mock_ability_mgr_host.h index 50b3dedb6..968d6350f 100644 --- a/services/test/mock/include/mock_ability_mgr_host.h +++ b/services/test/mock/include/mock_ability_mgr_host.h @@ -317,6 +317,53 @@ public: { return 0; } + + virtual int LockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int UnlockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int RegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int UnRegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax, + std::vector &missionInfos) override + { + return 0; + } + + virtual int GetMissionInfo(const std::string& deviceId, int32_t missionId, + MissionInfo &missionInfo) override + { + return 0; + } + + virtual int CleanMission(int32_t missionId) override + { + return 0; + } + + virtual int CleanAllMissions() override + { + return 0; + } + + virtual int MoveMissionToFront(int32_t missionId) override + { + return 0; + } }; } // namespace AppExecFwk } // namespace OHOS diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/config.json b/test/resource/formsystemtestability/formSystemTestServiceA/config.json index 9c9e18be8..4fc596162 100644 --- a/test/resource/formsystemtestability/formSystemTestServiceA/config.json +++ b/test/resource/formsystemtestability/formSystemTestServiceA/config.json @@ -48,6 +48,11 @@ "forms": [ { "name": "Form_Js001", + "src": "pages/card/index", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, "description": "form_description", "isDefault": true, "type": "JS", diff --git a/tools/test/systemtest/bm/BUILD.gn b/tools/test/systemtest/bm/BUILD.gn index 92c4d963b..3feddcf9a 100755 --- a/tools/test/systemtest/bm/BUILD.gn +++ b/tools/test/systemtest/bm/BUILD.gn @@ -47,7 +47,7 @@ ohos_systemtest("bm_command_install_system_test") { "ipc:ipc_core", ] resource_config_file = - "//foundation/appexecfwk/standard/test/resource/tools/ohos_test.xml" + "//foundation/appexecfwk/standard/test/resource/tools/ohos_test.xml" } ohos_systemtest("bm_command_uninstall_system_test") { @@ -81,7 +81,7 @@ ohos_systemtest("bm_command_uninstall_system_test") { "ipc:ipc_core", ] resource_config_file = - "//foundation/appexecfwk/standard/test/resource/tools/ohos_test.xml" + "//foundation/appexecfwk/standard/test/resource/tools/ohos_test.xml" } ohos_systemtest("bm_command_dump_system_test") { @@ -115,7 +115,7 @@ ohos_systemtest("bm_command_dump_system_test") { "ipc:ipc_core", ] resource_config_file = - "//foundation/appexecfwk/standard/test/resource/tools/ohos_test.xml" + "//foundation/appexecfwk/standard/test/resource/tools/ohos_test.xml" } group("systemtest") {