Update appexecfwk code on 1.6.

Signed-off-by: dy_study <dingyao5@huawei.com>
This commit is contained in:
dy_study 2022-01-06 17:15:12 +08:00
parent f1f1cfae15
commit e8632b904d
93 changed files with 3853 additions and 484 deletions

16
.gitattributes vendored
View File

@ -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

View File

@ -33,6 +33,7 @@ ohos_shared_library("appexecfwk_base") {
"src/compatible_ability_info.cpp", "src/compatible_ability_info.cpp",
"src/compatible_application_info.cpp", "src/compatible_application_info.cpp",
"src/element_name.cpp", "src/element_name.cpp",
"src/extension_info.cpp",
"src/form_info.cpp", "src/form_info.cpp",
"src/form_js_info.cpp", "src/form_js_info.cpp",
"src/form_provider_data.cpp", "src/form_provider_data.cpp",

View File

@ -208,6 +208,9 @@ struct AbilityInfo : public Parcelable {
bool grantPermission = false; bool grantPermission = false;
bool directLaunch = true; bool directLaunch = true;
AbilitySubType subType = AbilitySubType::UNSPECIFIED; AbilitySubType subType = AbilitySubType::UNSPECIFIED;
// new version fields
std::string srcEntrance;
std::vector<Metadata> metadata;
bool ReadFromParcel(Parcel &parcel); bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override; virtual bool Marshalling(Parcel &parcel) const override;

View File

@ -117,6 +117,10 @@ enum {
ERR_APPEXECFWK_RECOVER_GET_BUNDLEPATH_ERROR = APPEXECFWK_BUNDLEMGR_ERR_OFFSET + 0x0201, // 8520193 ERR_APPEXECFWK_RECOVER_GET_BUNDLEPATH_ERROR = APPEXECFWK_BUNDLEMGR_ERR_OFFSET + 0x0201, // 8520193
ERR_APPEXECFWK_RECOVER_INVALID_BUNDLE_NAME, 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 // Error code for FormMgr

View File

@ -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 <string>
#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<std::string> permissions;
bool visible = false;
std::vector<Metadata> metadata;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_EXTENSION_INFO_H

View File

@ -38,7 +38,7 @@ struct FormCustomizeData {
}; };
struct FormWindow { struct FormWindow {
int32_t designWidth; int32_t designWidth = 0;
bool autoDesignWidth = false; bool autoDesignWidth = false;
}; };
@ -73,6 +73,9 @@ struct FormInfo : public Parcelable {
bool ReadFromParcel(Parcel &parcel); bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override; virtual bool Marshalling(Parcel &parcel) const override;
static FormInfo *Unmarshalling(Parcel &parcel); static FormInfo *Unmarshalling(Parcel &parcel);
private:
bool ReadCustomizeData(Parcel &parcel);
}; };
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -19,6 +19,7 @@
#include <string> #include <string>
#include "form_provider_data.h" #include "form_provider_data.h"
#include "form_info.h"
#include "parcel.h" #include "parcel.h"
namespace OHOS { namespace OHOS {
@ -41,6 +42,12 @@ struct FormJsInfo : public Parcelable {
std::string cssPath; std::string cssPath;
std::string jsPath; std::string jsPath;
std::string fileReousePath; 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); bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override; virtual bool Marshalling(Parcel &parcel) const override;

View File

@ -151,12 +151,12 @@ public:
private: private:
bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const; bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const;
private: private:
nlohmann::json jsonFormProviderData_; nlohmann::json jsonFormProviderData_;
std::map<std::string, std::pair<sptr<Ashmem>, int32_t>> imageDataMap_; std::map<std::string, std::pair<sptr<Ashmem>, int32_t>> imageDataMap_;
std::map<std::string, char *> rawImageBytesMap_; std::map<std::string, char *> rawImageBytesMap_;
int32_t imageDataState_; int32_t imageDataState_ = 0;
}; };
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -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_FORM_ENABLED = "formEnabled";
const std::string JSON_KEY_SRC_PATH = "srcPath"; const std::string JSON_KEY_SRC_PATH = "srcPath";
const std::string JSON_KEY_SRC_LANGUAGE = "srcLanguage"; 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 } // namespace
bool AbilityInfo::ReadFromParcel(Parcel &parcel) 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) void to_json(nlohmann::json &jsonObject, const AbilityInfo &abilityInfo)
{ {
jsonObject = nlohmann::json { jsonObject = nlohmann::json {
@ -345,6 +359,8 @@ void to_json(nlohmann::json &jsonObject, const AbilityInfo &abilityInfo)
{JSON_KEY_LIB_PATH, abilityInfo.libPath}, {JSON_KEY_LIB_PATH, abilityInfo.libPath},
{JSON_KEY_META_DATA, abilityInfo.metaData}, {JSON_KEY_META_DATA, abilityInfo.metaData},
{JSON_KEY_FORM_ENABLED, abilityInfo.formEnabled}, {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); ArrayType::OBJECT);
} }
void from_json(const nlohmann::json &jsonObject, Metadata &metadata)
{
const auto &jsonObjectEnd = jsonObject.end();
int32_t parseResult = ERR_OK;
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
META_DATA_NAME,
metadata.name,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
META_DATA_VALUE,
metadata.value,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(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) void from_json(const nlohmann::json &jsonObject, AbilityInfo &abilityInfo)
{ {
const auto &jsonObjectEnd = jsonObject.end(); const auto &jsonObjectEnd = jsonObject.end();
@ -748,6 +797,25 @@ void from_json(const nlohmann::json &jsonObject, AbilityInfo &abilityInfo)
false, false,
parseResult, parseResult,
ArrayType::NOT_ARRAY); ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
SRC_ENTRANCE,
abilityInfo.srcEntrance,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::vector<Metadata>>(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 void AbilityInfo::ConvertToCompatiableAbilityInfo(CompatibleAbilityInfo& compatibleAbilityInfo) const

View File

@ -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 <fcntl.h>
#include <string>
#include <unistd.h>
#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<std::string>(jsonObject,
jsonObjectEnd,
BUNDLE_NAME,
extensionInfo.bundleName,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
MODULE_NAME,
extensionInfo.moduleName,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
NAME,
extensionInfo.name,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
SRC_ENTRANCE,
extensionInfo.srcEntrance,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
ICON,
extensionInfo.icon,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<int32_t>(jsonObject,
jsonObjectEnd,
ICON_ID,
extensionInfo.iconId,
JsonType::NUMBER,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
LABEL,
extensionInfo.label,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<int32_t>(jsonObject,
jsonObjectEnd,
LABEL_ID,
extensionInfo.labelId,
JsonType::NUMBER,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
DESCRIPTION,
extensionInfo.description,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<int32_t>(jsonObject,
jsonObjectEnd,
DESCRIPTION_ID,
extensionInfo.descriptionId,
JsonType::NUMBER,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::string>(jsonObject,
jsonObjectEnd,
TYPE,
extensionInfo.type,
JsonType::STRING,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::vector<std::string>>(jsonObject,
jsonObjectEnd,
PERMISSIONS,
extensionInfo.permissions,
JsonType::ARRAY,
false,
parseResult,
ArrayType::STRING);
GetValueIfFindKey<bool>(jsonObject,
jsonObjectEnd,
VISIBLE,
extensionInfo.visible,
JsonType::BOOLEAN,
false,
parseResult,
ArrayType::NOT_ARRAY);
GetValueIfFindKey<std::vector<Metadata>>(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

View File

@ -15,17 +15,17 @@
#include "form_info.h" #include "form_info.h"
#include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <string.h>
#include <unistd.h> #include <unistd.h>
#include <cerrno>
#include <cstring> #include "app_log_wrapper.h"
#include "bundle_constants.h"
#include "json_serializer.h" #include "json_serializer.h"
#include "nlohmann/json.hpp" #include "nlohmann/json.hpp"
#include "string_ex.h"
#include "parcel_macro.h" #include "parcel_macro.h"
#include "app_log_wrapper.h" #include "string_ex.h"
#include "nlohmann/json.hpp"
#include "bundle_constants.h"
namespace OHOS { namespace OHOS {
namespace AppExecFwk { namespace AppExecFwk {
@ -125,7 +125,10 @@ bool FormInfo::ReadFromParcel(Parcel &parcel)
portraitLayouts.emplace_back(Str16ToStr8(parcel.ReadString16())); portraitLayouts.emplace_back(Str16ToStr8(parcel.ReadString16()));
} }
ReadFromParcelCustomizeData(customizeDatas, parcel); if (!ReadCustomizeData(parcel)) {
return false;
}
window.designWidth = parcel.ReadInt32(); window.designWidth = parcel.ReadInt32();
window.autoDesignWidth = parcel.ReadBool(); window.autoDesignWidth = parcel.ReadBool();
return true; return true;
@ -200,7 +203,7 @@ void to_json(nlohmann::json &jsonObject, const FormCustomizeData &customizeDatas
jsonObject = nlohmann::json{ jsonObject = nlohmann::json{
{JSON_KEY_NAME, customizeDatas.name}, {JSON_KEY_NAME, customizeDatas.name},
{JSON_KEY_VALUE, customizeDatas.value} {JSON_KEY_VALUE, customizeDatas.value}
}; };
} }
void to_json(nlohmann::json &jsonObject, const FormWindow &formWindow) void to_json(nlohmann::json &jsonObject, const FormWindow &formWindow)

View File

@ -29,6 +29,15 @@ bool FormJsInfo::ReadFromParcel(Parcel &parcel)
jsFormCodePath = Str16ToStr8(parcel.ReadString16()); jsFormCodePath = Str16ToStr8(parcel.ReadString16());
formData = 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<FormProviderData>(); auto bindingData = parcel.ReadParcelable<FormProviderData>();
if (nullptr == bindingData){ if (nullptr == bindingData){
return false; return false;
@ -80,6 +89,35 @@ bool FormJsInfo::Marshalling(Parcel &parcel) const
return false; 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 // write formProviderData
if (!parcel.WriteParcelable(&formProviderData)) { if (!parcel.WriteParcelable(&formProviderData)) {
return false; return false;

View File

@ -44,6 +44,7 @@ ohos_shared_library("appexecfwk_core") {
] ]
sources = [ sources = [
"src/appmgr/ability_state_data.cpp",
"src/appmgr/ams_mgr_proxy.cpp", "src/appmgr/ams_mgr_proxy.cpp",
"src/appmgr/ams_mgr_stub.cpp", "src/appmgr/ams_mgr_stub.cpp",
"src/appmgr/app_launch_data.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_service_manager.cpp",
"src/appmgr/app_state_callback_host.cpp", "src/appmgr/app_state_callback_host.cpp",
"src/appmgr/app_state_callback_proxy.cpp", "src/appmgr/app_state_callback_proxy.cpp",
"src/appmgr/app_state_data.cpp",
"src/appmgr/app_task_info.cpp", "src/appmgr/app_task_info.cpp",
"src/appmgr/configuration.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/priority_object.cpp",
"src/appmgr/process_data.cpp",
"src/appmgr/process_info.cpp", "src/appmgr/process_info.cpp",
"src/appmgr/profile.cpp", "src/appmgr/profile.cpp",
"src/bundlemgr/bundle_installer_proxy.cpp", "src/bundlemgr/bundle_installer_proxy.cpp",

View File

@ -17,6 +17,8 @@ appexecfwk_headers = {
"appmgr/iapp_state_callback.h", "appmgr/iapp_state_callback.h",
"appmgr/app_state_callback_host.h", "appmgr/app_state_callback_host.h",
"appmgr/app_mgr_constants.h", "appmgr/app_mgr_constants.h",
"appmgr/iapplication_state_observer.h",
"appmgr/application_state_observer_stub.h",
"bundlemgr/bundle_installer_interface.h", "bundlemgr/bundle_installer_interface.h",
"bundlemgr/bundle_mgr_interface.h", "bundlemgr/bundle_mgr_interface.h",
"bundlemgr/bundle_status_callback_interface.h", "bundlemgr/bundle_status_callback_interface.h",

View File

@ -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 <sys/types.h>
#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<IRemoteObject> token;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_STATE_DATA_H

View File

@ -59,6 +59,15 @@ public:
*/ */
virtual void UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state) = 0; virtual void UpdateAbilityState(const sptr<IRemoteObject> &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<IRemoteObject> &token, const ExtensionState state) = 0;
/** /**
* RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback. * RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback.
* *
@ -134,6 +143,7 @@ public:
LOAD_ABILITY = 0, LOAD_ABILITY = 0,
TERMINATE_ABILITY, TERMINATE_ABILITY,
UPDATE_ABILITY_STATE, UPDATE_ABILITY_STATE,
UPDATE_EXTENSION_STATE,
REGISTER_APP_STATE_CALLBACK, REGISTER_APP_STATE_CALLBACK,
RESET, RESET,
ABILITY_BEHAVIOR_ANALYSIS, ABILITY_BEHAVIOR_ANALYSIS,

View File

@ -56,6 +56,15 @@ public:
*/ */
virtual void UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state) override; virtual void UpdateAbilityState(const sptr<IRemoteObject> &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<IRemoteObject> &token, const ExtensionState state) override;
/** /**
* RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback. * RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback.
* *

View File

@ -33,10 +33,19 @@ public:
virtual int OnRemoteRequest( virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; 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<IRemoteObject> &token, const ExtensionState state) override;
private: private:
int32_t HandleLoadAbility(MessageParcel &data, MessageParcel &reply); int32_t HandleLoadAbility(MessageParcel &data, MessageParcel &reply);
int32_t HandleTerminateAbility(MessageParcel &data, MessageParcel &reply); int32_t HandleTerminateAbility(MessageParcel &data, MessageParcel &reply);
int32_t HandleUpdateAbilityState(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 HandleRegisterAppStateCallback(MessageParcel &data, MessageParcel &reply);
int32_t HandleReset(MessageParcel &data, MessageParcel &reply); int32_t HandleReset(MessageParcel &data, MessageParcel &reply);
int32_t HandleAbilityBehaviorAnalysis(MessageParcel &data, MessageParcel &reply); int32_t HandleAbilityBehaviorAnalysis(MessageParcel &data, MessageParcel &reply);

View File

@ -64,6 +64,15 @@ public:
*/ */
virtual AppMgrResultCode UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state); virtual AppMgrResultCode UpdateAbilityState(const sptr<IRemoteObject> &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<IRemoteObject> &token, const ExtensionState state);
/** /**
* Register Application state callback. * Register Application state callback.
* *

View File

@ -44,6 +44,14 @@ enum class AbilityState {
ABILITY_STATE_END, ABILITY_STATE_END,
}; };
enum class ExtensionState {
EXTENSION_STATE_CREATE = 0,
EXTENSION_STATE_READY,
EXTENSION_STATE_CONNECTED,
EXTENSION_STATE_DISCONNECTED,
EXTENSION_STATE_TERMINATED,
};
enum AppMgrResultCode { enum AppMgrResultCode {
RESULT_OK = 0, RESULT_OK = 0,
ERROR_SERVICE_NOT_READY, ERROR_SERVICE_NOT_READY,

View File

@ -26,6 +26,7 @@
#include "ams_mgr_interface.h" #include "ams_mgr_interface.h"
#include "running_process_info.h" #include "running_process_info.h"
#include "system_memory_attr.h" #include "system_memory_attr.h"
#include "iapplication_state_observer.h"
namespace OHOS { namespace OHOS {
namespace AppExecFwk { namespace AppExecFwk {
@ -155,6 +156,27 @@ public:
*/ */
virtual void StartupResidentProcess() = 0; 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<IApplicationStateObserver> &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<IApplicationStateObserver> &observer) = 0;
/**
* Get foreground applications.
* @param list, foreground apps.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int32_t GetForegroundApplications(std::vector<AppStateData> &list) = 0;
enum class Message { enum class Message {
APP_ATTACH_APPLICATION = 0, APP_ATTACH_APPLICATION = 0,
APP_APPLICATION_FOREGROUNDED, APP_APPLICATION_FOREGROUNDED,
@ -171,6 +193,9 @@ public:
APP_GET_SYSTEM_MEMORY_ATTR, APP_GET_SYSTEM_MEMORY_ATTR,
APP_ADD_ABILITY_STAGE_INFO_DONE, APP_ADD_ABILITY_STAGE_INFO_DONE,
STARTUP_RESIDENT_PROCESS, STARTUP_RESIDENT_PROCESS,
REGISTER_APPLICATION_STATE_OBSERVER,
UNREGISTER_APPLICATION_STATE_OBSERVER,
GET_FOREGROUND_APPLICATIONS,
}; };
}; };
} // namespace AppExecFwk } // namespace AppExecFwk

View File

@ -149,6 +149,27 @@ public:
*/ */
virtual void StartupResidentProcess() override; 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<IApplicationStateObserver> &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<IApplicationStateObserver> &observer) override;
/**
* Get foreground applications.
* @param list, foreground apps.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int32_t GetForegroundApplications(std::vector<AppStateData> &list) override;
private: private:
bool SendTransactCmd(IAppMgr::Message code, MessageParcel &data, MessageParcel &reply); bool SendTransactCmd(IAppMgr::Message code, MessageParcel &data, MessageParcel &reply);
bool WriteInterfaceToken(MessageParcel &data); bool WriteInterfaceToken(MessageParcel &data);

View File

@ -33,6 +33,27 @@ public:
virtual int OnRemoteRequest( virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; 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<IApplicationStateObserver> &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<IApplicationStateObserver> &observer) override;
/**
* Get foreground applications.
* @param list, foreground apps.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int32_t GetForegroundApplications(std::vector<AppStateData> &list) override;
private: private:
int32_t HandleAttachApplication(MessageParcel &data, MessageParcel &reply); int32_t HandleAttachApplication(MessageParcel &data, MessageParcel &reply);
int32_t HandleApplicationForegrounded(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 HandleGetSystemMemoryAttr(MessageParcel &data, MessageParcel &reply);
int32_t HandleAddAbilityStageDone(MessageParcel &data, MessageParcel &reply); int32_t HandleAddAbilityStageDone(MessageParcel &data, MessageParcel &reply);
int32_t HandleStartupResidentProcess(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); using AppMgrFunc = int32_t (AppMgrStub::*)(MessageParcel &data, MessageParcel &reply);
std::map<uint32_t, AppMgrFunc> memberFuncMap_; std::map<uint32_t, AppMgrFunc> memberFuncMap_;

View File

@ -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 <sys/types.h>
#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

View File

@ -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<IApplicationStateObserver> {
public:
explicit ApplicationStateObserverProxy(const sptr<IRemoteObject> &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<ApplicationStateObserverProxy> delegator_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif

View File

@ -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 <map>
#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<IApplicationStateObserver> {
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<uint32_t, ApplicationStateObserverFunc> memberFuncMap_;
DISALLOW_COPY_AND_MOVE(ApplicationStateObserverStub);
};
/**
* @class ApplicationStateObserverRecipient
* ApplicationStateObserverRecipient notices IRemoteBroker died.
*/
class ApplicationStateObserverRecipient : public IRemoteObject::DeathRecipient {
public:
using RemoteDiedHandler = std::function<void(const wptr<IRemoteObject> &)>;
ApplicationStateObserverRecipient(RemoteDiedHandler handler);
virtual ~ApplicationStateObserverRecipient();
virtual void OnRemoteDied(const wptr<IRemoteObject> &remote);
private:
RemoteDiedHandler handler_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_STUB_H

View File

@ -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

View File

@ -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 <sys/types.h>
#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

View File

@ -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<IRemoteObject>();
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

View File

@ -113,6 +113,30 @@ void AmsMgrProxy::UpdateAbilityState(const sptr<IRemoteObject> &token, const Abi
APP_LOGD("end"); APP_LOGD("end");
} }
void AmsMgrProxy::UpdateExtensionState(const sptr<IRemoteObject> &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<int32_t>(state));
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
APP_LOGE("Remote() is NULL");
return;
}
int32_t ret =
remote->SendRequest(static_cast<uint32_t>(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<IAppStateCallback> &callback) void AmsMgrProxy::RegisterAppStateCallback(const sptr<IAppStateCallback> &callback)
{ {
APP_LOGD("start"); APP_LOGD("start");

View File

@ -36,6 +36,8 @@ AmsMgrStub::AmsMgrStub()
&AmsMgrStub::HandleTerminateAbility; &AmsMgrStub::HandleTerminateAbility;
memberFuncMap_[static_cast<uint32_t>(IAmsMgr::Message::UPDATE_ABILITY_STATE)] = memberFuncMap_[static_cast<uint32_t>(IAmsMgr::Message::UPDATE_ABILITY_STATE)] =
&AmsMgrStub::HandleUpdateAbilityState; &AmsMgrStub::HandleUpdateAbilityState;
memberFuncMap_[static_cast<uint32_t>(IAmsMgr::Message::UPDATE_EXTENSION_STATE)] =
&AmsMgrStub::HandleUpdateExtensionState;
memberFuncMap_[static_cast<uint32_t>(IAmsMgr::Message::REGISTER_APP_STATE_CALLBACK)] = memberFuncMap_[static_cast<uint32_t>(IAmsMgr::Message::REGISTER_APP_STATE_CALLBACK)] =
&AmsMgrStub::HandleRegisterAppStateCallback; &AmsMgrStub::HandleRegisterAppStateCallback;
memberFuncMap_[static_cast<uint32_t>(IAmsMgr::Message::RESET)] = &AmsMgrStub::HandleReset; memberFuncMap_[static_cast<uint32_t>(IAmsMgr::Message::RESET)] = &AmsMgrStub::HandleReset;
@ -117,6 +119,14 @@ ErrCode AmsMgrStub::HandleUpdateAbilityState(MessageParcel &data, MessageParcel
return NO_ERROR; return NO_ERROR;
} }
ErrCode AmsMgrStub::HandleUpdateExtensionState(MessageParcel &data, MessageParcel &reply)
{
sptr<IRemoteObject> token = data.ReadParcelable<IRemoteObject>();
int32_t state = data.ReadInt32();
UpdateExtensionState(token, static_cast<ExtensionState>(state));
return NO_ERROR;
}
ErrCode AmsMgrStub::HandleRegisterAppStateCallback(MessageParcel &data, MessageParcel &reply) ErrCode AmsMgrStub::HandleRegisterAppStateCallback(MessageParcel &data, MessageParcel &reply)
{ {
BYTRACE(BYTRACE_TAG_APP); BYTRACE(BYTRACE_TAG_APP);
@ -201,5 +211,8 @@ int32_t AmsMgrStub::HandlePrepareTerminate(MessageParcel &data, MessageParcel &r
PrepareTerminate(token); PrepareTerminate(token);
return NO_ERROR; return NO_ERROR;
} }
void AmsMgrStub::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
{}
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -79,6 +79,19 @@ AppMgrResultCode AppMgrClient::UpdateAbilityState(const sptr<IRemoteObject> &tok
return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED;
} }
AppMgrResultCode AppMgrClient::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
{
sptr<IAppMgr> service = iface_cast<IAppMgr>(remote_);
if (service != nullptr) {
sptr<IAmsMgr> 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<IAppStateCallback> &callback) AppMgrResultCode AppMgrClient::RegisterAppStateCallback(const sptr<IAppStateCallback> &callback)
{ {
sptr<IAppMgr> service = iface_cast<IAppMgr>(remote_); sptr<IAppMgr> service = iface_cast<IAppMgr>(remote_);

View File

@ -421,5 +421,80 @@ int AppMgrProxy::GetParcelableInfos(MessageParcel &reply, std::vector<T> &parcel
APP_LOGD("get parcelable infos success"); APP_LOGD("get parcelable infos success");
return NO_ERROR; return NO_ERROR;
} }
int AppMgrProxy::RegisterApplicationStateObserver(
const sptr<IApplicationStateObserver> &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<uint32_t>(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<IApplicationStateObserver> &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<uint32_t>(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<AppStateData> &list)
{
APP_LOGD("GetForegroundApplications start");
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!WriteInterfaceToken(data)) {
return ERR_FLATTEN_OBJECT;
}
auto error = Remote()->SendRequest(static_cast<uint32_t>(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<AppStateData> info(reply.ReadParcelable<AppStateData>());
if (!info) {
APP_LOGE("Read Parcelable infos failed.");
return ERR_INVALID_VALUE;
}
list.emplace_back(*info);
}
return reply.ReadInt32();
}
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -60,6 +60,12 @@ AppMgrStub::AppMgrStub()
&AppMgrStub::HandleAddAbilityStageDone; &AppMgrStub::HandleAddAbilityStageDone;
memberFuncMap_[static_cast<uint32_t>(IAppMgr::Message::STARTUP_RESIDENT_PROCESS)] = memberFuncMap_[static_cast<uint32_t>(IAppMgr::Message::STARTUP_RESIDENT_PROCESS)] =
&AppMgrStub::HandleStartupResidentProcess; &AppMgrStub::HandleStartupResidentProcess;
memberFuncMap_[static_cast<uint32_t>(IAppMgr::Message::REGISTER_APPLICATION_STATE_OBSERVER)] =
&AppMgrStub::HandleRegisterApplicationStateObserver;
memberFuncMap_[static_cast<uint32_t>(IAppMgr::Message::UNREGISTER_APPLICATION_STATE_OBSERVER)] =
&AppMgrStub::HandleUnregisterApplicationStateObserver;
memberFuncMap_[static_cast<uint32_t>(IAppMgr::Message::GET_FOREGROUND_APPLICATIONS)] =
&AppMgrStub::HandleGetForegroundApplications;
} }
AppMgrStub::~AppMgrStub() AppMgrStub::~AppMgrStub()
@ -231,5 +237,53 @@ int32_t AppMgrStub::HandleStartupResidentProcess(MessageParcel &data, MessagePar
StartupResidentProcess(); StartupResidentProcess();
return NO_ERROR; return NO_ERROR;
} }
int32_t AppMgrStub::HandleRegisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply)
{
auto callback = iface_cast<AppExecFwk::IApplicationStateObserver>(data.ReadParcelable<IRemoteObject>());
int32_t result = RegisterApplicationStateObserver(callback);
reply.WriteInt32(result);
return NO_ERROR;
}
int32_t AppMgrStub::HandleUnregisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply)
{
auto callback = iface_cast<AppExecFwk::IApplicationStateObserver>(data.ReadParcelable<IRemoteObject>());
int32_t result = UnregisterApplicationStateObserver(callback);
reply.WriteInt32(result);
return NO_ERROR;
}
int32_t AppMgrStub::HandleGetForegroundApplications(MessageParcel &data, MessageParcel &reply)
{
std::vector<AppStateData> 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<IApplicationStateObserver> &observer)
{
return NO_ERROR;
}
int32_t AppMgrStub::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
{
return NO_ERROR;
}
int32_t AppMgrStub::GetForegroundApplications(std::vector<AppStateData> &list)
{
return NO_ERROR;
}
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -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

View File

@ -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<IRemoteObject> &impl) : IRemoteProxy<IApplicationStateObserver>(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<IRemoteObject> remote = Remote();
if (remote == nullptr) {
APP_LOGE("Remote() is NULL");
return;
}
int32_t ret = remote->SendRequest(
static_cast<uint32_t>(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<IRemoteObject> remote = Remote();
if (remote == nullptr) {
APP_LOGE("Remote() is NULL");
return;
}
int32_t ret = remote->SendRequest(
static_cast<uint32_t>(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<IRemoteObject> remote = Remote();
if (remote == nullptr) {
APP_LOGE("Remote() is NULL");
return;
}
int32_t ret = remote->SendRequest(
static_cast<uint32_t>(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<IRemoteObject> remote = Remote();
if (remote == nullptr) {
APP_LOGE("Remote() is NULL");
return;
}
int32_t ret = remote->SendRequest(
static_cast<uint32_t>(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<IRemoteObject> remote = Remote();
if (remote == nullptr) {
APP_LOGE("Remote() is NULL");
return;
}
int32_t ret = remote->SendRequest(
static_cast<uint32_t>(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

View File

@ -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<uint32_t>(
IApplicationStateObserver::Message::TRANSACT_ON_FOREGROUND_APPLICATION_CHANGED)] =
&ApplicationStateObserverStub::HandleOnForegroundApplicationChanged;
memberFuncMap_[static_cast<uint32_t>(
IApplicationStateObserver::Message::TRANSACT_ON_ABILITY_STATE_CHANGED)] =
&ApplicationStateObserverStub::HandleOnAbilityStateChanged;
memberFuncMap_[static_cast<uint32_t>(
IApplicationStateObserver::Message::TRANSACT_ON_EXTENSION_STATE_CHANGED)] =
&ApplicationStateObserverStub::HandleOnExtensionStateChanged;
memberFuncMap_[static_cast<uint32_t>(
IApplicationStateObserver::Message::TRANSACT_ON_PROCESS_CREATED)] =
&ApplicationStateObserverStub::HandleOnProcessCreated;
memberFuncMap_[static_cast<uint32_t>(
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<AppStateData> processData(data.ReadParcelable<AppStateData>());
if (!processData) {
APP_LOGE("ReadParcelable<AppStateData> failed");
return ERR_APPEXECFWK_PARCEL_ERROR;
}
OnForegroundApplicationChanged(*processData);
return NO_ERROR;
}
int32_t ApplicationStateObserverStub::HandleOnAbilityStateChanged(MessageParcel &data, MessageParcel &reply)
{
std::unique_ptr<AbilityStateData> abilityStateData(data.ReadParcelable<AbilityStateData>());
if (!abilityStateData) {
APP_LOGE("ReadParcelable<AbilityStateData> failed");
return ERR_APPEXECFWK_PARCEL_ERROR;
}
OnAbilityStateChanged(*abilityStateData);
return NO_ERROR;
}
int32_t ApplicationStateObserverStub::HandleOnExtensionStateChanged(MessageParcel &data, MessageParcel &reply)
{
std::unique_ptr<AbilityStateData> abilityStateData(data.ReadParcelable<AbilityStateData>());
if (!abilityStateData) {
APP_LOGE("ReadParcelable<AbilityStateData> failed");
return ERR_APPEXECFWK_PARCEL_ERROR;
}
OnExtensionStateChanged(*abilityStateData);
return NO_ERROR;
}
int32_t ApplicationStateObserverStub::HandleOnProcessCreated(MessageParcel &data, MessageParcel &reply)
{
std::unique_ptr<ProcessData> processData(data.ReadParcelable<ProcessData>());
if (!processData) {
APP_LOGE("ReadParcelable<ProcessData> failed");
return ERR_APPEXECFWK_PARCEL_ERROR;
}
OnProcessCreated(*processData);
return NO_ERROR;
}
int32_t ApplicationStateObserverStub::HandleOnProcessDied(MessageParcel &data, MessageParcel &reply)
{
std::unique_ptr<ProcessData> processData(data.ReadParcelable<ProcessData>());
if (!processData) {
APP_LOGE("ReadParcelable<ProcessData> failed");
return ERR_APPEXECFWK_PARCEL_ERROR;
}
OnProcessDied(*processData);
return NO_ERROR;
}
void ApplicationStateObserverRecipient::OnRemoteDied(const wptr<IRemoteObject> &__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

View File

@ -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

View File

@ -337,9 +337,9 @@ int FormProviderProxy::FireFormEvent(
MessageParcel reply; MessageParcel reply;
MessageOption option; MessageOption option;
int error = Remote()->SendRequest( int error = Remote()->SendRequest(
static_cast<uint32_t>(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), static_cast<uint32_t>(IFormProvider::Message::FORM_PROVIDER_EVENT_MESSAGE),
data, data,
reply, reply,
option); option);
if (error != ERR_OK) { if (error != ERR_OK) {
APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error);

View File

@ -46,7 +46,7 @@ private:
void InitErrorMessageMap(); void InitErrorMessageMap();
private: private:
std::map<ErrCode, std::string> errorMessageMap_; std::map<ErrCode, std::string> errorMessageMap_;
}; };
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -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:abilitystage_napi",
"//foundation/appexecfwk/standard/kits/appkit/napi/ability_stage_context:abilitystagecontext_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/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/bundlemgr:bundle",
"//foundation/appexecfwk/standard/kits/appkit/napi/context:context_napi", "//foundation/appexecfwk/standard/kits/appkit/napi/context:context_napi",
"//foundation/appexecfwk/standard/kits/appkit/napi/launchermgr:innerbundlemanager", "//foundation/appexecfwk/standard/kits/appkit/napi/launchermgr:innerbundlemanager",

View File

@ -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"
}

View File

@ -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);
}

View File

@ -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 <cstdint>
#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<OHOS::AppExecFwk::IAppMgr> appManager) : appManager_(appManager) {}
~JsAppManager() = default;
static void Finalizer(NativeEngine* engine, void* data, void* hint)
{
HILOG_INFO("JsAbilityContext::Finalizer is called");
std::unique_ptr<JsAppManager>(static_cast<JsAppManager*>(data));
}
static NativeValue* RegisterApplicationStateObserver(NativeEngine* engine, NativeCallbackInfo* info)
{
JsAppManager* me = CheckParamsAndGetThis<JsAppManager>(engine, info);
return (me != nullptr) ? me->OnRegisterApplicationStateObserver(*engine, *info) : nullptr;
}
static NativeValue* UnregisterApplicationStateObserver(NativeEngine* engine, NativeCallbackInfo* info)
{
JsAppManager* me = CheckParamsAndGetThis<JsAppManager>(engine, info);
return (me != nullptr) ? me->OnUnregisterApplicationStateObserver(*engine, *info) : nullptr;
}
static NativeValue* GetForegroundApplications(NativeEngine* engine, NativeCallbackInfo* info)
{
JsAppManager* me = CheckParamsAndGetThis<JsAppManager>(engine, info);
return (me != nullptr) ? me->OnGetForegroundApplications(*engine, *info) : nullptr;
}
private:
sptr<OHOS::AppExecFwk::IAppMgr> 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<JSApplicationStateObserver> 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<JSApplicationStateObserver> observer = nullptr;
napi_get_value_int64(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(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<AppExecFwk::AppStateData> 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<OHOS::AppExecFwk::IAppMgr> GetAppManagerInstance()
{
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::sptr<OHOS::IRemoteObject> appObject = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID);
return OHOS::iface_cast<OHOS::AppExecFwk::IAppMgr>(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<NativeObject>(exportObj);
if (object == nullptr) {
HILOG_INFO("object null");
return nullptr;
}
std::unique_ptr<JsAppManager> jsAppManager =
std::make_unique<JsAppManager>(GetAppManagerInstance());
object->SetNativePointer(jsAppManager.release(), JsAppManager::Finalizer, nullptr);
//make handler
handler_ = std::make_shared<AppExecFwk::EventHandler>(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<JSApplicationStateObserver> jsObserver = this;
auto task = [jsObserver, appStateData]() {
sptr<JSApplicationStateObserver> 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<JSApplicationStateObserver> jsObserver = this;
auto task = [jsObserver, abilityStateData]() {
sptr<JSApplicationStateObserver> 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<JSApplicationStateObserver> jsObserver = this;
auto task = [jsObserver, abilityStateData]() {
sptr<JSApplicationStateObserver> 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<JSApplicationStateObserver> jsObserver = this;
auto task = [jsObserver, processData]() {
sptr<JSApplicationStateObserver> 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<JSApplicationStateObserver> jsObserver = this;
auto task = [jsObserver, processData]() {
sptr<JSApplicationStateObserver> 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<NativeObject>(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<NativeReference>(engine_->CreateReference(jsObserverObject, 1));
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -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<NativeReference> jsObserverObject_ = nullptr;
};
static std::map<int64_t, sptr<JSApplicationStateObserver>> observerIds_;
static int64_t serialNumber_ = 0;
static std::shared_ptr<AppExecFwk::EventHandler> handler_ = nullptr;
} // namespace AbilityRuntime
} // namespace OHOS
#endif // OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_H

View File

@ -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 <cstdint>
#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<NativeObject>(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<NativeObject>(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<NativeObject>(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<AppStateData> &appStateDatas)
{
NativeValue* arrayValue = engine.CreateArray(appStateDatas.size());
NativeArray* array = ConvertNativeValueTo<NativeArray>(arrayValue);
uint32_t index = 0;
for (const auto &appStateData : appStateDatas) {
array->SetElement(index++, CreateJsAppStateData(engine, appStateData));
}
return arrayValue;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -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<AppStateData> &appStateDatas);
} // namespace AbilityRuntime
} // namespace OHOS
#endif // OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H

View File

@ -82,7 +82,7 @@ NativeValue* JsBaseContext::OnCreateBundleContext(NativeEngine& engine, NativeCa
} }
std::string bundleName; std::string bundleName;
if (!ConvertFormJsValue(engine, info.argv[0], bundleName)) { if (!ConvertFromJsValue(engine, info.argv[0], bundleName)) {
HILOG_ERROR("Parse bundleName failed"); HILOG_ERROR("Parse bundleName failed");
return engine.CreateUndefined(); return engine.CreateUndefined();
} }

View File

@ -27,5 +27,10 @@ void ExtensionContext::SetToken(const sptr<IRemoteObject> &token)
} }
token_ = token; token_ = token;
} }
sptr<IRemoteObject> ExtensionContext::GetToken() const
{
return token_;
}
} // namespace AbilityRuntime } // namespace AbilityRuntime
} // namespace OHOS } // namespace OHOS

View File

@ -37,6 +37,13 @@ public:
*/ */
void SetToken(const sptr<IRemoteObject> &token); void SetToken(const sptr<IRemoteObject> &token);
/**
* @brief Get the token witch the app launched.
*
* @return token The token which the is launched by app.
*/
sptr<IRemoteObject> GetToken() const;
protected: protected:
sptr<IRemoteObject> token_; sptr<IRemoteObject> token_;
private: private:

View File

@ -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<AppExecFwk::AbilityInfo> info = GetAbilityInfo();
if (info == nullptr) {
HILOG_ERROR("ServiceContext::GetAbilityInfoType info == nullptr");
return AppExecFwk::AbilityType::UNKNOWN;
}
return info->type;
}
std::shared_ptr<AppExecFwk::AbilityInfo> FormExtensionContext::GetAbilityInfo() const
{
return abilityInfo_;
}
void FormExtensionContext::SetAbilityInfo(const std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> &abilityInfo)
{
if (abilityInfo == nullptr) {
HILOG_ERROR("FormExtensionContext::SetAbilityInfo Info == nullptr");
return;
}
abilityInfo_ = abilityInfo;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -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<OHOS::AppExecFwk::AbilityInfo> GetAbilityInfo() const;
/**
* @brief Set AbilityInfo when init.
*
*/
void SetAbilityInfo(const std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> &abilityInfo);
private:
/**
* @brief Get Current Ability Type
*
* @return Current Ability Type
*/
OHOS::AppExecFwk::AbilityType GetAbilityInfoType() const;
std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> abilityInfo_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_EXTENSION_CONTEXT_H

View File

@ -15,6 +15,7 @@
#include "service_extension_context.h" #include "service_extension_context.h"
#include "ability_connection.h"
#include "ability_manager_client.h" #include "ability_manager_client.h"
#include "hilog_wrapper.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<AAFwk::IAbilityConnection> &conn) void ServiceExtensionContext::StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const
{ {
HILOG_INFO("%{public}s begin.", __func__); HILOG_DEBUG("%{public}s begin.", __func__);
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_,
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, conn, token_); ILLEGAL_REQUEST_CODE);
HILOG_INFO("%{public}s end ConnectAbility, ret=%{public}d", __func__, ret); HILOG_DEBUG("%{public}s. End calling ams->StartAbility. ret=%{public}d", __func__, err);
bool value = ((ret == ERR_OK) ? true : false); if (err != ERR_OK) {
if (!value) { HILOG_ERROR("ServiceContext::StartAbility is failed %{public}d", err);
HILOG_ERROR("ServiceContext::ConnectAbility ErrorCode = %{public}d", ret);
} }
HILOG_INFO("%{public}s end.", __func__);
return value;
} }
void ServiceExtensionContext::DisconnectAbility(const sptr<AAFwk::IAbilityConnection> &conn) bool ServiceExtensionContext::ConnectAbility(
const AAFwk::Want &want, const std::shared_ptr<AbilityConnectCallback> &connectCallback) const
{ {
HILOG_INFO("%{public}s begin.", __func__); HILOG_INFO("%{public}s begin.", __func__);
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn); ErrCode ret =
HILOG_INFO("%{public}s end ams->DisconnectAbility, ret=%{public}d", __func__, 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<AbilityConnectCallback> &connectCallback) const
{
HILOG_INFO("%{public}s begin.", __func__);
ErrCode ret =
ConnectionManager::GetInstance().DisconnectAbility(token_, want.GetElement(), connectCallback);
if (ret != ERR_OK) { 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() void ServiceExtensionContext::TerminateAbility()

View File

@ -18,8 +18,10 @@
#include "extension_context.h" #include "extension_context.h"
#include "ability_connect_callback_interface.h" #include "ability_connect_callback.h"
#include "ability_info.h" #include "ability_info.h"
#include "connection_manager.h"
#include "start_options.h"
#include "want.h" #include "want.h"
namespace OHOS { namespace OHOS {
@ -44,6 +46,8 @@ public:
*/ */
void StartAbility(const AAFwk::Want &want) const; 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. * @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 * @return True means success and false means failure
*/ */
bool ConnectAbility(const AAFwk::Want &want, const sptr<AAFwk::IAbilityConnection> &conn); bool ConnectAbility(
const AAFwk::Want &want, const std::shared_ptr<AbilityConnectCallback> &connectCallback) const;
/** /**
* @brief Disconnects the current ability from an ability * @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 * @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. * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities.
*/ */
void DisconnectAbility(const sptr<AAFwk::IAbilityConnection> &conn); void DisconnectAbility(
const AAFwk::Want &want, const std::shared_ptr<AbilityConnectCallback> &connectCallback) const;
/** /**
* @brief Destroys the current ability. * @brief Destroys the current ability.

View File

@ -718,6 +718,13 @@ public:
*/ */
void SetRunner(const std::shared_ptr<EventRunner> &runner); void SetRunner(const std::shared_ptr<EventRunner> &runner);
/**
* @brief Obtains the lifecycle state info.
*
* @return Returns the lifecycle state info.
*/
AAFwk::LifeCycleStateInfo GetLifeCycleStateInfo() const;
public: public:
static const std::string CONTEXT_DEAL_FILE_SEPARATOR; static const std::string CONTEXT_DEAL_FILE_SEPARATOR;
static const std::string CONTEXT_DEAL_CODE_CACHE; static const std::string CONTEXT_DEAL_CODE_CACHE;

View File

@ -20,10 +20,10 @@
#include <list> #include <list>
#include <memory> #include <memory>
#include "application_context.h"
#include "ability_lifecycle_callbacks.h" #include "ability_lifecycle_callbacks.h"
#include "ability_runtime/context/context.h" #include "ability_runtime/context/context.h"
#include "ability_stage.h" #include "ability_stage.h"
#include "application_context.h"
#include "element_callback.h" #include "element_callback.h"
namespace OHOS { namespace OHOS {

View File

@ -740,7 +740,7 @@ void ContextDeal::initResourceManager(const std::shared_ptr<Global::Resource::Re
resourceManager_ = resourceManager; resourceManager_ = resourceManager;
APP_LOGI("ContextDeal::initResourceManager. End."); APP_LOGI("ContextDeal::initResourceManager. End.");
} }
/** /**
* @brief Obtains information about the caller of this ability. * @brief Obtains information about the caller of this ability.
* *
@ -1110,6 +1110,16 @@ int ContextDeal::GetMissionId()
return lifeCycleStateInfo_.missionId; return lifeCycleStateInfo_.missionId;
} }
/**
* @brief Obtains the lifecycle state info.
*
* @return Returns the lifecycle state info.
*/
AAFwk::LifeCycleStateInfo ContextDeal::GetLifeCycleStateInfo() const
{
return lifeCycleStateInfo_;
}
/** /**
* @brief Call this when your ability should be closed and the mission should be completely removed as a part of * @brief Call this when your ability should be closed and the mission should be completely removed as a part of
* finishing the root ability of the mission. * finishing the root ability of the mission.

View File

@ -25,6 +25,7 @@
#include "bytrace.h" #include "bytrace.h"
#include "context_deal.h" #include "context_deal.h"
#include "context_impl.h" #include "context_impl.h"
#include "form_extension.h"
#include "if_system_ability_manager.h" #include "if_system_ability_manager.h"
#include "iservice_registry.h" #include "iservice_registry.h"
#include "js_runtime.h" #include "js_runtime.h"
@ -391,8 +392,8 @@ void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr<IRemo
} else { } else {
BundleInfo bundleInfo; BundleInfo bundleInfo;
bundleMgr->GetBundleInfo(abilityInfo->bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); bundleMgr->GetBundleInfo(abilityInfo->bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo);
abilityRecord->SetTargetVersion(bundleInfo.targetVersion); abilityRecord->SetCompatibleVersion(bundleInfo.compatibleVersion);
APP_LOGI("MainThread::ScheduleLaunchAbility targetVersion:%{public}d", bundleInfo.targetVersion); APP_LOGI("MainThread::ScheduleLaunchAbility compatibleVersion:%{public}d", bundleInfo.compatibleVersion);
} }
auto task = [appThread = this, abilityRecord]() { appThread->HandleLaunchAbility(abilityRecord); }; auto task = [appThread = this, abilityRecord]() { appThread->HandleLaunchAbility(abilityRecord); };
@ -741,21 +742,13 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData)
// Create runtime // Create runtime
AbilityRuntime::Runtime::Options options; AbilityRuntime::Runtime::Options options;
options.codePath = appInfo.codePath; options.codePath = appInfo.codePath;
options.eventRunner = mainHandler_->GetEventRunner();
auto runtime = AbilityRuntime::Runtime::Create(options); auto runtime = AbilityRuntime::Runtime::Create(options);
if (!runtime) { if (!runtime) {
APP_LOGE("OHOSApplication::OHOSApplication: Failed to create runtime"); APP_LOGE("OHOSApplication::OHOSApplication: Failed to create runtime");
return; return;
} }
if (runtime->GetLanguage() == AbilityRuntime::Runtime::Language::JS) {
std::unique_ptr<std::function<void()>> idleTask = std::make_unique<std::function<void()>>();
*idleTask = [&jsRuntime = static_cast<AbilityRuntime::JsRuntime&>(*runtime), &idleTask = *idleTask]() {
jsRuntime.GetNativeEngine().Loop(LOOP_NOWAIT);
EventHandler::Current()->PostIdleTask(idleTask);
};
mainHandler_->PostIdleTask(*idleTask.release());
}
application_->SetRuntime(std::move(runtime)); application_->SetRuntime(std::move(runtime));
AbilityLoader::GetInstance().RegisterAbility("Ability", [application = application_]() { AbilityLoader::GetInstance().RegisterAbility("Ability", [application = application_]() {
return Ability::Create(application->GetRuntime()); return Ability::Create(application->GetRuntime());
@ -763,6 +756,9 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData)
AbilityLoader::GetInstance().RegisterExtension("ServiceExtension", [application = application_]() { AbilityLoader::GetInstance().RegisterExtension("ServiceExtension", [application = application_]() {
return AbilityRuntime::ServiceExtension::Create(application->GetRuntime()); return AbilityRuntime::ServiceExtension::Create(application->GetRuntime());
}); });
AbilityLoader::GetInstance().RegisterExtension("FormExtension", [application = application_]() {
return AbilityRuntime::FormExtension::Create(application->GetRuntime());
});
} }
contextDeal->initResourceManager(resourceManager); contextDeal->initResourceManager(resourceManager);

View File

@ -89,11 +89,13 @@ public:
{ {
return true; 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; return true;
}; };
virtual bool GetBundleInfos(const BundleFlag flag, std::vector<BundleInfo> &bundleInfos) virtual bool GetBundleInfos(
const BundleFlag flag, std::vector<BundleInfo> &bundleInfos, int32_t userId)
{ {
return true; return true;
}; };
@ -215,7 +217,8 @@ public:
{ {
return true; 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; return true;
}; };
@ -296,6 +299,10 @@ public:
{ {
return true; return true;
} }
virtual sptr<IBundleUserMgr> GetBundleUserMgr() override
{
return nullptr;
}
}; };
class MockAbilityContextDeal : public ContextDeal { class MockAbilityContextDeal : public ContextDeal {

View File

@ -36,7 +36,7 @@ public:
MOCK_METHOD2(ReleaseDataAbility, int(sptr<IAbilityScheduler>, const sptr<IRemoteObject> &)); MOCK_METHOD2(ReleaseDataAbility, int(sptr<IAbilityScheduler>, const sptr<IRemoteObject> &));
MOCK_METHOD2(AddWindowInfo, void(const sptr<IRemoteObject> &token, int32_t windowToken)); MOCK_METHOD2(AddWindowInfo, void(const sptr<IRemoteObject> &token, int32_t windowToken));
MOCK_METHOD2(AttachAbilityThread, int(const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)); MOCK_METHOD2(AttachAbilityThread, int(const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token));
MOCK_METHOD3(AbilityTransitionDone, int(const sptr<IRemoteObject> &token, int state, const PacMap &)); MOCK_METHOD3(AbilityTransitionDone, int(const sptr<IRemoteObject> &token, int state, const PacMap &saveData));
MOCK_METHOD2( MOCK_METHOD2(
ScheduleConnectAbilityDone, int(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)); ScheduleConnectAbilityDone, int(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject));
MOCK_METHOD1(ScheduleDisconnectAbilityDone, int(const sptr<IRemoteObject> &token)); MOCK_METHOD1(ScheduleDisconnectAbilityDone, int(const sptr<IRemoteObject> &token));
@ -63,6 +63,17 @@ public:
MOCK_METHOD2(UninstallApp, int(const std::string &bundleName, const int userId)); MOCK_METHOD2(UninstallApp, int(const std::string &bundleName, const int userId));
MOCK_METHOD1(TerminateAbilityByRecordId, int(const int64_t recordId)); 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<IMissionListener> &listener));
MOCK_METHOD1(UnRegisterMissionListener, int(const sptr<IMissionListener> &listener));
MOCK_METHOD3(
GetMissionInfos, int(const std::string& deviceId, int32_t numMax, std::vector<MissionInfo> &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() void Wait()
{ {
sem_.Wait(); sem_.Wait();

View File

@ -1 +0,0 @@
hmf/appexecfwk/standard

View File

@ -145,6 +145,18 @@ public:
*/ */
int32_t GetConnectionState() const; 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); void SetEventId(const int64_t eventId);
int64_t GetEventId() const; int64_t GetEventId() const;
@ -154,6 +166,7 @@ private:
int32_t perceptibility_ = 0; int32_t perceptibility_ = 0;
int32_t connectionState_ = 0; int32_t connectionState_ = 0;
int64_t eventId_ = 0; int64_t eventId_ = 0;
bool isTerminating_ = false;
AbilityState state_ = AbilityState::ABILITY_STATE_BEGIN; AbilityState state_ = AbilityState::ABILITY_STATE_BEGIN;
std::shared_ptr<AbilityInfo> info_; std::shared_ptr<AbilityInfo> info_;
sptr<IRemoteObject> token_; sptr<IRemoteObject> token_;

View File

@ -69,6 +69,15 @@ public:
*/ */
virtual void UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state) override; virtual void UpdateAbilityState(const sptr<IRemoteObject> &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<IRemoteObject> &token, const ExtensionState state) override;
/** /**
* RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback. * RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback.
* *

View File

@ -131,7 +131,7 @@ public:
sptr<IAppScheduler> GetApplicationClient() const; sptr<IAppScheduler> GetApplicationClient() const;
private: private:
sptr<IAppScheduler> appThread_; sptr<IAppScheduler> appThread_ = nullptr;
}; };
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -237,6 +237,27 @@ private:
*/ */
void SetInnerService(const std::shared_ptr<AppMgrServiceInner> &innerService); void SetInnerService(const std::shared_ptr<AppMgrServiceInner> &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<IApplicationStateObserver> &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<IApplicationStateObserver> &observer) override;
/**
* Get foreground applications.
* @param list, foreground apps.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int32_t GetForegroundApplications(std::vector<AppStateData> &list) override;
private: private:
std::shared_ptr<AppMgrServiceInner> appMgrServiceInner_; std::shared_ptr<AppMgrServiceInner> appMgrServiceInner_;
AppMgrServiceState appMgrServiceState_; AppMgrServiceState appMgrServiceState_;

View File

@ -33,6 +33,7 @@
#include "app_spawn_client.h" #include "app_spawn_client.h"
#include "app_task_info.h" #include "app_task_info.h"
#include "iapp_state_callback.h" #include "iapp_state_callback.h"
#include "iapplication_state_observer.h"
#include "app_process_manager.h" #include "app_process_manager.h"
#include "remote_client_manager.h" #include "remote_client_manager.h"
#include "app_running_manager.h" #include "app_running_manager.h"
@ -85,6 +86,24 @@ public:
*/ */
virtual void UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state); virtual void UpdateAbilityState(const sptr<IRemoteObject> &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<IRemoteObject> &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. * RegisterAppStateCallback, register the callback.
* *
@ -486,6 +505,27 @@ public:
bool CheckRemoteClient(); 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<IApplicationStateObserver> &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<IApplicationStateObserver> &observer);
/**
* Get Foreground Applications.
*
* @return Foreground Applications.
*/
int32_t GetForegroundApplications(std::vector<AppStateData> &list);
private: private:
void StartEmptyResidentProcess(const std::string &appName, const std::string &processName, 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); int32_t KillApplicationByUserId(const std::string &bundleName, const int userId);
AppProcessData WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &appRecord,
const ApplicationState state);
AppStateData WrapAppStateData(const std::shared_ptr<AppRunningRecord> &appRecord,
const ApplicationState state);
ProcessData WrapProcessData(const std::shared_ptr<AppRunningRecord> &appRecord);
void AddObserverDeathRecipient(const sptr<IApplicationStateObserver> &observer);
void RemoveObserverDeathRecipient(const sptr<IApplicationStateObserver> &observer);
void OnObserverDied(const wptr<IRemoteObject> &remote);
void HandleObserverDiedTask(const sptr<IRemoteObject> &observer);
bool ObserverExist(const sptr<IApplicationStateObserver> &observer);
void OnProcessCreated(const std::shared_ptr<AppRunningRecord> &appRecord);
void OnProcessDied(const std::shared_ptr<AppRunningRecord> &appRecord);
private: private:
/** /**
* ClearUpApplicationData, clear the application data. * ClearUpApplicationData, clear the application data.
@ -696,6 +758,10 @@ private:
*/ */
void NotifyAppStatus(const std::string &bundleName, const std::string &eventData); void NotifyAppStatus(const std::string &bundleName, const std::string &eventData);
const std::string TASK_ON_CALLBACK_DIED = "OnCallbackDiedTask";
std::vector<sptr<IApplicationStateObserver>> appStateObservers_;
std::map<sptr<IRemoteObject>, sptr<IRemoteObject::DeathRecipient>> recipientMap_;
std::recursive_mutex observerLock_;
std::vector<const sptr<IAppStateCallback>> appStateCallbacks_; std::vector<const sptr<IAppStateCallback>> appStateCallbacks_;
std::shared_ptr<AppProcessManager> appProcessManager_; std::shared_ptr<AppProcessManager> appProcessManager_;
std::shared_ptr<RemoteClientManager> remoteClientManager_; std::shared_ptr<RemoteClientManager> remoteClientManager_;

View File

@ -25,6 +25,7 @@
#include "app_running_record.h" #include "app_running_record.h"
#include "ability_info.h" #include "ability_info.h"
#include "application_info.h" #include "application_info.h"
#include "app_state_data.h"
#include "record_query_result.h" #include "record_query_result.h"
namespace OHOS { namespace OHOS {
@ -120,6 +121,13 @@ public:
*/ */
void ClearAppRunningRecordMap(); void ClearAppRunningRecordMap();
/**
* Get Foreground Applications.
*
* @return Foreground Applications.
*/
void GetForegroundApplications(std::vector<AppStateData> &list);
void HandleTerminateTimeOut(int64_t eventId); void HandleTerminateTimeOut(int64_t eventId);
void HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token); void HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token);
std::shared_ptr<AppRunningRecord> GetAppRunningRecord(const int64_t eventId); std::shared_ptr<AppRunningRecord> GetAppRunningRecord(const int64_t eventId);

View File

@ -24,6 +24,7 @@
#include "iremote_object.h" #include "iremote_object.h"
#include "ability_running_record.h" #include "ability_running_record.h"
#include "ability_state_data.h"
#include "application_info.h" #include "application_info.h"
#include "app_death_recipient.h" #include "app_death_recipient.h"
#include "app_launch_data.h" #include "app_launch_data.h"
@ -382,6 +383,14 @@ public:
void insertAbilityStageInfo(std::vector<HapModuleInfo> moduleInfos); void insertAbilityStageInfo(std::vector<HapModuleInfo> moduleInfos);
/**
* Notify observers when state change.
*
* @param ability, ability or extension record.
* @param state, ability or extension state.
*/
void StateChangedNotifyObserver(const std::shared_ptr<AbilityRunningRecord> &ability, int32_t state, bool isAbility);
private: private:
// drive application state changes when ability state changes. // 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 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 ApplicationState curState_ = ApplicationState::APP_STATE_CREATE; // current state of this process
std::shared_ptr<ApplicationInfo> appInfo_; // the application's info of this process std::shared_ptr<ApplicationInfo> appInfo_ = nullptr; // the application's info of this process
int32_t appRecordId_ = 0; int32_t appRecordId_ = 0;
std::string appName_;
std::string processName_; // the name of this process std::string processName_; // the name of this process
int32_t uid_ = 0; int32_t uid_ = 0;
static int64_t appEventId_; static int64_t appEventId_;
@ -441,10 +451,10 @@ private:
std::map<int32_t, std::vector<HapModuleInfo>> abilityStage_; std::map<int32_t, std::vector<HapModuleInfo>> abilityStage_;
std::list<const sptr<IRemoteObject>> foregroundingAbilityTokens_; std::list<const sptr<IRemoteObject>> foregroundingAbilityTokens_;
std::weak_ptr<AppMgrServiceInner> appMgrServiceInner_; std::weak_ptr<AppMgrServiceInner> appMgrServiceInner_;
sptr<AppDeathRecipient> appDeathRecipient_; sptr<AppDeathRecipient> appDeathRecipient_ = nullptr;
std::shared_ptr<PriorityObject> priorityObject_; std::shared_ptr<PriorityObject> priorityObject_ = nullptr;
std::shared_ptr<AppLifeCycleDeal> appLifeCycleDeal_; std::shared_ptr<AppLifeCycleDeal> appLifeCycleDeal_ = nullptr;
std::shared_ptr<AMSEventHandler> eventHandler_; std::shared_ptr<AMSEventHandler> eventHandler_ = nullptr;
bool isTerminating = false; bool isTerminating = false;
}; };
} // namespace AppExecFwk } // namespace AppExecFwk

View File

@ -110,5 +110,15 @@ int64_t AbilityRunningRecord::GetEventId() const
{ {
return eventId_; return eventId_;
} }
void AbilityRunningRecord::SetTerminating()
{
isTerminating_ = true;
}
bool AbilityRunningRecord::IsTerminating() const
{
return isTerminating_;
}
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -31,6 +31,7 @@ namespace {
const std::string TASK_LOAD_ABILITY = "LoadAbilityTask"; const std::string TASK_LOAD_ABILITY = "LoadAbilityTask";
const std::string TASK_TERMINATE_ABILITY = "TerminateAbilityTask"; const std::string TASK_TERMINATE_ABILITY = "TerminateAbilityTask";
const std::string TASK_UPDATE_ABILITY_STATE = "UpdateAbilityStateTask"; 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_REGISTER_APP_STATE_CALLBACK = "RegisterAppStateCallbackTask";
const std::string TASK_STOP_ALL_PROCESS = "StopAllProcessTask"; const std::string TASK_STOP_ALL_PROCESS = "StopAllProcessTask";
const std::string TASK_ABILITY_BEHAVIOR_ANALYSIS = "AbilityBehaviorAnalysisTask"; const std::string TASK_ABILITY_BEHAVIOR_ANALYSIS = "AbilityBehaviorAnalysisTask";
@ -76,6 +77,16 @@ void AmsMgrScheduler::UpdateAbilityState(const sptr<IRemoteObject> &token, const
amsHandler_->PostTask(updateAbilityStateFunc, TASK_UPDATE_ABILITY_STATE); amsHandler_->PostTask(updateAbilityStateFunc, TASK_UPDATE_ABILITY_STATE);
} }
void AmsMgrScheduler::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
{
if (!IsReady()) {
return;
}
std::function<void()> updateExtensionStateFunc =
std::bind(&AppMgrServiceInner::UpdateExtensionState, amsMgrServiceInner_, token, state);
amsHandler_->PostTask(updateExtensionStateFunc, TASK_UPDATE_EXTENSION_STATE);
}
void AmsMgrScheduler::TerminateAbility(const sptr<IRemoteObject> &token) void AmsMgrScheduler::TerminateAbility(const sptr<IRemoteObject> &token)
{ {
if (!IsReady()) { if (!IsReady()) {

View File

@ -27,7 +27,9 @@ AppLifeCycleDeal::~AppLifeCycleDeal()
void AppLifeCycleDeal::LaunchApplication(const AppLaunchData &launchData_) void AppLifeCycleDeal::LaunchApplication(const AppLaunchData &launchData_)
{ {
APP_LOGI("AppLifeCycleDeal ScheduleLaunchApplication"); APP_LOGI("AppLifeCycleDeal ScheduleLaunchApplication");
appThread_->ScheduleLaunchApplication(launchData_); if (appThread_) {
appThread_->ScheduleLaunchApplication(launchData_);
}
} }
void AppLifeCycleDeal::AddAbilityStageInfo(const AppResidentProcessInfo &residentProcessInfo) void AppLifeCycleDeal::AddAbilityStageInfo(const AppResidentProcessInfo &residentProcessInfo)
@ -39,7 +41,9 @@ void AppLifeCycleDeal::AddAbilityStageInfo(const AppResidentProcessInfo &residen
void AppLifeCycleDeal::LaunchAbility(const std::shared_ptr<AbilityRunningRecord> &ability) void AppLifeCycleDeal::LaunchAbility(const std::shared_ptr<AbilityRunningRecord> &ability)
{ {
appThread_->ScheduleLaunchAbility(*(ability->GetAbilityInfo()), ability->GetToken()); if (appThread_) {
appThread_->ScheduleLaunchAbility(*(ability->GetAbilityInfo()), ability->GetToken());
}
} }
void AppLifeCycleDeal::ScheduleTerminate() void AppLifeCycleDeal::ScheduleTerminate()

View File

@ -337,5 +337,35 @@ void AppMgrService::AddAbilityStageDone(const int32_t recordId)
std::bind(&AppMgrServiceInner::AddAbilityStageDone, appMgrServiceInner_, recordId); std::bind(&AppMgrServiceInner::AddAbilityStageDone, appMgrServiceInner_, recordId);
handler_->PostTask(addAbilityStageDone, TASK_ADD_ABILITY_STAGE_DONE); handler_->PostTask(addAbilityStageDone, TASK_ADD_ABILITY_STAGE_DONE);
} }
int32_t AppMgrService::RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> &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<IApplicationStateObserver> &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<AppStateData> &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 AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -20,6 +20,7 @@
#include <sys/stat.h> #include <sys/stat.h>
#include "app_log_wrapper.h" #include "app_log_wrapper.h"
#include "application_state_observer_stub.h"
#include "datetime_ex.h" #include "datetime_ex.h"
#include "perf_profile.h" #include "perf_profile.h"
@ -244,6 +245,7 @@ void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId)
OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED);
appRunningManager_->RemoveAppRunningRecordById(recordId); appRunningManager_->RemoveAppRunningRecordById(recordId);
RemoveAppFromRecentListById(recordId); RemoveAppFromRecentListById(recordId);
OnProcessDied(appRecord);
APP_LOGI("application is terminated"); APP_LOGI("application is terminated");
} }
@ -603,6 +605,25 @@ void AppMgrServiceInner::UpdateAbilityState(const sptr<IRemoteObject> &token, co
APP_LOGD("end"); APP_LOGD("end");
} }
void AppMgrServiceInner::UpdateExtensionState(const sptr<IRemoteObject> &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<int32_t>(state), false);
}
void AppMgrServiceInner::OnStop() void AppMgrServiceInner::OnStop()
{ {
appRunningManager_->ClearAppRunningRecordMap(); appRunningManager_->ClearAppRunningRecordMap();
@ -900,18 +921,55 @@ void AppMgrServiceInner::OnAppStateChanged(
for (const auto &callback : appStateCallbacks_) { for (const auto &callback : appStateCallbacks_) {
if (callback != nullptr) { if (callback != nullptr) {
AppProcessData processData; callback->OnAppStateChanged(WrapAppProcessData(appRecord, state));
processData.appName = appRecord->GetName(); }
processData.processName = appRecord->GetProcessName(); }
processData.pid = appRecord->GetPriorityObject()->GetPid();
processData.appState = state; if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_BACKGROUND) {
processData.uid = appRecord->GetUid(); AppStateData data = WrapAppStateData(appRecord, state);
callback->OnAppStateChanged(processData); 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<std::recursive_mutex> lockNotify(observerLock_);
for (const auto &observer : appStateObservers_) {
if (observer != nullptr) {
observer->OnForegroundApplicationChanged(data);
}
} }
} }
APP_LOGD("end"); APP_LOGD("end");
} }
AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &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<AppRunningRecord> &appRecord,
const ApplicationState state)
{
AppStateData appStateData;
appStateData.bundleName = appRecord->GetBundleName();
appStateData.state = static_cast<int32_t>(state);
appStateData.uid = appRecord->GetUid();
return appStateData;
}
ProcessData AppMgrServiceInner::WrapProcessData(const std::shared_ptr<AppRunningRecord> &appRecord)
{
ProcessData processData;
processData.bundleName = appRecord->GetBundleName();
processData.pid = appRecord->GetPriorityObject()->GetPid();
processData.uid = appRecord->GetUid();
return processData;
}
void AppMgrServiceInner::OnAbilityStateChanged( void AppMgrServiceInner::OnAbilityStateChanged(
const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state) const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state)
{ {
@ -928,6 +986,61 @@ void AppMgrServiceInner::OnAbilityStateChanged(
APP_LOGD("end"); APP_LOGD("end");
} }
void AppMgrServiceInner::StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility)
{
std::lock_guard<std::recursive_mutex> 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<AppRunningRecord> &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<std::recursive_mutex> lockNotify(observerLock_);
for (const auto &observer : appStateObservers_) {
if (observer != nullptr) {
observer->OnProcessCreated(data);
}
}
APP_LOGD("end");
}
void AppMgrServiceInner::OnProcessDied(const std::shared_ptr<AppRunningRecord> &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<std::recursive_mutex> 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, void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName,
const std::shared_ptr<AppRunningRecord> &appRecord, const int uid) const std::shared_ptr<AppRunningRecord> &appRecord, const int uid)
{ {
@ -987,6 +1100,7 @@ void AppMgrServiceInner::StartProcess(const std::string &appName, const std::str
appRecord->SetAppMgrServiceInner(weak_from_this()); appRecord->SetAppMgrServiceInner(weak_from_this());
OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE); OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE);
AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId()); AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId());
OnProcessCreated(appRecord);
PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount()); PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount());
} }
@ -1050,9 +1164,12 @@ void AppMgrServiceInner::OnRemoteDied(const wptr<IRemoteObject> &remote)
for (const auto &item : appRecord->GetAbilities()) { for (const auto &item : appRecord->GetAbilities()) {
const auto &abilityRecord = item.second; const auto &abilityRecord = item.second;
OptimizerAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_TERMINATED); OptimizerAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_TERMINATED);
appRecord->StateChangedNotifyObserver(abilityRecord,
static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true);
} }
OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED);
RemoveAppFromRecentListById(appRecord->GetRecordId()); RemoveAppFromRecentListById(appRecord->GetRecordId());
OnProcessDied(appRecord);
} }
if (appRecord && appRecord->IsKeepAliveApp()) { if (appRecord && appRecord->IsKeepAliveApp()) {
@ -1293,6 +1410,7 @@ void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId
} }
appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
RemoveAppFromRecentListById(appRecord->GetRecordId()); RemoveAppFromRecentListById(appRecord->GetRecordId());
OnProcessDied(appRecord);
} }
void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId) 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::CommonEventData commonData {want};
EventFwk::CommonEventManager::PublishCommonEvent(commonData); EventFwk::CommonEventManager::PublishCommonEvent(commonData);
} }
int32_t AppMgrServiceInner::RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
{
APP_LOGI("%{public}s begin", __func__);
std::lock_guard<std::recursive_mutex> 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<IApplicationStateObserver> &observer)
{
APP_LOGI("%{public}s begin", __func__);
std::lock_guard<std::recursive_mutex> lockUnregister(observerLock_);
if (observer == nullptr) {
APP_LOGE("Observer nullptr");
return ERR_INVALID_VALUE;
}
std::vector<sptr<IApplicationStateObserver>>::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<IApplicationStateObserver> &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<IApplicationStateObserver> &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<IRemoteObject::DeathRecipient> 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<IApplicationStateObserver> &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<IRemoteObject> &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<IRemoteObject> &observer)
{
APP_LOGI("Handle call back died task.");
if (observer == nullptr) {
APP_LOGE("observer nullptr.");
return;
}
sptr<IApplicationStateObserver> object = iface_cast<IApplicationStateObserver>(observer);
UnregisterApplicationStateObserver(object);
}
int32_t AppMgrServiceInner::GetForegroundApplications(std::vector<AppStateData> &list)
{
APP_LOGI("%{public}s, begin.", __func__);
appRunningManager_->GetForegroundApplications(list);
return ERR_OK;
}
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -306,6 +306,11 @@ void AppRunningManager::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &to
return; return;
} }
std::shared_ptr<AbilityRunningRecord> abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
if (abilityRecord) {
abilityRecord->SetTerminating();
}
if (appRecord->IsLastAbilityRecord(token)) { if (appRecord->IsLastAbilityRecord(token)) {
appRecord->SetTerminating(); appRecord->SetTerminating();
} }
@ -397,5 +402,22 @@ std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecordByBundle
} }
return nullptr; return nullptr;
} }
void AppRunningManager::GetForegroundApplications(std::vector<AppStateData> &list)
{
APP_LOGI("%{public}s, begin.", __func__);
std::lock_guard<std::recursive_mutex> 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<int32_t>(ApplicationState::APP_STATE_FOREGROUND);
list.push_back(appData);
APP_LOGI("%{public}s, bundleName:%{public}s", __func__, appData.bundleName.c_str());
}
}
}
} // namespace AppExecFwk } // namespace AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -26,7 +26,11 @@ int64_t AppRunningRecord::appEventId_ = 0;
AppRunningRecord::AppRunningRecord( AppRunningRecord::AppRunningRecord(
const std::shared_ptr<ApplicationInfo> &info, const int32_t recordId, const std::string &processName) const std::shared_ptr<ApplicationInfo> &info, const int32_t recordId, const std::string &processName)
: appInfo_(info), appRecordId_(recordId), processName_(processName) : appInfo_(info), appRecordId_(recordId), processName_(processName)
{} {
if (appInfo_) {
appName_ = appInfo_->name;
}
}
void AppRunningRecord::SetApplicationClient(const sptr<IAppScheduler> &thread) void AppRunningRecord::SetApplicationClient(const sptr<IAppScheduler> &thread)
{ {
@ -38,12 +42,12 @@ void AppRunningRecord::SetApplicationClient(const sptr<IAppScheduler> &thread)
std::string AppRunningRecord::GetBundleName() const std::string AppRunningRecord::GetBundleName() const
{ {
return appInfo_->bundleName; return appInfo_ ? appInfo_->bundleName : "";
} }
bool AppRunningRecord::IsLauncherApp() const bool AppRunningRecord::IsLauncherApp() const
{ {
return appInfo_->isLauncherApp; return appInfo_ ? appInfo_->isLauncherApp : false;
} }
int32_t AppRunningRecord::GetRecordId() const int32_t AppRunningRecord::GetRecordId() const
@ -53,7 +57,7 @@ int32_t AppRunningRecord::GetRecordId() const
const std::string &AppRunningRecord::GetName() const const std::string &AppRunningRecord::GetName() const
{ {
return appInfo_->name; return appName_;
} }
bool AppRunningRecord::GetCloneInfo() const bool AppRunningRecord::GetCloneInfo() const
@ -119,7 +123,7 @@ std::shared_ptr<AbilityRunningRecord> AppRunningRecord::AddAbility(
std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecord(const std::string &abilityName) const std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecord(const std::string &abilityName) const
{ {
const auto &iter = std::find_if(abilities_.begin(), abilities_.end(), [&abilityName](const auto &pair) { 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); return ((iter == abilities_.end()) ? nullptr : iter->second);
} }
@ -164,6 +168,10 @@ void AppRunningRecord::ScheduleAppCrash([[maybe_unused]] const std::string &desc
void AppRunningRecord::LaunchApplication() void AppRunningRecord::LaunchApplication()
{ {
if (appLifeCycleDeal_ == nullptr) {
APP_LOGE("appLifeCycleDeal_ is null");
return;
}
if (!appInfo_ || !appLifeCycleDeal_->GetApplicationClient()) { if (!appInfo_ || !appLifeCycleDeal_->GetApplicationClient()) {
APP_LOGE("appInfo or appThread is null"); APP_LOGE("appInfo or appThread is null");
return; return;
@ -197,6 +205,10 @@ void AppRunningRecord::AddAbilityStageDone()
void AppRunningRecord::LaunchAbility(const std::shared_ptr<AbilityRunningRecord> &ability) void AppRunningRecord::LaunchAbility(const std::shared_ptr<AbilityRunningRecord> &ability)
{ {
if (appLifeCycleDeal_ == nullptr) {
APP_LOGE("appLifeCycleDeal_ is null");
return;
}
if (!ability || !ability->GetToken()) { if (!ability || !ability->GetToken()) {
APP_LOGE("null abilityRecord or abilityToken"); APP_LOGE("null abilityRecord or abilityToken");
return; return;
@ -222,32 +234,44 @@ void AppRunningRecord::LaunchPendingAbilities()
void AppRunningRecord::ScheduleTerminate() void AppRunningRecord::ScheduleTerminate()
{ {
SendEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT); SendEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT);
appLifeCycleDeal_->ScheduleTerminate(); if (appLifeCycleDeal_) {
appLifeCycleDeal_->ScheduleTerminate();
}
} }
void AppRunningRecord::ScheduleForegroundRunning() void AppRunningRecord::ScheduleForegroundRunning()
{ {
appLifeCycleDeal_->ScheduleForegroundRunning(); if (appLifeCycleDeal_) {
appLifeCycleDeal_->ScheduleForegroundRunning();
}
} }
void AppRunningRecord::ScheduleBackgroundRunning() void AppRunningRecord::ScheduleBackgroundRunning()
{ {
appLifeCycleDeal_->ScheduleBackgroundRunning(); if (appLifeCycleDeal_) {
appLifeCycleDeal_->ScheduleBackgroundRunning();
}
} }
void AppRunningRecord::ScheduleProcessSecurityExit() void AppRunningRecord::ScheduleProcessSecurityExit()
{ {
appLifeCycleDeal_->ScheduleProcessSecurityExit(); if (appLifeCycleDeal_) {
appLifeCycleDeal_->ScheduleProcessSecurityExit();
}
} }
void AppRunningRecord::ScheduleTrimMemory() void AppRunningRecord::ScheduleTrimMemory()
{ {
appLifeCycleDeal_->ScheduleTrimMemory(priorityObject_->GetTimeLevel()); if (appLifeCycleDeal_ && priorityObject_) {
appLifeCycleDeal_->ScheduleTrimMemory(priorityObject_->GetTimeLevel());
}
} }
void AppRunningRecord::LowMemoryWarning() void AppRunningRecord::LowMemoryWarning()
{ {
appLifeCycleDeal_->LowMemoryWarning(); if (appLifeCycleDeal_) {
appLifeCycleDeal_->LowMemoryWarning();
}
} }
void AppRunningRecord::OnAbilityStateChanged( void AppRunningRecord::OnAbilityStateChanged(
@ -266,6 +290,32 @@ void AppRunningRecord::OnAbilityStateChanged(
} }
} }
void AppRunningRecord::StateChangedNotifyObserver(
const std::shared_ptr<AbilityRunningRecord> &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<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecordByToken( std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecordByToken(
const sptr<IRemoteObject> &token) const const sptr<IRemoteObject> &token) const
{ {
@ -340,6 +390,7 @@ void AppRunningRecord::AbilityForeground(const std::shared_ptr<AbilityRunningRec
} else if (curState_ == ApplicationState::APP_STATE_FOREGROUND) { } else if (curState_ == ApplicationState::APP_STATE_FOREGROUND) {
// Just change ability to foreground if current application state is foreground. // Just change ability to foreground if current application state is foreground.
OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND); OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND);
StateChangedNotifyObserver(ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_FOREGROUND), true);
auto serviceInner = appMgrServiceInner_.lock(); auto serviceInner = appMgrServiceInner_.lock();
if (serviceInner) { if (serviceInner) {
serviceInner->OnAppStateChanged(shared_from_this(), curState_); serviceInner->OnAppStateChanged(shared_from_this(), curState_);
@ -363,6 +414,7 @@ void AppRunningRecord::AbilityBackground(const std::shared_ptr<AbilityRunningRec
// First change ability to backgrounded. // First change ability to backgrounded.
OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_BACKGROUND); OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_BACKGROUND);
StateChangedNotifyObserver(ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_BACKGROUND), true);
if (curState_ == ApplicationState::APP_STATE_FOREGROUND) { if (curState_ == ApplicationState::APP_STATE_FOREGROUND) {
int32_t foregroundSize = 0; int32_t foregroundSize = 0;
for (const auto &item : abilities_) { for (const auto &item : abilities_) {
@ -398,6 +450,7 @@ void AppRunningRecord::PopForegroundingAbilityTokens()
const auto &token = foregroundingAbilityTokens_.front(); const auto &token = foregroundingAbilityTokens_.front();
auto ability = GetAbilityRunningRecordByToken(token); auto ability = GetAbilityRunningRecordByToken(token);
OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND); OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND);
StateChangedNotifyObserver(ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_FOREGROUND), true);
foregroundingAbilityTokens_.pop_front(); foregroundingAbilityTokens_.pop_front();
} }
} }
@ -427,7 +480,12 @@ void AppRunningRecord::TerminateAbility(const sptr<IRemoteObject> &token, const
} }
OptimizerAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_TERMINATED); OptimizerAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_TERMINATED);
appLifeCycleDeal_->ScheduleCleanAbility(token); StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true);
if (appLifeCycleDeal_) {
appLifeCycleDeal_->ScheduleCleanAbility(token);
} else {
APP_LOGE("appLifeCycleDeal_ is null");
}
APP_LOGD("AppRunningRecord::TerminateAbility end"); APP_LOGD("AppRunningRecord::TerminateAbility end");
} }
@ -463,6 +521,10 @@ void AppRunningRecord::AbilityTerminated(const sptr<IRemoteObject> &token)
void AppRunningRecord::RegisterAppDeathRecipient() const void AppRunningRecord::RegisterAppDeathRecipient() const
{ {
if (appLifeCycleDeal_ == nullptr) {
APP_LOGE("appLifeCycleDeal_ is null");
return;
}
if (!appLifeCycleDeal_->GetApplicationClient()) { if (!appLifeCycleDeal_->GetApplicationClient()) {
APP_LOGE("appThread is null"); APP_LOGE("appThread is null");
return; return;
@ -475,6 +537,10 @@ void AppRunningRecord::RegisterAppDeathRecipient() const
void AppRunningRecord::RemoveAppDeathRecipient() const void AppRunningRecord::RemoveAppDeathRecipient() const
{ {
if (appLifeCycleDeal_ == nullptr) {
APP_LOGE("appLifeCycleDeal_ is null");
return;
}
if (!appLifeCycleDeal_->GetApplicationClient()) { if (!appLifeCycleDeal_->GetApplicationClient()) {
APP_LOGE("appThread is null"); APP_LOGE("appThread is null");
return; return;

View File

@ -431,7 +431,10 @@ void ProcessOptimizer::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel leve
APP_LOGI("OnLowMemoryAlert level %{public}d", level); APP_LOGI("OnLowMemoryAlert level %{public}d", level);
// Find the oldest background app. // Find the oldest background app.
for (auto it(appLru_.rbegin()); it != appLru_.rend(); ++it) { 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); AppLowMemoryAlert(*it, level);
break; break;
} }
@ -440,7 +443,11 @@ void ProcessOptimizer::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel leve
// send pid which will be killed. // send pid which will be killed.
std::list<AppPtr>::iterator iter = appLru_.begin(); std::list<AppPtr>::iterator iter = appLru_.begin();
while (iter != appLru_.end()) { 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]) { if (priorityObject != nullptr && priorityObject->GetCurAdj() >= G_MEMORY_LEVEL[level]) {
auto pid = priorityObject->GetPid(); auto pid = priorityObject->GetPid();
if (pid <= 0) { if (pid <= 0) {
@ -449,13 +456,12 @@ void ProcessOptimizer::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel leve
continue; continue;
} }
if (lmksClient_->ProcRemove(priorityObject->GetPid()) != ERR_OK) { APP_LOGI("remove pid (%{publid}d) from lmks, bundle:%{public}s", pid, appRecord->GetBundleName().c_str());
APP_LOGE("failed to remove pid (%{publid}d) from lmks.", priorityObject->GetPid()); if (lmksClient_->ProcRemove(pid) == ERR_OK) {
} else {
APP_LOGE("success to remove pid (%{publid}d) from lmks.", priorityObject->GetPid());
iter = appLru_.erase(iter); iter = appLru_.erase(iter);
continue; continue;
} }
APP_LOGE("remove error, pid:%{publid}d, bundle:%{public}s", pid, appRecord->GetBundleName().c_str());
} }
iter++; iter++;
} }

View File

@ -82,6 +82,7 @@ ohos_source_set("appmgr_test_source") {
"//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//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", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
] ]

View File

@ -46,6 +46,8 @@ public:
MOCK_METHOD2(GetSystemMemoryAttr, void(SystemMemoryAttr &memoryInfo, std::string &strConfig)); MOCK_METHOD2(GetSystemMemoryAttr, void(SystemMemoryAttr &memoryInfo, std::string &strConfig));
MOCK_METHOD0(StartupResidentProcess, void()); MOCK_METHOD0(StartupResidentProcess, void());
MOCK_METHOD1(AddAbilityStageDone, void(const int32_t recordId)); MOCK_METHOD1(AddAbilityStageDone, void(const int32_t recordId));
MOCK_METHOD1(RegisterApplicationStateObserver, int32_t(const sptr<IApplicationStateObserver> &observer));
MOCK_METHOD1(UnregisterApplicationStateObserver, int32_t(const sptr<IApplicationStateObserver> &observer));
virtual void RegisterAppStateCallback(const sptr<IAppStateCallback> &callback) virtual void RegisterAppStateCallback(const sptr<IAppStateCallback> &callback)
{ {

View File

@ -23,6 +23,7 @@
#include "app_record_id.h" #include "app_record_id.h"
#include "mock_application.h" #include "mock_application.h"
#include "mock_app_mgr_service.h" #include "mock_app_mgr_service.h"
#include "application_state_observer_stub.h"
using namespace testing::ext; using namespace testing::ext;
@ -266,7 +267,6 @@ HWTEST_F(AmsIpcAppMgrInterfaceTest, GetAllRunningProcesses_010, TestSize.Level1)
APP_LOGD("GetAllRunningProcesses_009 end"); APP_LOGD("GetAllRunningProcesses_009 end");
} }
/* /*
* Feature: AMS * Feature: AMS
* Function: IPC * Function: IPC
@ -301,5 +301,53 @@ HWTEST_F(AmsIpcAppMgrInterfaceTest, GetSystemMemoryAttr_0100, TestSize.Level1)
APP_LOGD("GetSystemMemoryAttr_0100 end"); 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<IApplicationStateObserver> observer = new ApplicationStateObserverStub();
sptr<MockAppMgrService> mockAppMgr(new MockAppMgrService());
sptr<IAppMgr> appMgrClient = iface_cast<IAppMgr>(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<IApplicationStateObserver> observer = new ApplicationStateObserverStub();
sptr<MockAppMgrService> mockAppMgr(new MockAppMgrService());
sptr<IAppMgr> appMgrClient = iface_cast<IAppMgr>(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 AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -23,6 +23,7 @@
#include "app_state_callback_host.h" #include "app_state_callback_host.h"
#include "mock_ability_token.h" #include "mock_ability_token.h"
#include "mock_app_mgr_service_inner.h" #include "mock_app_mgr_service_inner.h"
#include "application_state_observer_stub.h"
using namespace testing; using namespace testing;
using namespace testing::ext; using namespace testing::ext;
@ -402,5 +403,45 @@ HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_010, TestSize.Level1)
APP_LOGD("AmsMgrScheduler_010 end."); 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<IApplicationStateObserver> observer = new ApplicationStateObserverStub();
auto mockAppMgrServiceInner = std::make_shared<MockAppMgrServiceInner>();
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<IApplicationStateObserver> observer = new ApplicationStateObserverStub();
auto mockAppMgrServiceInner = std::make_shared<MockAppMgrServiceInner>();
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 AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -21,6 +21,7 @@
#include <vector> #include <vector>
#include <unordered_map> #include <unordered_map>
#include "form_record.h" #include "form_record.h"
#include "form_info.h"
namespace OHOS { namespace OHOS {
namespace AppExecFwk { namespace AppExecFwk {
@ -220,6 +221,67 @@ public:
* @param isFormVisibleNotify visible notify or not. * @param isFormVisibleNotify visible notify or not.
*/ */
void SetFormVisibleNotify(bool isFormVisibleNotify); 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: private:
/** /**
* @brief Equal or not. * @brief Equal or not.
@ -228,7 +290,7 @@ private:
* @return Equal or not * @return Equal or not
*/ */
bool IsEqual(const std::string &left, const std::string &right); bool IsEqual(const std::string &left, const std::string &right);
private: private:
int64_t formId_ = -1; int64_t formId_ = -1;
std::string packageName_ = ""; std::string packageName_ = "";
@ -244,6 +306,12 @@ private:
std::vector<std::string> hapSourceDirs_; std::vector<std::string> hapSourceDirs_;
bool temporaryFlag_ = false; bool temporaryFlag_ = false;
bool formVisibleNotify_ = 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 jsComponentName_ = "";
std::string abilityModuleName_ = ""; std::string abilityModuleName_ = "";

View File

@ -18,6 +18,7 @@
#include <vector> #include <vector>
#include "form_provider_info.h" #include "form_provider_info.h"
#include "form_info.h"
namespace OHOS { namespace OHOS {
namespace AppExecFwk { namespace AppExecFwk {
@ -51,6 +52,12 @@ public:
bool formVisibleNotify = false; bool formVisibleNotify = false;
int formVisibleNotifyState = 0; int formVisibleNotifyState = 0;
int userId = 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 AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -51,7 +51,7 @@ void FormAcquireConnection::OnAbilityConnectDone(
APP_LOGI("%{public}s called.", __func__); APP_LOGI("%{public}s called.", __func__);
if (resultCode != ERR_OK) { 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); __func__, element.GetAbilityName().c_str(), formId_, resultCode);
return; return;
} }
@ -59,6 +59,7 @@ void FormAcquireConnection::OnAbilityConnectDone(
Want want; Want want;
want.SetParams(wantParams_); want.SetParams(wantParams_);
FormUtil::CreateFormWant(info_.GetFormName(), info_.GetSpecificationId(), info_.IsTemporaryForm(), want); FormUtil::CreateFormWant(info_.GetFormName(), info_.GetSpecificationId(), info_.IsTemporaryForm(), want);
want.SetElementName(info_.GetProviderBundleName(), info_.GetAbilityName());
if (want.GetBoolParam(Constants::RECREATE_FORM_KEY, false)) { if (want.GetBoolParam(Constants::RECREATE_FORM_KEY, false)) {
want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM);
} else { } else {

View File

@ -161,6 +161,13 @@ FormRecord FormDataMgr::CreateFormRecord(const FormItemInfo &formInfo, const int
newRecord.formTempFlg = formInfo.IsTemporaryForm(); newRecord.formTempFlg = formInfo.IsTemporaryForm();
newRecord.formVisibleNotify = formInfo.IsFormVisibleNotify(); newRecord.formVisibleNotify = formInfo.IsFormVisibleNotify();
newRecord.jsFormCodePath = formInfo.GetHapSourceByModuleName(newRecord.moduleName); 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; newRecord.formVisibleNotifyState = 0;
if (newRecord.isEnableUpdate) { if (newRecord.isEnableUpdate) {
ParseUpdateConfig(newRecord, formInfo); ParseUpdateConfig(newRecord, formInfo);
@ -188,6 +195,12 @@ void FormDataMgr::CreateFormInfo(const int64_t formId, const FormRecord &record,
formInfo.abilityName = record.abilityName; formInfo.abilityName = record.abilityName;
formInfo.formName = record.formName; formInfo.formName = record.formName;
formInfo.formTempFlg = record.formTempFlg; 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. * @brief Check temp form count is max.

View File

@ -134,6 +134,13 @@ void FormDumpMgr::DumpFormInfo(const FormRecord &formRecordInfo, std::string &fo
formInfo += " formTempFlg [" + std::to_string(formRecordInfo.formTempFlg) + "]"; formInfo += " formTempFlg [" + std::to_string(formRecordInfo.formTempFlg) + "]";
formInfo += " formVisibleNotify [" + std::to_string(formRecordInfo.formVisibleNotify) + "]"; formInfo += " formVisibleNotify [" + std::to_string(formRecordInfo.formVisibleNotify) + "]";
formInfo += " formVisibleNotifyState [" + std::to_string(formRecordInfo.formVisibleNotifyState) + "]"; 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) { if (formRecordInfo.hapSourceDirs.size() > 0) {
formInfo += " hapSourceDirs ["; formInfo += " hapSourceDirs [";

View File

@ -1,370 +1,467 @@
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "app_log_wrapper.h" #include "app_log_wrapper.h"
#include "form_item_info.h" #include "form_item_info.h"
namespace OHOS { namespace OHOS {
namespace AppExecFwk { namespace AppExecFwk {
/** /**
* @brief Get formId_. * @brief Get formId_.
* @return formId_. * @return formId_.
*/ */
int64_t FormItemInfo::GetFormId() const int64_t FormItemInfo::GetFormId() const
{ {
return formId_; return formId_;
} }
/** /**
* @brief Get packageName_. * @brief Get packageName_.
* @return packageName_. * @return packageName_.
*/ */
std::string FormItemInfo::GetPackageName() const std::string FormItemInfo::GetPackageName() const
{ {
return packageName_; return packageName_;
} }
/** /**
* @brief Get providerBundleName_. * @brief Get providerBundleName_.
* @return providerBundleName_. * @return providerBundleName_.
*/ */
std::string FormItemInfo::GetProviderBundleName() const std::string FormItemInfo::GetProviderBundleName() const
{ {
return providerBundleName_; return providerBundleName_;
} }
/** /**
* @brief Get hostBundleName_. * @brief Get hostBundleName_.
* @return hostBundleName_. * @return hostBundleName_.
*/ */
std::string FormItemInfo::GetHostBundleName() const std::string FormItemInfo::GetHostBundleName() const
{ {
return hostBundleName_; return hostBundleName_;
} }
/** /**
* @brief Get moduleName_. * @brief Get moduleName_.
* @return moduleName_. * @return moduleName_.
*/ */
std::string FormItemInfo::GetModuleName() const std::string FormItemInfo::GetModuleName() const
{ {
return moduleName_; return moduleName_;
} }
/** /**
* @brief Get abilityName_. * @brief Get abilityName_.
* @return abilityName_. * @return abilityName_.
*/ */
std::string FormItemInfo::GetAbilityName() const std::string FormItemInfo::GetAbilityName() const
{ {
return abilityName_; return abilityName_;
} }
/** /**
* @brief Get formName_. * @brief Get formName_.
* @return formName_. * @return formName_.
*/ */
std::string FormItemInfo::GetFormName() const std::string FormItemInfo::GetFormName() const
{ {
return formName_; return formName_;
} }
/** /**
* @brief Get jsComponentName_. * @brief Get jsComponentName_.
* @return jsComponentName_. * @return jsComponentName_.
*/ */
std::string FormItemInfo::GetJsComponentName() const std::string FormItemInfo::GetJsComponentName() const
{ {
return jsComponentName_; return jsComponentName_;
} }
/** /**
* @brief Get abilityModuleName_. * @brief Get abilityModuleName_.
* @return abilityModuleName_. * @return abilityModuleName_.
*/ */
std::string FormItemInfo::GetAbilityModuleName() const std::string FormItemInfo::GetAbilityModuleName() const
{ {
return abilityModuleName_; return abilityModuleName_;
} }
/** /**
* @brief Get specificationId_. * @brief Get specificationId_.
* @return specificationId_. * @return specificationId_.
*/ */
int FormItemInfo::GetSpecificationId() const int FormItemInfo::GetSpecificationId() const
{ {
return specificationId_; return specificationId_;
} }
/** /**
* @brief Obtains the updageFlag. * @brief Obtains the updageFlag.
* @return Returns updageFlag. * @return Returns updageFlag.
*/ */
bool FormItemInfo::IsEnableUpdateFlag() const bool FormItemInfo::IsEnableUpdateFlag() const
{ {
return updateFlag_; return updateFlag_;
} }
/** /**
* @brief Get updateDuration_. * @brief Get updateDuration_.
* @return updateDuration_. * @return updateDuration_.
*/ */
int FormItemInfo::GetUpdateDuration() const int FormItemInfo::GetUpdateDuration() const
{ {
return updateDuration_; return updateDuration_;
} }
/** /**
* @brief Get scheduledUpdateTime_. * @brief Get scheduledUpdateTime_.
* @return scheduledUpdateTime_. * @return scheduledUpdateTime_.
*/ */
std::string FormItemInfo::GetScheduledUpdateTime() const std::string FormItemInfo::GetScheduledUpdateTime() const
{ {
return scheduledUpdateTime_; return scheduledUpdateTime_;
} }
/** /**
* @brief Get hapSourceDirs_. * @brief Get hapSourceDirs_.
* @param dirs Hap source dirs. * @param dirs Hap source dirs.
* @return Returns true on success, false on failure. * @return Returns true on success, false on failure.
*/ */
bool FormItemInfo::GetHapSourceDirs(std::vector<std::string> &dirs) const bool FormItemInfo::GetHapSourceDirs(std::vector<std::string> &dirs) const
{ {
if (hapSourceDirs_.size() > 0) { if (hapSourceDirs_.size() > 0) {
dirs.assign(hapSourceDirs_.begin(), hapSourceDirs_.end()); dirs.assign(hapSourceDirs_.begin(), hapSourceDirs_.end());
return true; return true;
} }
return false; return false;
} }
/** /**
* @brief Set value of hapSourceDirs_. * @brief Set value of hapSourceDirs_.
* @param hapSourceDirs Hap source dirs. * @param hapSourceDirs Hap source dirs.
*/ */
void FormItemInfo::SetHapSourceDirs(const std::vector<std::string> &hapSourceDirs) void FormItemInfo::SetHapSourceDirs(const std::vector<std::string> &hapSourceDirs)
{ {
hapSourceDirs_ = hapSourceDirs; hapSourceDirs_ = hapSourceDirs;
} }
/** /**
* @brief Obtains the temporaryFlag. * @brief Obtains the temporaryFlag.
* @return Returns temporaryFlag. * @return Returns temporaryFlag.
*/ */
bool FormItemInfo::IsTemporaryForm() const bool FormItemInfo::IsTemporaryForm() const
{ {
return temporaryFlag_; return temporaryFlag_;
} }
/** /**
* @brief Obtains the hap source by ability module name. * @brief Obtains the hap source by ability module name.
* @param moduleName ability module name * @param moduleName ability module name
* @return Returns hap source. * @return Returns hap source.
*/ */
std::string FormItemInfo::GetHapSourceByModuleName(const std::string &moduleName) const std::string FormItemInfo::GetHapSourceByModuleName(const std::string &moduleName) const
{ {
auto iter = moduleInfoMap_.find(moduleName); auto iter = moduleInfoMap_.find(moduleName);
if (iter != moduleInfoMap_.end()) { if (iter != moduleInfoMap_.end()) {
return iter->second; return iter->second;
} }
return ""; return "";
} }
/** /**
* @brief Check if item valid or not. * @brief Check if item valid or not.
* @return Valid or not * @return Valid or not
*/ */
bool FormItemInfo::IsValidItem() const bool FormItemInfo::IsValidItem() const
{ {
if (providerBundleName_.empty() || moduleName_.empty() if (providerBundleName_.empty() || moduleName_.empty()
|| abilityName_.empty() || formName_.empty()) { || abilityName_.empty() || formName_.empty()) {
return false; return false;
} }
return true; return true;
} }
/** /**
* @brief Check if item match or not. * @brief Check if item match or not.
* @return Match or not * @return Match or not
*/ */
bool FormItemInfo::IsMatch(const FormRecord &record) const bool FormItemInfo::IsMatch(const FormRecord &record) const
{ {
APP_LOGD("match data"); APP_LOGD("match data");
APP_LOGD("FormRecord.bundleName : %{public}s", record.bundleName.c_str()); APP_LOGD("FormRecord.bundleName : %{public}s", record.bundleName.c_str());
APP_LOGD("FormRecord.moduleName : %{public}s", record.moduleName.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.abilityName : %{public}s", record.abilityName.c_str());
APP_LOGD("FormRecord.formName : %{public}s", record.formName.c_str()); APP_LOGD("FormRecord.formName : %{public}s", record.formName.c_str());
APP_LOGD("FormRecord.specification : %{public}d", record.specification); APP_LOGD("FormRecord.specification : %{public}d", record.specification);
APP_LOGD("FormItemInfo.providerBundleName_ : %{public}s", providerBundleName_.c_str()); APP_LOGD("FormItemInfo.providerBundleName_ : %{public}s", providerBundleName_.c_str());
APP_LOGD("FormItemInfo.moduleName : %{public}s", moduleName_.c_str()); APP_LOGD("FormItemInfo.moduleName : %{public}s", moduleName_.c_str());
APP_LOGD("FormItemInfo.abilityName : %{public}s", abilityName_.c_str()); APP_LOGD("FormItemInfo.abilityName : %{public}s", abilityName_.c_str());
APP_LOGD("FormItemInfo.formName : %{public}s", formName_.c_str()); APP_LOGD("FormItemInfo.formName : %{public}s", formName_.c_str());
APP_LOGD("FormItemInfo.specification : %{public}d", specificationId_); APP_LOGD("FormItemInfo.specification : %{public}d", specificationId_);
return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_)
&& (record.abilityName == abilityName_) && (record.formName == formName_) && (record.abilityName == abilityName_) && (record.formName == formName_)
&& (record.specification == specificationId_); && (record.specification == specificationId_);
} }
/** /**
* @brief Check if form config same or not. * @brief Check if form config same or not.
* @return Same or not * @return Same or not
*/ */
bool FormItemInfo::IsSameFormConfig(const FormRecord &record) const bool FormItemInfo::IsSameFormConfig(const FormRecord &record) const
{ {
return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_)
&& (record.abilityName == abilityName_) && (record.formName == formName_); && (record.abilityName == abilityName_) && (record.formName == formName_);
} }
/** /**
* @brief Check if visible notify or not. * @brief Check if visible notify or not.
* @return visible notify or not * @return visible notify or not
*/ */
bool FormItemInfo::IsFormVisibleNotify() const bool FormItemInfo::IsFormVisibleNotify() const
{ {
return formVisibleNotify_; return formVisibleNotify_;
} }
/** /**
* @brief Equal or not. * @brief Equal or not.
* @param left left string. * @param left left string.
* @param right right string. * @param right right string.
* @return Equal or not * @return Equal or not
*/ */
bool FormItemInfo::IsEqual(const std::string &left, const std::string &right) bool FormItemInfo::IsEqual(const std::string &left, const std::string &right)
{ {
return left == right; return left == right;
} }
/** /**
* @brief Set value of formId_. * @brief Set value of formId_.
* @param formId Form Id. * @param formId Form Id.
*/ */
void FormItemInfo::SetFormId(int64_t formId) void FormItemInfo::SetFormId(int64_t formId)
{ {
formId_ = formId; formId_ = formId;
} }
/** /**
* @brief Set value of packageName_. * @brief Set value of packageName_.
* @param packageName Package name. * @param packageName Package name.
*/ */
void FormItemInfo::SetPackageName(const std::string &packageName) void FormItemInfo::SetPackageName(const std::string &packageName)
{ {
packageName_ = packageName; packageName_ = packageName;
} }
/** /**
* @brief Set value of providerBundleName_. * @brief Set value of providerBundleName_.
* @param providerBundleName Provider bundle Name. * @param providerBundleName Provider bundle Name.
*/ */
void FormItemInfo::SetProviderBundleName(const std::string &providerBundleName) void FormItemInfo::SetProviderBundleName(const std::string &providerBundleName)
{ {
providerBundleName_ = providerBundleName; providerBundleName_ = providerBundleName;
} }
/** /**
* @brief Set value of hostBundleName_. * @brief Set value of hostBundleName_.
* @param hostBundleName Host bundle Name. * @param hostBundleName Host bundle Name.
*/ */
void FormItemInfo::SetHostBundleName(const std::string &hostBundleName) void FormItemInfo::SetHostBundleName(const std::string &hostBundleName)
{ {
hostBundleName_ = hostBundleName; hostBundleName_ = hostBundleName;
} }
/** /**
* @brief Set value of moduleName_. * @brief Set value of moduleName_.
* @param moduleName Module Name. * @param moduleName Module Name.
*/ */
void FormItemInfo::SetModuleName(const std::string &moduleName) void FormItemInfo::SetModuleName(const std::string &moduleName)
{ {
moduleName_ = moduleName; moduleName_ = moduleName;
} }
/** /**
* @brief Set value of abilityName_. * @brief Set value of abilityName_.
* @param abilityName Ability name. * @param abilityName Ability name.
*/ */
void FormItemInfo::SetAbilityName(const std::string &abilityName) void FormItemInfo::SetAbilityName(const std::string &abilityName)
{ {
abilityName_ = abilityName; abilityName_ = abilityName;
} }
/** /**
* @brief Set value of formName_. * @brief Set value of formName_.
* @param formName Form name. * @param formName Form name.
*/ */
void FormItemInfo::SetFormName(const std::string &formName) void FormItemInfo::SetFormName(const std::string &formName)
{ {
formName_ = formName; formName_ = formName;
} }
/** /**
* @brief Set value of jsComponentName_. * @brief Set value of jsComponentName_.
* @param jsComponentName Js component name. * @param jsComponentName Js component name.
*/ */
void FormItemInfo::SetJsComponentName(const std::string &jsComponentName) void FormItemInfo::SetJsComponentName(const std::string &jsComponentName)
{ {
jsComponentName_ = jsComponentName; jsComponentName_ = jsComponentName;
} }
/** /**
* @brief Set value of abilityModuleName_. * @brief Set value of abilityModuleName_.
* @param abilityModuleName ability module name_. * @param abilityModuleName ability module name_.
*/ */
void FormItemInfo::SetAbilityModuleName(const std::string &abilityModuleName) void FormItemInfo::SetAbilityModuleName(const std::string &abilityModuleName)
{ {
abilityModuleName_ = abilityModuleName; abilityModuleName_ = abilityModuleName;
} }
/** /**
* @brief Set value of specificationId_. * @brief Set value of specificationId_.
* @param specificationId Specification id. * @param specificationId Specification id.
*/ */
void FormItemInfo::SetSpecificationId(const int specificationId) void FormItemInfo::SetSpecificationId(const int specificationId)
{ {
specificationId_ = specificationId; specificationId_ = specificationId;
} }
/** /**
* @brief Set value of updateFlag_. * @brief Set value of updateFlag_.
* @param IsEnableUpdateFlag Enable update flag or not. * @param IsEnableUpdateFlag Enable update flag or not.
*/ */
void FormItemInfo::SetEnableUpdateFlag(bool IsEnableUpdateFlag) void FormItemInfo::SetEnableUpdateFlag(bool IsEnableUpdateFlag)
{ {
updateFlag_ = IsEnableUpdateFlag; updateFlag_ = IsEnableUpdateFlag;
} }
/** /**
* @brief Set value of updateDuration_. * @brief Set value of updateDuration_.
* @param updateDuration Update duration. * @param updateDuration Update duration.
*/ */
void FormItemInfo::SetUpdateDuration(int updateDuration) void FormItemInfo::SetUpdateDuration(int updateDuration)
{ {
updateDuration_ = updateDuration; updateDuration_ = updateDuration;
} }
/** /**
* @brief Set value of scheduledUpdateTime_. * @brief Set value of scheduledUpdateTime_.
* @param scheduledUpdateTime Scheduled update time. * @param scheduledUpdateTime Scheduled update time.
*/ */
void FormItemInfo::SetScheduledUpdateTime(const std::string &scheduledUpdateTime) void FormItemInfo::SetScheduledUpdateTime(const std::string &scheduledUpdateTime)
{ {
scheduledUpdateTime_ = scheduledUpdateTime; scheduledUpdateTime_ = scheduledUpdateTime;
} }
/** /**
* @brief Add hap source dir. * @brief Add hap source dir.
* @param hapSourceDir Hap source dir. * @param hapSourceDir Hap source dir.
*/ */
void FormItemInfo::AddHapSourceDirs(const std::string &hapSourceDir) void FormItemInfo::AddHapSourceDirs(const std::string &hapSourceDir)
{ {
hapSourceDirs_.emplace_back(hapSourceDir); hapSourceDirs_.emplace_back(hapSourceDir);
} }
/** /**
* @brief Set value of temporaryFlag_. * @brief Set value of temporaryFlag_.
* @param temporaryFlag Temporary flag. * @param temporaryFlag Temporary flag.
*/ */
void FormItemInfo::SetTemporaryFlag(bool temporaryFlag) void FormItemInfo::SetTemporaryFlag(bool temporaryFlag)
{ {
temporaryFlag_ = temporaryFlag; temporaryFlag_ = temporaryFlag;
} }
/** /**
* @brief Add module info. * @brief Add module info.
* @param moduleName Module name. * @param moduleName Module name.
* @param moduleSourceDir Module source dir. * @param moduleSourceDir Module source dir.
*/ */
void FormItemInfo::AddModuleInfo(const std::string &moduleName, const std::string &moduleSourceDir) void FormItemInfo::AddModuleInfo(const std::string &moduleName, const std::string &moduleSourceDir)
{ {
moduleInfoMap_.emplace(std::make_pair(moduleName, moduleSourceDir)); moduleInfoMap_.emplace(std::make_pair(moduleName, moduleSourceDir));
} }
/** /**
* @brief Set value of formVisibleNotify_. * @brief Set value of formVisibleNotify_.
* @param isFormVisibleNotify visible notify or not. * @param isFormVisibleNotify visible notify or not.
*/ */
void FormItemInfo::SetFormVisibleNotify(bool isFormVisibleNotify) void FormItemInfo::SetFormVisibleNotify(bool isFormVisibleNotify)
{ {
formVisibleNotify_ = isFormVisibleNotify; formVisibleNotify_ = isFormVisibleNotify;
} }
} // namespace AppExecFwk /**
* @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 } // namespace OHOS

View File

@ -394,12 +394,6 @@ int FormMgrAdapter::UpdateForm(const int64_t formId,
return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; 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 // check bundleName match
if (formRecord.bundleName.compare(bundleName) != 0) { if (formRecord.bundleName.compare(bundleName) != 0) {
APP_LOGE("%{public}s error, not match bundleName:%{public}s.", __func__, bundleName.c_str()); 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 formInfo Form info.
* @param itemInfo Form configure info. * @param itemInfo Form configure info.
*/ */
ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo,
const FormInfo &formInfo, FormItemInfo &itemInfo) const FormInfo &formInfo, FormItemInfo &itemInfo)
{ {
itemInfo.SetProviderBundleName(bundleInfo.name); itemInfo.SetProviderBundleName(bundleInfo.name);
itemInfo.SetVersionCode(bundleInfo.versionCode);
itemInfo.SetVersionName(bundleInfo.versionName);
itemInfo.SetCompatibleVersion(bundleInfo.compatibleVersion);
sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
if (iBundleMgr == nullptr) { if (iBundleMgr == nullptr) {
APP_LOGE("GetFormInfo, failed to get IBundleMgr."); APP_LOGE("GetFormInfo, failed to get IBundleMgr.");
@ -1159,6 +1157,9 @@ ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo,
return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
} }
itemInfo.SetHostBundleName(hostBundleName); itemInfo.SetHostBundleName(hostBundleName);
std::string icon = iBundleMgr->GetAbilityIcon(bundleInfo.name, formInfo.abilityName);
itemInfo.SetIcon(icon);
itemInfo.SetAbilityName(formInfo.abilityName); itemInfo.SetAbilityName(formInfo.abilityName);
itemInfo.SetModuleName(formInfo.moduleName); // formInfo.moduleName: bundleMagr do not set itemInfo.SetModuleName(formInfo.moduleName); // formInfo.moduleName: bundleMagr do not set
itemInfo.SetFormName(formInfo.name); itemInfo.SetFormName(formInfo.name);
@ -1167,6 +1168,8 @@ ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo,
itemInfo.SetScheduledUpdateTime(formInfo.scheduledUpateTime); itemInfo.SetScheduledUpdateTime(formInfo.scheduledUpateTime);
itemInfo.SetJsComponentName(formInfo.jsComponentName); itemInfo.SetJsComponentName(formInfo.jsComponentName);
itemInfo.SetFormVisibleNotify(formInfo.formVisibleNotify); itemInfo.SetFormVisibleNotify(formInfo.formVisibleNotify);
itemInfo.SetFormSrc(formInfo.src);
itemInfo.SetFormWindow(formInfo.window);
for (const auto &abilityInfo : bundleInfo.abilityInfos) { for (const auto &abilityInfo : bundleInfo.abilityInfos) {
if (abilityInfo.name == formInfo.abilityName) { 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()); APP_LOGI("%{public}s moduleInfos size: %{public}zu", __func__, bundleInfo.applicationInfo.moduleInfos.size());
for (const auto &item : bundleInfo.applicationInfo.moduleInfos) { 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()); item.moduleName.c_str(), item.moduleSourceDir.c_str());
if (formInfo.moduleName == item.moduleName) { if (formInfo.moduleName == item.moduleName) {
itemInfo.AddHapSourceDirs(item.moduleSourceDir); itemInfo.AddHapSourceDirs(item.moduleSourceDir);

View File

@ -500,7 +500,9 @@ FormJsInfo FormTaskMgr::CreateFormJsInfo(const int64_t formId, const FormRecord
form.jsFormCodePath = record.jsFormCodePath; form.jsFormCodePath = record.jsFormCodePath;
form.formData = record.formProviderInfo.GetFormDataString(); form.formData = record.formProviderInfo.GetFormDataString();
form.formProviderData = record.formProviderInfo.GetFormData(); 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()); form.jsFormCodePath.c_str(), form.formData.c_str());
return form; return form;
} }

View File

@ -268,6 +268,53 @@ public:
{ {
return 0; 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<IMissionListener> &listener) override
{
return 0;
}
virtual int UnRegisterMissionListener(const sptr<IMissionListener> &listener) override
{
return 0;
}
virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax,
std::vector<MissionInfo> &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<AAFwk::IAbilityManager> { class MockAbilityMgrStub : public IRemoteStub<AAFwk::IAbilityManager> {
@ -597,6 +644,52 @@ public:
return 0; 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<IMissionListener> &listener) override
{
return 0;
}
virtual int UnRegisterMissionListener(const sptr<IMissionListener> &listener) override
{
return 0;
}
virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax,
std::vector<MissionInfo> &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: private:
Semaphore sem_; Semaphore sem_;
}; };

View File

@ -66,6 +66,7 @@ ohos_unittest("FmsFormMgrAddFormTest") {
#"${services_path}/bundlemgr:bms_target", #"${services_path}/bundlemgr:bms_target",
"//foundation/aafwk/standard/services/abilitymgr:abilityms_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/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gmock_main", "//third_party/googletest:gmock_main",

View File

@ -317,6 +317,53 @@ public:
{ {
return 0; 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<IMissionListener> &listener) override
{
return 0;
}
virtual int UnRegisterMissionListener(const sptr<IMissionListener> &listener) override
{
return 0;
}
virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax,
std::vector<MissionInfo> &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 AppExecFwk
} // namespace OHOS } // namespace OHOS

View File

@ -48,6 +48,11 @@
"forms": [ "forms": [
{ {
"name": "Form_Js001", "name": "Form_Js001",
"src": "pages/card/index",
"window": {
"designWidth": 720,
"autoDesignWidth": true
},
"description": "form_description", "description": "form_description",
"isDefault": true, "isDefault": true,
"type": "JS", "type": "JS",

View File

@ -47,7 +47,7 @@ ohos_systemtest("bm_command_install_system_test") {
"ipc:ipc_core", "ipc:ipc_core",
] ]
resource_config_file = 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") { ohos_systemtest("bm_command_uninstall_system_test") {
@ -81,7 +81,7 @@ ohos_systemtest("bm_command_uninstall_system_test") {
"ipc:ipc_core", "ipc:ipc_core",
] ]
resource_config_file = 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") { ohos_systemtest("bm_command_dump_system_test") {
@ -115,7 +115,7 @@ ohos_systemtest("bm_command_dump_system_test") {
"ipc:ipc_core", "ipc:ipc_core",
] ]
resource_config_file = resource_config_file =
"//foundation/appexecfwk/standard/test/resource/tools/ohos_test.xml" "//foundation/appexecfwk/standard/test/resource/tools/ohos_test.xml"
} }
group("systemtest") { group("systemtest") {