Generic component call call

Signed-off-by: njupthan <hanhaibin@huawei.com>
This commit is contained in:
njupthan 2022-01-26 14:45:49 +00:00
parent 24742f9645
commit 14faefcfb1
83 changed files with 4029 additions and 33 deletions

View File

@ -38,6 +38,8 @@ ohos_shared_library("ability_context_native") {
"${SO_DIR}/src/ability_context_impl.cpp",
"${SO_DIR}/src/connection_manager.cpp",
"${SO_DIR}/src/js_extension_context.cpp",
"${SO_DIR}/src/local_call_container.cpp",
"${SO_DIR}/src/local_call_record.cpp",
]
deps = [

View File

@ -23,6 +23,7 @@
#include "native_engine/native_value.h"
#include "start_options.h"
#include "want.h"
#include "caller_callback.h"
namespace OHOS {
namespace AbilityRuntime {
@ -151,6 +152,25 @@ public:
*/
virtual void* GetContentStorage() = 0;
/**
* call function by callback object
*
* @param want Request info for ability.
* @param callback Indicates the callback object.
*
* @return Returns zero on success, others on failure.
*/
virtual ErrCode StartAbility(const AAFwk::Want& want, const std::shared_ptr<CallerCallBack> &callback) = 0;
/**
* caller release by callback object
*
* @param callback Indicates the callback object.
*
* @return Returns zero on success, others on failure.
*/
virtual ErrCode ReleaseAbility(const std::shared_ptr<CallerCallBack> &callback) = 0;
/**
* @brief Set mission label of this ability.
*

View File

@ -19,6 +19,7 @@
#include "ability_context.h"
#include "context_impl.h"
#include "local_call_container.h"
namespace OHOS {
namespace AbilityRuntime {
@ -101,6 +102,25 @@ public:
return contentStorage_;
}
/**
* call function by callback object
*
* @param want Request info for ability.
* @param callback Indicates the callback object.
*
* @return Returns zero on success, others on failure.
*/
ErrCode StartAbility(const AAFwk::Want& want, const std::shared_ptr<CallerCallBack> &callback) override;
/**
* caller release by callback object
*
* @param callback Indicates the callback object.
*
* @return Returns zero on success, others on failure.
*/
ErrCode ReleaseAbility(const std::shared_ptr<CallerCallBack> &callback) override;
private:
sptr<IRemoteObject> token_;
std::shared_ptr<AppExecFwk::AbilityInfo> abilityInfo_ = nullptr;
@ -108,6 +128,7 @@ private:
std::map<int, RuntimeTask> resultCallbacks_;
std::map<int, PermissionRequestTask> permissionRequestCallbacks_;
void* contentStorage_ = nullptr;
sptr<LocalCallContainer> localCallContainer_;
};
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,71 @@
/*
* 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 ABILITY_RUNTIME_CALLER_CALLBACK_H
#define ABILITY_RUNTIME_CALLER_CALLBACK_H
#include "iremote_object.h"
namespace OHOS {
namespace AbilityRuntime {
const std::string ON_RELEASE = "release";
const std::string ON_DIED = "died";
/**
* @class CallerCallBack
* CallerCallBack the callback function of caller.
*/
class CallerCallBack : public std::enable_shared_from_this<CallerCallBack> {
public:
/* Caller's callback object */
using CallBackClosure = std::function<void(const sptr<IRemoteObject> &)>;
using OnReleaeClosure = std::function<void(const std::string &)>;
CallerCallBack() = default;
virtual ~CallerCallBack() = default;
void SetCallBack(CallBackClosure callback)
{
callback_ = callback;
};
void SetOnRelease(OnReleaeClosure onRelease)
{
onRelease_ = onRelease;
};
void InvokeCallBack(const sptr<IRemoteObject> &remoteObject)
{
if (callback_) {
callback_(remoteObject);
isCallBack_ = true;
}
};
void InvokeOnRelease(const std::string &key)
{
if (onRelease_) {
onRelease_(key);
}
};
bool IsCallBack()
{
return isCallBack_;
};
private:
CallBackClosure callback_ = {};
OnReleaeClosure onRelease_ = {};
bool isCallBack_ = false;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_CALLER_CALLBACK_H

View File

@ -0,0 +1,54 @@
/*
* 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 ABILITY_RUNTIME_LOCAL_CALL_CONTAINER_H
#define ABILITY_RUNTIME_LOCAL_CALL_CONTAINER_H
#include "ability_connect_callback_stub.h"
#include "ability_connect_callback_proxy.h"
#include "local_call_record.h"
#include "want.h"
namespace OHOS {
namespace AbilityRuntime {
using Want = OHOS::AAFwk::Want;
using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub;
class LocalCallContainer : public AbilityConnectionStub {
public:
LocalCallContainer() = default;
virtual ~LocalCallContainer() = default;
int StartAbilityInner(
const Want &want, const std::shared_ptr<CallerCallBack> &callback, const sptr<IRemoteObject> &callerToken);
int Release(const std::shared_ptr<CallerCallBack> &callback);
void DumpCalls(std::vector<std::string> &info) const;
virtual void OnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode) override;
virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override;
private:
bool GetCallLocalreocrd(
const AppExecFwk::ElementName &elementName, std::shared_ptr<LocalCallRecord> &localCallRecord);
private:
std::map<std::string, std::shared_ptr<LocalCallRecord>> callProxyRecords_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_LOCAL_CALL_CONTAINER_H

View File

@ -0,0 +1,75 @@
/*
* 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 ABILITY_RUNTIME_LOCAL_CALL_RECORD_H
#define ABILITY_RUNTIME_LOCAL_CALL_RECORD_H
#include "caller_callback.h"
#include "element_name.h"
#include "iremote_object.h"
namespace OHOS {
namespace AbilityRuntime {
/**
* @class LocalCallRecord
* LocalCallRecord record local call info.
*/
class LocalCallRecord : public std::enable_shared_from_this<LocalCallRecord> {
public:
LocalCallRecord(const AppExecFwk::ElementName &elementName);
virtual ~LocalCallRecord();
void SetRemoteObject(const sptr<IRemoteObject> &call);
void AddCaller(const std::shared_ptr<CallerCallBack> &callback);
bool RemoveCaller(const std::shared_ptr<CallerCallBack> &callback);
void OnCallStubDied(const wptr<IRemoteObject> &remote);
sptr<IRemoteObject> GetRemoteObject() const;
void InvokeCallBack() const;
AppExecFwk::ElementName GetElementName() const;
bool IsExistCallBack() const;
private:
static int64_t callRecordId;
int recordId_ = 0; // record id
sptr<IRemoteObject> remoteObject_ = nullptr;
sptr<IRemoteObject::DeathRecipient> callRecipient_ = nullptr;
std::vector<std::shared_ptr<CallerCallBack>> callers_;
AppExecFwk::ElementName elementName_ = {};
};
/**
* @class CallRecipient
* CallRecipient notices IRemoteBroker died.
*/
class CallRecipient : public IRemoteObject::DeathRecipient {
public:
using RemoteDiedHandler = std::function<void(const wptr<IRemoteObject> &)>;
CallRecipient(RemoteDiedHandler handler) : handler_(handler) {};
virtual ~CallRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject> &__attribute__((unused)) remote) override
{
if (handler_) {
handler_(remote);
}
};
private:
RemoteDiedHandler handler_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_LOCAL_CALL_RECORD_H

View File

@ -250,6 +250,26 @@ ErrCode AbilityContextImpl::RestoreWindowStage(void* contentStorage)
return err;
}
ErrCode AbilityContextImpl::StartAbility(
const AAFwk::Want& want, const std::shared_ptr<CallerCallBack> &callback)
{
if (!localCallContainer_) {
localCallContainer_ = new (std::nothrow)LocalCallContainer();
}
return localCallContainer_->StartAbilityInner(want, callback, token_);
}
ErrCode AbilityContextImpl::ReleaseAbility(const std::shared_ptr<CallerCallBack> &callback)
{
if (!localCallContainer_) {
HILOG_ERROR("%{public}s false.", __func__);
return ERR_INVALID_VALUE;
}
return localCallContainer_->Release(callback);
}
ErrCode AbilityContextImpl::SetMissionLabel(const std::string &label)
{
HILOG_INFO("%{public}s begin. label = %{public}s", __func__, label.c_str());

View File

@ -0,0 +1,161 @@
/*
* 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 "hilog_wrapper.h"
#include "ability_manager_client.h"
#include "local_call_container.h"
namespace OHOS {
namespace AbilityRuntime {
int LocalCallContainer::StartAbilityInner(
const Want &want, const std::shared_ptr<CallerCallBack> &callback, const sptr<IRemoteObject> &callerToken)
{
HILOG_DEBUG("start ability by call.");
if (!callback) {
HILOG_ERROR("callbackis nullptr.");
return ERR_INVALID_VALUE;
}
if (want.GetElement().GetBundleName().empty()
|| want.GetElement().GetAbilityName().empty()) {
HILOG_ERROR("the element of want is empty.");
return ERR_INVALID_VALUE;
}
if (want.GetElement().GetDeviceID().empty()) {
HILOG_DEBUG("start ability by call, element:DeviceID is empty");
}
HILOG_DEBUG("start ability by call, element:%{public}s", want.GetElement().GetURI().c_str());
AppExecFwk::ElementName element = want.GetElement();
std::shared_ptr<LocalCallRecord> localCallRecord;
if (!GetCallLocalreocrd(element, localCallRecord)) {
localCallRecord = std::make_shared<LocalCallRecord>(element);
if (!localCallRecord) {
HILOG_ERROR("localCallRecord create fail.");
return ERR_INVALID_VALUE;
}
std::string uri = element.GetURI();
callProxyRecords_.emplace(uri, localCallRecord);
}
HILOG_DEBUG("start ability by call, localCallRecord->AddCaller(callback) begin");
localCallRecord->AddCaller(callback);
HILOG_DEBUG("start ability by call, localCallRecord->AddCaller(callback) end");
auto remote = localCallRecord->GetRemoteObject();
if (!remote) {
auto abilityClient = AAFwk::AbilityManagerClient::GetInstance();
if (abilityClient == nullptr) {
HILOG_ERROR("LocalCallContainer::Resolve abilityClient is nullptr");
return ERR_INVALID_VALUE;
}
sptr<IAbilityConnection> connect = iface_cast<IAbilityConnection>(this);
HILOG_DEBUG("start ability by call, abilityClient->StartAbilityByCall call");
return abilityClient->StartAbilityByCall(want, this, callerToken);
}
// already finish call requst.
HILOG_DEBUG("start ability by call, callback->InvokeCallBack(remote) begin");
callback->InvokeCallBack(remote);
HILOG_DEBUG("start ability by call, callback->InvokeCallBack(remote) end");
return ERR_OK;
}
int LocalCallContainer::Release(const std::shared_ptr<CallerCallBack>& callback)
{
auto isExist = [&callback](auto &record) {
return record.second->RemoveCaller(callback);
};
auto iter = std::find_if(callProxyRecords_.begin(), callProxyRecords_.end(), isExist);
if (iter == callProxyRecords_.end()) {
HILOG_ERROR("release localcallrecord failed.");
return ERR_INVALID_VALUE;
}
std::shared_ptr<LocalCallRecord> record = iter->second;
if (!record) {
HILOG_ERROR("record is nullptr.");
return ERR_INVALID_VALUE;
}
if (record->IsExistCallBack()) {
// just release callback.
return ERR_OK;
}
// notify ams this connect need to release.
AppExecFwk::ElementName elementName = record->GetElementName() ;
auto abilityClient = AAFwk::AbilityManagerClient::GetInstance();
if (abilityClient == nullptr) {
HILOG_ERROR("LocalCallContainer::Resolve abilityClient is nullptr");
return ERR_INVALID_VALUE;
}
sptr<IAbilityConnection> connect = iface_cast<IAbilityConnection>(this);
if (abilityClient->ReleaseAbility(connect, elementName) != ERR_OK) {
HILOG_ERROR("ReleaseAbility failed.");
return ERR_INVALID_VALUE;
}
callProxyRecords_.erase(iter);
return ERR_OK;
}
void LocalCallContainer::DumpCalls(std::vector<std::string> &info) const
{
HILOG_DEBUG("LocalCallContainer::DumpCalls called.");
}
void LocalCallContainer::OnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode)
{
HILOG_DEBUG("LocalCallContainer::OnAbilityConnectDone start %{public}s .", element.GetURI().c_str());
if (resultCode != ERR_OK) {
HILOG_ERROR("OnAbilityConnectDone failed.");
}
std::shared_ptr<LocalCallRecord> localCallRecord;
if (GetCallLocalreocrd(element, localCallRecord)) {
localCallRecord->SetRemoteObject(remoteObject);
}
if (localCallRecord) {
localCallRecord->InvokeCallBack();
}
HILOG_DEBUG("LocalCallContainer::OnAbilityConnectDone end.");
return;
}
void LocalCallContainer::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode)
{
}
bool LocalCallContainer::GetCallLocalreocrd(
const AppExecFwk::ElementName &elementName, std::shared_ptr<LocalCallRecord> &localCallRecord)
{
auto iter = callProxyRecords_.find(elementName.GetURI());
if (iter != callProxyRecords_.end()) {
localCallRecord = iter->second;
return true;
}
return false;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,117 @@
/*
* 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 "local_call_record.h"
#include "hilog_wrapper.h"
namespace OHOS {
namespace AbilityRuntime {
int64_t LocalCallRecord::callRecordId = 0;
LocalCallRecord::LocalCallRecord(const AppExecFwk::ElementName &elementName)
{
recordId_ = callRecordId++;
elementName_ = elementName;
}
LocalCallRecord::~LocalCallRecord()
{
if (remoteObject_ && callRecipient_) {
remoteObject_->RemoveDeathRecipient(callRecipient_);
}
}
void LocalCallRecord::SetRemoteObject(const sptr<IRemoteObject> &call)
{
if (!call) {
HILOG_ERROR("remote object is nullptr");
return;
}
remoteObject_ = call;
if (!callRecipient_) {
callRecipient_ =
new CallRecipient(std::bind(&LocalCallRecord::OnCallStubDied, this, std::placeholders::_1));
}
remoteObject_->AddDeathRecipient(callRecipient_);
HILOG_DEBUG("SetRemoteObject complete.");
}
void LocalCallRecord::AddCaller(const std::shared_ptr<CallerCallBack> &callback)
{
callers_.emplace_back(callback);
}
bool LocalCallRecord::RemoveCaller(const std::shared_ptr<CallerCallBack> &callback)
{
if (callers_.empty()) {
HILOG_ERROR("this caller vector is empty.");
return false;
}
auto iter = std::find(callers_.begin(), callers_.end(), callback);
if (iter != callers_.end()) {
callback->InvokeOnRelease(ON_RELEASE);
callers_.erase(iter);
return true;
}
HILOG_ERROR("this caller callback can't find.");
return false;
}
void LocalCallRecord::OnCallStubDied(const wptr<IRemoteObject> &remote)
{
HILOG_DEBUG("OnCallStubDied.");
for (auto &callBack:callers_) {
if (callBack) {
HILOG_ERROR("invoke caller's OnRelease.");
callBack->InvokeOnRelease(ON_DIED);
}
}
}
void LocalCallRecord::InvokeCallBack() const
{
if (!remoteObject_) {
HILOG_ERROR("remote object is nullptr, can't callback.");
return;
}
for (auto &callBack:callers_) {
if (callBack && !callBack->IsCallBack()) {
callBack->InvokeCallBack(remoteObject_);
}
}
HILOG_DEBUG("finish callback with remote object.");
}
sptr<IRemoteObject> LocalCallRecord::GetRemoteObject() const
{
return remoteObject_;
}
AppExecFwk::ElementName LocalCallRecord::GetElementName() const
{
return elementName_;
}
bool LocalCallRecord::IsExistCallBack() const
{
return (callers_.size() > 0);
}
} // namespace AbilityRuntime
} // namespace OHOS

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.
import("//build/test.gni")
module_output_path = "aafwk_standard/aafwk_L2"
###############################################################################
#1. intent(c++) get/set test without transport
config("module_private_config") {
visibility = [ ":*" ]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
include_dirs = [ "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS" ]
}
ohos_moduletest("ability_caller_fw_module_test") {
module_out_path = module_output_path
sources = [
"//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/sys_mgr_client_mock.cpp",
"moduletest/ability_caller_fw_module_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//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/kits:appkit_native",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"multimodalinput_base:libmmi-client",
"native_appdatamgr:native_appdatafwk",
"native_appdatamgr:native_dataability",
"native_appdatamgr:native_rdb",
]
}
################################################################################
group("abilityruntimemoduletest") {
testonly = true
deps = []
if (is_phone_product) {
deps += [ ":ability_caller_fw_module_test" ]
}
}

View File

@ -0,0 +1,328 @@
/*
* 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_manager_client.h"
#include "ability_manager_interface.h"
#include "string_ex.h"
#include "hilog_wrapper.h"
#include "ipc_skeleton.h"
#include "if_system_ability_manager.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
#include "sys_mgr_client.h"
namespace OHOS {
namespace AAFwk {
std::shared_ptr<AbilityManagerClient> mockMTInstance_ = nullptr;
std::mutex mockMTMutex_;
std::shared_ptr<AbilityManagerClient> AbilityManagerClient::GetInstance()
{
if (mockMTInstance_ == nullptr) {
std::lock_guard<std::mutex> lock_l(mockMTMutex_);
if (mockMTInstance_ == nullptr) {
mockMTInstance_ = std::make_shared<AbilityManagerClient>();
}
}
return mockMTInstance_;
}
AbilityManagerClient::AbilityManagerClient()
{}
AbilityManagerClient::~AbilityManagerClient()
{}
ErrCode AbilityManagerClient::AttachAbilityThread(
const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
{
HILOG_INFO("AbilityManagerClient::AttachAbilityThread start");
ErrCode err = Connect();
if (err != ERR_OK) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->AttachAbilityThread(scheduler, token);
}
ErrCode AbilityManagerClient::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->AbilityTransitionDone(token, state, saveData);
}
ErrCode AbilityManagerClient::ScheduleConnectAbilityDone(
const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ScheduleConnectAbilityDone(token, remoteObject);
}
ErrCode AbilityManagerClient::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ScheduleDisconnectAbilityDone(token);
}
ErrCode AbilityManagerClient::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
{
if (remoteObject_ == nullptr) {
HILOG_ERROR("%{private}s:ability service not command", __func__);
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ScheduleCommandAbilityDone(token);
}
void AbilityManagerClient::AddWindowInfo(const sptr<IRemoteObject> &token, int32_t windowToken)
{
if (remoteObject_ == nullptr) {
return;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
abms->AddWindowInfo(token, windowToken);
}
ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StartAbility(want, requestCode);
}
ErrCode AbilityManagerClient::StartAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
HILOG_INFO("AbilityManagerClient::StartAbility start");
if (remoteObject_ == nullptr) {
HILOG_INFO("AbilityManagerClient::StartAbility fail because remoteobject is null");
return ABILITY_SERVICE_NOT_CONNECTED;
}
HILOG_INFO("AbilityManagerClient::StartAbility start2");
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StartAbility(want, connect, callerToken);
}
ErrCode AbilityManagerClient::ReleaseAbility(
const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
{
HILOG_INFO("AbilityManagerClient::ReleaseAbility start");
if (remoteObject_ == nullptr) {
HILOG_INFO("AbilityManagerClient::ReleaseAbility fail because remoteobject is null");
return ABILITY_SERVICE_NOT_CONNECTED;
}
HILOG_INFO("AbilityManagerClient::StartAbility start2");
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ReleaseAbility(connect, element);
}
ErrCode AbilityManagerClient::TerminateAbility(
const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
{
HILOG_INFO("AbilityManagerClient::TerminateAbility start");
if (remoteObject_ == nullptr) {
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
HILOG_INFO("AbilityManagerClient::TerminateAbility end");
return abms->TerminateAbility(token, resultCode, resultWant);
}
ErrCode AbilityManagerClient::TerminateAbility(const sptr<IRemoteObject> &callerToken, int requestCode)
{
if (remoteObject_ == nullptr) {
HILOG_ERROR("%{private}s:ability service not connect", __func__);
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->TerminateAbility(callerToken, requestCode);
}
ErrCode AbilityManagerClient::ConnectAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
if (remoteObject_ == nullptr) {
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ConnectAbility(want, connect, callerToken);
}
ErrCode AbilityManagerClient::DisconnectAbility(const sptr<IAbilityConnection> &connect)
{
if (remoteObject_ == nullptr) {
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->DisconnectAbility(connect);
}
ErrCode AbilityManagerClient::DumpState(const std::string &args, std::vector<std::string> &state)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
abms->DumpState(args, state);
return ERR_OK;
}
ErrCode AbilityManagerClient::Connect()
{
std::lock_guard<std::mutex> lock(mockMTMutex_);
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
if (remoteObject_ == nullptr) {
HILOG_ERROR("AbilityManagerClient::Connect remoteObject_ == nullptr");
return ERR_NO_MEMORY;
}
return ERR_OK;
}
ErrCode AbilityManagerClient::GetAllStackInfo(StackInfo &stackInfo)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->GetAllStackInfo(stackInfo);
}
ErrCode AbilityManagerClient::StopServiceAbility(const Want &want)
{
if (remoteObject_ == nullptr) {
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StopServiceAbility(want);
}
sptr<IAbilityScheduler> AbilityManagerClient::AcquireDataAbility(
const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
{
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
if (remoteObject_ == nullptr) {
return nullptr;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->AcquireDataAbility(uri, tryBind, callerToken);
}
ErrCode AbilityManagerClient::ReleaseDataAbility(
sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
{
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
if (remoteObject_ == nullptr) {
return -1;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ReleaseDataAbility(dataAbilityScheduler, callerToken);
}
ErrCode AbilityManagerClient::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
int32_t missionId, const sptr<IRemoteObject> &callback, AAFwk::WantParams &wantParams)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ContinueMission(srcDeviceId, dstDeviceId, missionId, callback, wantParams);
}
ErrCode AbilityManagerClient::StartContinuation(const Want &want, const sptr<IRemoteObject> &abilityToken,
int32_t status)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StartContinuation(want, abilityToken, status);
}
void AbilityManagerClient::NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess)
{
if (remoteObject_ == nullptr) {
return;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
abms->NotifyCompleteContinuation(deviceId, sessionId, isSuccess);
}
ErrCode AbilityManagerClient::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StartSyncRemoteMissions(devId, fixConflict, tag);
}
ErrCode AbilityManagerClient::StopSyncRemoteMissions(const std::string& devId)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StopSyncRemoteMissions(devId);
}
ErrCode AbilityManagerClient::StartUser(int accountId)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StartUser(accountId);
}
ErrCode AbilityManagerClient::StopUser(int accountId, const sptr<IStopUserCallback> &callback)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StopUser(accountId, callback);
}
} // namespace AAFwk
} // namespace OHOS

View File

@ -0,0 +1,164 @@
/*
* 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 "mock_serviceability_manager_service.h"
#include <gtest/gtest.h>
#include <functional>
#include <memory>
#include <string>
#include <unistd.h>
using OHOS::AppExecFwk::ElementName;
namespace OHOS {
namespace AAFwk {
MockServiceAbilityManagerService::MockServiceAbilityManagerService()
{}
MockServiceAbilityManagerService::~MockServiceAbilityManagerService()
{}
int MockServiceAbilityManagerService::StartAbility(const Want &want, int requestCode)
{
return 0;
}
int MockServiceAbilityManagerService::StartAbility(
const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode)
{
return 0;
}
int MockServiceAbilityManagerService::StartAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
GTEST_LOG_(INFO) << "MockServiceAbilityManagerService::StartAbility";
if (!connect) {
GTEST_LOG_(INFO) << "MockAbilityManagerService::TerminateAbility connect is null";
return -1;
}
return 0;
}
int MockServiceAbilityManagerService::TerminateAbility(
const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
{
return 0;
}
int MockServiceAbilityManagerService::ConnectAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
return -1;
}
int MockServiceAbilityManagerService::DisconnectAbility(const sptr<IAbilityConnection> &connect)
{
return 0;
}
int MockServiceAbilityManagerService::AttachAbilityThread(
const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
{
return 0;
}
void MockServiceAbilityManagerService::DumpState(const std::string &args, std::vector<std::string> &info)
{}
int MockServiceAbilityManagerService::AbilityTransitionDone(
const sptr<IRemoteObject> &token, int state, const PacMap &saveData)
{
return 0;
}
int MockServiceAbilityManagerService::ScheduleConnectAbilityDone(
const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
{
return 0;
}
int MockServiceAbilityManagerService::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
{
return 0;
}
int MockServiceAbilityManagerService::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
{
return 0;
}
void MockServiceAbilityManagerService::AddWindowInfo(const sptr<IRemoteObject> &token, int32_t windowToken)
{}
int MockServiceAbilityManagerService::TerminateAbilityResult(const sptr<IRemoteObject> &token, int startId)
{
return 0;
}
int MockServiceAbilityManagerService::TerminateAbilityByCaller(const sptr<IRemoteObject> &callerToken, int requestCode)
{
return 0;
}
int MockServiceAbilityManagerService::ReleaseAbility(const sptr<IAbilityConnection> &connect,
const AppExecFwk::ElementName &element)
{
GTEST_LOG_(INFO) << "MockServiceAbilityManagerService::ReleaseAbility";
return 0;
}
int MockServiceAbilityManagerService::StopServiceAbility(const Want &want)
{
return 0;
}
int MockServiceAbilityManagerService::RemoveMission(int id)
{
return 0;
}
int MockServiceAbilityManagerService::RemoveStack(int id)
{
return 0;
}
int MockServiceAbilityManagerService::MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst)
{
return 0;
}
bool MockServiceAbilityManagerService::IsFirstInMission(const sptr<IRemoteObject> &token)
{
return true;
}
int MockServiceAbilityManagerService::CompelVerifyPermission(
const std::string &permission, int pid, int uid, std::string &message)
{
return 0;
}
int MockServiceAbilityManagerService::PowerOff()
{
return 0;
}
int MockServiceAbilityManagerService::PowerOn()
{
return 0;
}
} // namespace AAFwk
} // namespace OHOS

View File

@ -0,0 +1,223 @@
/*
* 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 OHOS_AAFWK_SERVICEABILITY_MOCK_MANAGER_SERVICE_H
#define OHOS_AAFWK_SERVICEABILITY_MOCK_MANAGER_SERVICE_H
#include <memory>
#include <singleton.h>
#include <thread_ex.h>
#include <unordered_map>
#include "ability_manager_stub.h"
#include "iremote_object.h"
#include "gmock/gmock.h"
namespace OHOS {
namespace AAFwk {
enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING };
class MockServiceAbilityManagerService : public AbilityManagerStub,
public std::enable_shared_from_this<MockServiceAbilityManagerService> {
public:
MockServiceAbilityManagerService();
~MockServiceAbilityManagerService();
int StartAbility(const Want &want, int requestCode = -1) override;
int StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode = -1) override;
int StartAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken) override;
int TerminateAbility(
const sptr<IRemoteObject> &token, int resultCode = -1, const Want *resultWant = nullptr) override;
int MinimizeAbility(const sptr<IRemoteObject> &token) override
{
return 0;
}
int ConnectAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken) override;
int DisconnectAbility(const sptr<IAbilityConnection> &connect) override;
void AddWindowInfo(const sptr<IRemoteObject> &token, int32_t windowToken) override;
int AttachAbilityThread(const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token) override;
int AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData) override;
int ScheduleConnectAbilityDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject) override;
int ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token) override;
int ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token) override;
void DumpState(const std::string &args, std::vector<std::string> &info) override;
int TerminateAbilityResult(const sptr<IRemoteObject> &token, int startId) override;
int StopServiceAbility(const Want &want) override;
int TerminateAbilityByCaller(const sptr<IRemoteObject> &callerToken, int requestCode) override;
int ReleaseAbility(const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element) override;
MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo));
MOCK_METHOD1(MoveMissionToTop, int(int32_t missionId));
MOCK_METHOD1(KillProcess, int(const std::string &bundleName));
MOCK_METHOD1(UninstallApp, int(const std::string &bundleName));
MOCK_METHOD2(
GetWantSender, sptr<IWantSender>(const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken));
MOCK_METHOD2(SendWantSender, int(const sptr<IWantSender> &target, const SenderInfo &senderInfo));
MOCK_METHOD1(CancelWantSender, void(const sptr<IWantSender> &sender));
MOCK_METHOD1(GetPendingWantUid, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantUserId, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantBundleName, std::string(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantCode, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantType, int(const sptr<IWantSender> &target));
MOCK_METHOD2(RegisterCancelListener, void(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver));
MOCK_METHOD2(UnregisterCancelListener, void(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver));
MOCK_METHOD2(GetPendingRequestWant, int(const sptr<IWantSender> &target, std::shared_ptr<Want> &want));
MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting,
const sptr<IRemoteObject> &callerToken, int requestCode));
MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption));
MOCK_METHOD2(MoveMissionToSplitScreenStack, int(const MissionOption &primary, const MissionOption &secondary));
MOCK_METHOD2(
ChangeFocusAbility, int(const sptr<IRemoteObject> &lostFocusToken, const sptr<IRemoteObject> &getFocusToken));
MOCK_METHOD1(MinimizeMultiWindow, int(int missionId));
MOCK_METHOD1(MaximizeMultiWindow, int(int missionId));
MOCK_METHOD1(GetFloatingMissions, int(std::vector<AbilityMissionInfo> &list));
MOCK_METHOD1(CloseMultiWindow, int(int missionId));
MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting));
MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id));
MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo));
MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr<IRemoteObject> &abilityToken, int32_t status));
MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result));
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_METHOD2(RegisterMissionListener, int(const std::string &deviceId,
const sptr<IRemoteMissionListener> &listener));
MOCK_METHOD2(UnRegisterMissionListener, int(const std::string &deviceId,
const sptr<IRemoteMissionListener> &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));
MOCK_METHOD2(GetWantSenderInfo, int(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info));
int MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst) override;
bool IsFirstInMission(const sptr<IRemoteObject> &token) override;
int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override;
int RemoveMission(int id) override;
int RemoveStack(int id) override;
int PowerOff() override;
int PowerOn() override;
int LockMission(int missionId) override
{
return 0;
}
int UnlockMission(int missionId) override
{
return 0;
}
int SetMissionDescriptionInfo(
const sptr<IRemoteObject> &token, const MissionDescriptionInfo &missionDescriptionInfo) override
{
return 0;
}
int GetMissionLockModeState()
{
return 0;
}
int UpdateConfiguration(const AppExecFwk::Configuration &config)
{
return 0;
}
sptr<IAbilityScheduler> AcquireDataAbility(
const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken) override
{
return nullptr;
}
int ReleaseDataAbility(
sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken) override
{
return 0;
}
int GetRecentMissions(
const int32_t numMax, const int32_t flags, std::vector<AbilityMissionInfo> &recentList) override
{
return 0;
}
int GetMissionSnapshot(const int32_t missionId, MissionPixelMap &missionPixelMap)
{
return 0;
}
virtual int SetShowOnLockScreen(bool isAllow) override
{
return 0;
}
virtual int ClearUpApplicationData(const std::string &bundleName) override
{
return 0;
}
int ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
int32_t missionId, const sptr<IRemoteObject> &callback, AAFwk::WantParams &wantParams)
{
return 0;
}
int ContinueAbility(const std::string &deviceId, int32_t missionId)
{
return 0;
}
void NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess)
{}
int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)
{
return 0;
}
int StopSyncRemoteMissions(const std::string& devId)
{
return 0;
}
int StartUser(int accountId)
{
return 0;
}
int StopUser(int accountId, const sptr<IStopUserCallback> &callback)
{
return 0;
}
sptr<IAbilityScheduler> abilityScheduler_ = nullptr; // kit interface used to schedule ability life
Want want_;
bool startAbility = false;
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_SERVICEABILITY_MOCK_MANAGER_SERVICE_H

View File

@ -0,0 +1,260 @@
/*
* 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 <gtest/gtest.h>
#include "ability_thread.h"
#define private public
#define protected public
#include "ability_context_impl.h"
#include "caller_callback.h"
#undef private
#undef protected
#include "ability_context.h"
#include "ability_loader.h"
#include "ability_manager_client.h"
#include "mock_serviceability_manager_service.h"
#include "system_ability_definition.h"
#include "sys_mgr_client.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS::AppExecFwk;
using namespace OHOS::AbilityRuntime;
using namespace OHOS;
using namespace AAFwk;
namespace {
const std::string ACE_SERVICE_ABILITY_NAME = "AceServiceAbility";
}
class AbilityCallerTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
static constexpr int TEST_WAIT_TIME = 500 * 1000; // 500 ms
public:
std::unique_ptr<AbilityContextImpl> context_ = nullptr;
};
void AbilityCallerTest::SetUpTestCase(void)
{
OHOS::sptr<OHOS::IRemoteObject> abilityObject = new (std::nothrow) MockServiceAbilityManagerService();
auto sysMgr = OHOS::DelayedSingleton<SysMrgClient>::GetInstance();
if (sysMgr == NULL) {
GTEST_LOG_(ERROR) << "fail to get ISystemAbilityManager";
return;
}
sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject);
auto task = []()->Ability* { return new (std::nothrow) Ability; };
AbilityLoader::GetInstance().RegisterAbility(ACE_SERVICE_ABILITY_NAME, task);
}
void AbilityCallerTest::TearDownTestCase(void)
{}
void AbilityCallerTest::SetUp(void)
{
context_ = std::make_unique<AbilityContextImpl>();
}
void AbilityCallerTest::TearDown(void)
{}
/**
* @tc.number: AaFwk_Ability_StartAbility_0100
* @tc.name: AbilityFwk
* @tc.desc: Ability caller to process StartAbility, and the result is success.
*/
HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0100, Function | MediumTest | Level1)
{
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
sptr<IRemoteObject> abilityToken = sptr<IRemoteObject>(new AbilityThread());
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AppExecFwk::AbilityType::SERVICE;
abilityInfo->name = "DemoAbilityNameA";
abilityInfo->bundleName = "DemoBundleNameA";
abilityInfo->deviceId = "DemoDeviceIdA";
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, abilityToken);
AbilityThread::AbilityThreadMain(application, abilityRecord, nullptr);
Want want;
want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB");
std::shared_ptr<CallerCallBack> callback = std::make_shared<CallerCallBack>();
callback->SetCallBack([](const sptr<IRemoteObject> &) {});
EXPECT_FALSE(callback->IsCallBack());
ErrCode ret = context_->StartAbility(want, callback);
EXPECT_TRUE(ret == 0);
AppExecFwk::ElementName element("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB");
sptr<IRemoteObject> callRemoteObject =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
context_->localCallContainer_->OnAbilityConnectDone(element, callRemoteObject, ERR_OK);
EXPECT_TRUE(callback->IsCallBack());
}
/**
* @tc.number: AaFwk_Ability_StartAbility_0200
* @tc.name: AbilityFwk
* @tc.desc: Ability caller to process StartAbility, and the result is fail because call back is nullptr.
*/
HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0200, Function | MediumTest | Level1)
{
Want want;
want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB");
ErrCode ret = context_->StartAbility(want, nullptr);
EXPECT_FALSE(ret == 0);
}
/**
* @tc.number: AaFwk_Ability_StartAbility_0300
* @tc.name: AbilityFwk
* @tc.desc: Ability caller to process StartAbility, and the result is fail because the element of want is empty.
*/
HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0300, Function | MediumTest | Level1)
{
Want want;
std::shared_ptr<CallerCallBack> callback = std::make_shared<CallerCallBack>();
callback->SetCallBack([](const sptr<IRemoteObject> &) {});
EXPECT_FALSE(callback->IsCallBack());
ErrCode ret = context_->StartAbility(want, callback);
EXPECT_FALSE(ret == 0);
}
/**
* @tc.number: AaFwk_Ability_ReleaseAbility_0100
* @tc.name: AbilityFwk
* @tc.desc: Ability Caller to process ReleaseAbility, and the result is success.
*/
HWTEST_F(AbilityCallerTest, AaFwk_Ability_ReleaseAbility_0100, Function | MediumTest | Level1)
{
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
sptr<IRemoteObject> abilityToken = sptr<IRemoteObject>(new AbilityThread());
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AppExecFwk::AbilityType::SERVICE;
abilityInfo->name = "DemoAbilityNameA";
abilityInfo->bundleName = "DemoBundleNameA";
abilityInfo->deviceId = "DemoDeviceIdA";
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, abilityToken);
AbilityThread::AbilityThreadMain(application, abilityRecord, nullptr);
Want want;
want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB");
std::shared_ptr<CallerCallBack> callback = std::make_shared<CallerCallBack>();
callback->SetCallBack([](const sptr<IRemoteObject> &) {});
ErrCode ret = context_->StartAbility(want, callback);
EXPECT_TRUE(ret == 0);
ret = context_->ReleaseAbility(callback);
EXPECT_TRUE(ret == 0);
}
/**
* @tc.number: AaFwk_Ability_ReleaseAbility_0200
* @tc.name: AbilityFwk
* @tc.desc: Ability Caller to process ReleaseAbility, and the result is fail because has no caller record.
*/
HWTEST_F(AbilityCallerTest, AaFwk_Ability_ReleaseAbility_0200, Function | MediumTest | Level1)
{
std::shared_ptr<CallerCallBack> callback = std::make_shared<CallerCallBack>();
callback->SetCallBack([](const sptr<IRemoteObject> &) {});
ErrCode ret = context_->ReleaseAbility(callback);
EXPECT_FALSE(ret == 0);
}
/**
* @tc.number: AaFwk_Ability_OnCallStubDied_0100
* @tc.name: AbilityFwk
* @tc.desc: Ability Caller to process OnCallStubDied, and the result is success.
*/
HWTEST_F(AbilityCallerTest, AaFwk_Ability_OnCallStubDied_0100, Function | MediumTest | Level1)
{
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
sptr<IRemoteObject> abilityToken = sptr<IRemoteObject>(new AbilityThread());
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AppExecFwk::AbilityType::SERVICE;
abilityInfo->name = "DemoAbilityNameA";
abilityInfo->bundleName = "DemoBundleNameA";
abilityInfo->deviceId = "DemoDeviceIdA";
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, abilityToken);
AbilityThread::AbilityThreadMain(application, abilityRecord, nullptr);
Want want;
want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB");
std::shared_ptr<CallerCallBack> callback = std::make_shared<CallerCallBack>();
bool isSetOnReleaseCalled = false;
callback->SetCallBack([](const sptr<IRemoteObject> &) {});
callback->SetOnRelease([&isSetOnReleaseCalled](const std::string &result) mutable {
GTEST_LOG_(ERROR) << "OnRelease-----------" << result;
EXPECT_TRUE(result == "died");
isSetOnReleaseCalled = true;
});
ErrCode ret = context_->StartAbility(want, callback);
EXPECT_TRUE(ret == 0);
std::shared_ptr<LocalCallRecord> localCallRecord;
AppExecFwk::ElementName elementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB");
context_->localCallContainer_->GetCallLocalreocrd(elementName, localCallRecord);
sptr<IRemoteObject> callRemoteObject =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
localCallRecord->OnCallStubDied(callRemoteObject);
EXPECT_TRUE(isSetOnReleaseCalled);
}
/**
* @tc.number: AaFwk_Ability_OnCallStubDied_0200
* @tc.name: AbilityFwk
* @tc.desc: Ability Caller to process OnCallStubDied, and the result is fail because no caller.
*/
HWTEST_F(AbilityCallerTest, AaFwk_Ability_OnCallStubDied_0200, Function | MediumTest | Level1)
{
std::shared_ptr<CallerCallBack> callback = std::make_shared<CallerCallBack>();
bool isSetOnReleaseCalled = false;
callback->SetOnRelease([&isSetOnReleaseCalled](const std::string &result) mutable {
GTEST_LOG_(ERROR) << "OnRelease-----------" << result;
isSetOnReleaseCalled = true;
});
AppExecFwk::ElementName elementName ("DemoDeviceId", "DemoBundleName", "DemoAbilityName");
LocalCallRecord localCallRecord(elementName);
sptr<IRemoteObject> callRemoteObject =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
localCallRecord.OnCallStubDied(callRemoteObject);
EXPECT_FALSE(isSetOnReleaseCalled);
}
} // namespace AppExecFwk
} // namespace OHOS

View File

@ -213,6 +213,7 @@ ohos_shared_library("abilitykit_native") {
#"//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb/napi_rdb_predicates.cpp",
"${SUBSYSTEM_DIR}/src/ability_runtime/js_ability.cpp",
"${SUBSYSTEM_DIR}/src/ability_runtime/js_ability_context.cpp",
"${SUBSYSTEM_DIR}/src/ability_runtime/js_caller_complex.cpp",
"${SUBSYSTEM_DIR}/src/ability_runtime/js_window_stage.cpp",
"//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_dataability/napi_data_ability_predicates.cpp",
"//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb/napi_result_set.cpp",

View File

@ -1385,6 +1385,12 @@ public:
* @return None.
*/
void SetSceneListener(const sptr<Rosen::IWindowLifeCycle> &listener);
/**
* @brief request a remote object of callee from this ability.
* @return Returns the remote object of callee.
*/
virtual sptr<IRemoteObject> CallRequest();
protected:
/**

View File

@ -699,19 +699,8 @@ public:
void SetShowOnLockScreen(bool isAllow) override;
friend DataAbilityHelper;
public:
static int ABILITY_CONTEXT_DEFAULT_REQUEST_CODE;
private:
/**
* @brief Get Current Ability Type
*
* @return Current Ability Type
*/
AppExecFwk::AbilityType GetAbilityInfoType();
void GetPermissionDes(const std::string &permissionName, std::string &des);
protected:
sptr<IRemoteObject> GetToken() override;
sptr<IRemoteObject> token_;
@ -721,8 +710,16 @@ protected:
std::string callingBundleName_;
std::string callingAbilityName_;
std::map<sptr<AAFwk::IAbilityConnection>, sptr<IRemoteObject>> abilityConnectionMap_;
};
private:
/**
* @brief Get Current Ability Type
*
* @return Current Ability Type
*/
AppExecFwk::AbilityType GetAbilityInfoType();
void GetPermissionDes(const std::string &permissionName, std::string &des);
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_CONTEXT_H

View File

@ -58,6 +58,8 @@ public:
void OnRequestPermissionsFromUserResult(
int requestCode, const std::vector<std::string> &permissions, const std::vector<int> &grantResults) override;
sptr<IRemoteObject> CallRequest() override;
protected:
void DoOnForeground(const Want &want) override;

View File

@ -39,6 +39,7 @@ public:
static void Finalizer(NativeEngine* engine, void* data, void* hint);
static NativeValue* StartAbility(NativeEngine* engine, NativeCallbackInfo* info);
static NativeValue* StartAbilityByCall(NativeEngine* engine, NativeCallbackInfo* info);
static NativeValue* StartAbilityForResult(NativeEngine* engine, NativeCallbackInfo* info);
static NativeValue* ConnectAbility(NativeEngine* engine, NativeCallbackInfo* info);
static NativeValue* DisconnectAbility(NativeEngine* engine, NativeCallbackInfo* info);
@ -55,6 +56,7 @@ public:
private:
NativeValue* OnStartAbility(NativeEngine& engine, NativeCallbackInfo& info);
NativeValue* OnStartAbilityByCall(NativeEngine& engine, NativeCallbackInfo& info);
NativeValue* OnStartAbilityForResult(NativeEngine& engine, NativeCallbackInfo& info);
NativeValue* OnTerminateSelfWithResult(NativeEngine& engine, NativeCallbackInfo& info);
NativeValue* OnConnectAbility(NativeEngine& engine, NativeCallbackInfo& info);

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.
*/
#ifndef ABILITY_RUNTIME_JS_CALLERCOMPLEX_H
#define ABILITY_RUNTIME_JS_CALLERCOMPLEX_H
#include <memory>
#include <native_engine/native_value.h>
#include "iremote_object.h"
#include "foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/include/ability_context.h"
namespace OHOS {
namespace AbilityRuntime {
NativeValue* CreateJsCallerComplex(
NativeEngine& engine, std::shared_ptr<AbilityContext> context, sptr<IRemoteObject> callee,
std::shared_ptr<CallerCallBack> callerCallBack);
NativeValue* CreateJsCalleeRemoteObject(NativeEngine& engine, sptr<IRemoteObject> callee);
} // AbilityRuntime
} // OHOS
#endif // ABILITY_RUNTIME_JS_CALLERCOMPLEX_H

View File

@ -395,7 +395,10 @@ public:
*/
bool CheckObsPermission();
std::vector<std::shared_ptr<DataAbilityResult>> ExecuteBatch(const std::vector<std::shared_ptr<DataAbilityOperation>> &operations);
sptr<IRemoteObject> CallRequest();
std::vector<std::shared_ptr<DataAbilityResult>> ExecuteBatch(
const std::vector<std::shared_ptr<DataAbilityOperation>> &operations);
private:
/**
* @description: Create the abilityname.

View File

@ -3254,5 +3254,14 @@ void Ability::DoOnForeground(const Want& want)
}
}
/**
* @brief request a remote object of callee from this ability.
* @return Returns the remote object of callee.
*/
sptr<IRemoteObject> Ability::CallRequest()
{
return nullptr;
}
} // namespace AppExecFwk
} // namespace OHOS

View File

@ -13,6 +13,8 @@
* limitations under the License.
*/
#include <regex>
#include "system_ability_definition.h"
#include "if_system_ability_manager.h"
#include "ability_runtime/js_ability.h"
#include "ability_runtime/js_ability_context.h"
@ -286,6 +288,50 @@ void JsAbility::OnAbilityResult(int requestCode, int resultCode, const Want &res
HILOG_INFO("%{public}s end.", __func__);
}
sptr<IRemoteObject> JsAbility::CallRequest()
{
HILOG_INFO("JsAbility::CallRequest begin.");
if (jsAbilityObj_ == nullptr) {
HILOG_WARN("JsAbility::CallRequest Obj is nullptr");
return nullptr;
}
HandleScope handleScope(jsRuntime_);
HILOG_DEBUG("JsAbility::CallRequest set runtime scope.");
auto& nativeEngine = jsRuntime_.GetNativeEngine();
auto value = jsAbilityObj_->Get();
if (value == nullptr) {
HILOG_ERROR("JsAbility::CallRequest value is nullptr");
return nullptr;
}
NativeObject* obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
HILOG_ERROR("JsAbility::CallRequest obj is nullptr");
return nullptr;
}
auto method = obj->GetProperty("onCallRequest");
if (method == nullptr || !method->IsCallable()) {
HILOG_ERROR("JsAbility::CallRequest method is %{public}s", method == nullptr ? "nullptr" : "not func");
return nullptr;
}
auto remoteJsObj = nativeEngine.CallFunction(value, method, nullptr, 0);
if (remoteJsObj == nullptr) {
HILOG_ERROR("JsAbility::CallRequest JsObj is nullptr");
return nullptr;
}
auto remoteObj = NAPI_ohos_rpc_getNativeRemoteObject(
reinterpret_cast<napi_env>(&nativeEngine), reinterpret_cast<napi_value>(remoteJsObj));
if (remoteObj == nullptr) {
HILOG_ERROR("JsAbility::CallRequest obj is nullptr");
}
HILOG_INFO("JsAbility::CallRequest end.");
return remoteObj;
}
void JsAbility::OnRequestPermissionsFromUserResult(
int requestCode, const std::vector<std::string> &permissions, const std::vector<int> &grantResults)
{

View File

@ -23,12 +23,14 @@
#include "js_data_struct_converter.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "ability_runtime/js_caller_complex.h"
#include "napi_common_start_options.h"
#include "napi_common_util.h"
#include "napi_common_want.h"
#include "napi_remote_object.h"
#include "start_options.h"
#include "want.h"
#include "event_handler.h"
namespace OHOS {
namespace AbilityRuntime {
@ -50,6 +52,12 @@ NativeValue* JsAbilityContext::StartAbility(NativeEngine* engine, NativeCallback
return (me != nullptr) ? me->OnStartAbility(*engine, *info) : nullptr;
}
NativeValue* JsAbilityContext::StartAbilityByCall(NativeEngine* engine, NativeCallbackInfo* info)
{
JsAbilityContext* me = CheckParamsAndGetThis<JsAbilityContext>(engine, info);
return (me != nullptr) ? me->OnStartAbilityByCall(*engine, *info) : nullptr;
}
NativeValue* JsAbilityContext::StartAbilityForResult(NativeEngine* engine, NativeCallbackInfo* info)
{
JsAbilityContext* me = CheckParamsAndGetThis<JsAbilityContext>(engine, info);
@ -143,6 +151,58 @@ NativeValue* JsAbilityContext::OnStartAbility(NativeEngine& engine, NativeCallba
return result;
}
NativeValue* JsAbilityContext::OnStartAbilityByCall(NativeEngine& engine, NativeCallbackInfo& info)
{
int errCode = 0;
sptr<IRemoteObject> remoteCallee;
if (info.argc != ARGC_ONE || info.argv[0]->TypeOf() != NATIVE_OBJECT) {
HILOG_ERROR("int put params count error");
return engine.CreateUndefined();
}
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[0]), want);
NativeValue* callerComplex = nullptr;
std::mutex mutexlock;
std::condition_variable condition;
auto callBackDone = [&mutexlock, &condition, &remoteCallee](const sptr<IRemoteObject> &obj) {
std::unique_lock<std::mutex> lock(mutexlock);
remoteCallee = obj;
condition.notify_all();
HILOG_INFO("OnStartAbilityByCall callBackDone is called");
};
auto releaseListen = [](const std::string &str) {
HILOG_INFO("OnStartAbilityByCall releaseListen is called %{public}s", str.c_str());
};
auto context = context_.lock();
constexpr int CALLER_TIME_OUT = 5; // 5s
if (!context) {
HILOG_ERROR("context is released");
errCode = -1;
return engine.CreateUndefined();
}
std::shared_ptr<CallerCallBack> callerCallBack = std::make_shared<CallerCallBack>();
callerCallBack->SetCallBack(callBackDone);
callerCallBack->SetOnRelease(releaseListen);
HILOG_INFO("OnStartAbilityByCall execute is StartAbility");
errCode = context->StartAbility(want, callerCallBack);
if (remoteCallee == nullptr) {
HILOG_INFO("OnStartAbilityByCall lock mutexlock Done");
std::unique_lock<std::mutex> lock(mutexlock);
HILOG_INFO("OnStartAbilityByCall lock waiting callBackDone");
if (condition.wait_for(lock, std::chrono::seconds(CALLER_TIME_OUT)) == std::cv_status::timeout) {
remoteCallee = nullptr;
errCode = -1;
HILOG_ERROR("Waiting callee timeout");
return engine.CreateUndefined();
}
} else {
HILOG_INFO("OnStartAbilityByCall remoteCallee isn~t nullptr");
}
callerComplex = CreateJsCallerComplex(engine, context, remoteCallee, callerCallBack);
return callerComplex;
}
NativeValue* JsAbilityContext::OnStartAbilityForResult(NativeEngine& engine, NativeCallbackInfo& info)
{
HILOG_INFO("OnStartAbilityForResult is called");
@ -564,6 +624,7 @@ NativeValue* CreateJsAbilityContext(NativeEngine& engine, std::shared_ptr<Abilit
}
BindNativeFunction(engine, *object, "startAbility", JsAbilityContext::StartAbility);
BindNativeFunction(engine, *object, "startAbilityByCall", JsAbilityContext::StartAbilityByCall);
BindNativeFunction(engine, *object, "startAbilityForResult", JsAbilityContext::StartAbilityForResult);
BindNativeFunction(engine, *object, "connectAbility", JsAbilityContext::ConnectAbility);
BindNativeFunction(engine, *object, "disconnectAbility", JsAbilityContext::DisconnectAbility);

View File

@ -0,0 +1,274 @@
/*
* 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 <string>
#include <set>
#include "hilog_wrapper.h"
#include "js_context_utils.h"
#include "js_data_struct_converter.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi_common_want.h"
#include "napi_remote_object.h"
#include "ability_runtime/js_caller_complex.h"
namespace OHOS {
namespace AbilityRuntime {
namespace { // nameless
static std::map<NativeValueType, std::string> logcast = {
{ NATIVE_UNDEFINED, std::string("NATIVE_UNDEFINED") },
{ NATIVE_NULL, std::string("NATIVE_NULL") },
{ NATIVE_BOOLEAN, std::string("NATIVE_BOOLEAN") },
{ NATIVE_NUMBER, std::string("NATIVE_NUMBER") },
{ NATIVE_STRING, std::string("NATIVE_STRING") },
{ NATIVE_SYMBOL, std::string("NATIVE_SYMBOL") },
{ NATIVE_OBJECT, std::string("NATIVE_OBJECT") },
{ NATIVE_FUNCTION, std::string("NATIVE_FUNCTION") },
{ NATIVE_EXTERNAL, std::string("NATIVE_EXTERNAL") },
{ NATIVE_BIGINT, std::string("NATIVE_BIGINT") },
};
class JsCallerComplex {
public:
explicit JsCallerComplex(
NativeEngine& engine, std::shared_ptr<AbilityContext> context, sptr<IRemoteObject> callee,
std::shared_ptr<CallerCallBack> callerCallBack) : context_(context), callee_(callee),
releaseCallBackEngine_(engine), callerCallBackObj_(callerCallBack), jsreleaseCallBackObj_(nullptr)
{
handler_ = std::make_shared<AppExecFwk::EventHandler>(AppExecFwk::EventRunner::GetMainEventRunner());
};
virtual~JsCallerComplex() {};
static void Finalizer(NativeEngine* engine, void* data, void* hint)
{
if (data == nullptr) {
HILOG_ERROR("JsCallerComplex::%{public}s is called, but input parameters is nullptr", __func__);
return;
}
std::unique_ptr<JsCallerComplex>(static_cast<JsCallerComplex*>(data));
}
static NativeValue* JsRelease(NativeEngine* engine, NativeCallbackInfo* info)
{
if (engine == nullptr || info == nullptr) {
HILOG_ERROR("JsCallerComplex::%{public}s is called, but input parameters %{public}s is nullptr",
__func__,
((engine == nullptr) ? "engine" : "info"));
return nullptr;
}
auto object = CheckParamsAndGetThis<JsCallerComplex>(engine, info);
if (object == nullptr) {
HILOG_ERROR("JsCallerComplex::%{public}s is called, CheckParamsAndGetThis return nullptr", __func__);
return nullptr;
}
return object->ReleaseInner(*engine, *info);
}
static NativeValue* JsSetOnReleaseCallBack(NativeEngine* engine, NativeCallbackInfo* info)
{
if (engine == nullptr || info == nullptr) {
HILOG_ERROR("JsCallerComplex::%{public}s is called, but input parameters %{public}s is nullptr",
__func__,
((engine == nullptr) ? "engine" : "info"));
return nullptr;
}
auto object = CheckParamsAndGetThis<JsCallerComplex>(engine, info);
if (object == nullptr) {
HILOG_ERROR("JsCallerComplex::%{public}s is called, CheckParamsAndGetThis return nullptr", __func__);
return nullptr;
}
return object->SetOnReleaseCallBackInner(*engine, *info);
}
sptr<IRemoteObject> GetRemoteObject()
{
return callee_;
}
private:
void OnReleaseNotify(const std::string &str)
{
HILOG_DEBUG("OnReleaseNotify begin");
if (handler_ == nullptr) {
HILOG_ERROR("");
return;
}
auto task = [notify = this, &str] () { notify->OnReleaseNotifyTask(str); };
handler_->PostTask(task, "OnReleaseNotify");
HILOG_DEBUG("OnReleaseNotify end");
}
void OnReleaseNotifyTask(const std::string &str)
{
HILOG_DEBUG("OnReleaseNotifyTask begin");
if (jsreleaseCallBackObj_ == nullptr) {
HILOG_ERROR("JsCallerComplex::%{public}s, jsreleaseObj is nullptr", __func__);
return;
}
NativeValue* value = jsreleaseCallBackObj_->Get();
NativeValue* callback = jsreleaseCallBackObj_->Get();
NativeValue* args[] = { CreateJsValue(releaseCallBackEngine_, str) };
releaseCallBackEngine_.CallFunction(value, callback, args, 1);
HILOG_DEBUG("OnReleaseNotifyTask end");
}
NativeValue* ReleaseInner(NativeEngine& engine, NativeCallbackInfo& info)
{
HILOG_DEBUG("JsCallerComplex::%{public}s, called", __func__);
constexpr size_t ARGC_ZERO = 0;
constexpr size_t ARGC_ONE = 1;
int errCode = 0;
AsyncTask::ExecuteCallback execute =
[weak = context_, callback = callerCallBackObj_, &errCode] (NativeEngine& engine, AsyncTask& task) {
auto context = weak.lock();
if (context == nullptr) {
HILOG_ERROR("JsCallerComplex::%{public}s, context is nullptr", "ReleaseInner::ExecuteCallback");
errCode = -1;
return;
}
errCode = context->ReleaseAbility(callback);
HILOG_DEBUG("JsCallerComplex::%{public}s %{public}d, end", "ReleaseInner::ExecuteCallback", errCode);
};
AsyncTask::CompleteCallback complete =
[errCode] (NativeEngine& engine, AsyncTask& task, int32_t status) {
if (errCode == 0) {
task.Resolve(engine, engine.CreateUndefined());
} else {
task.Reject(engine, CreateJsError(engine, errCode, "CallerComplex Release Failed."));
}
HILOG_DEBUG("JsCallerComplex::%{public}s, end", "ReleaseInner::CompleteCallback");
};
NativeValue* lastParam = ((info.argc == ARGC_ONE) ? info.argv[ARGC_ZERO] : nullptr);
NativeValue* retsult = nullptr;
AsyncTask::Schedule(
engine,
CreateAsyncTaskWithLastParam(engine, lastParam, std::move(execute), std::move(complete), &retsult));
return retsult;
}
NativeValue* SetOnReleaseCallBackInner(NativeEngine& engine, NativeCallbackInfo& info)
{
HILOG_DEBUG("JsCallerComplex::%{public}s, begin", __func__);
constexpr size_t ARGC_ONE = 1;
constexpr size_t ARGC_TWO = 2;
bool errCode = true;
if (info.argc >= ARGC_TWO) {
HILOG_ERROR("JsCallerComplex::%{public}s, Invalid input params", __func__);
return engine.CreateUndefined();
}
if (!info.argv[0]->IsCallable()) {
HILOG_ERROR("JsCallerComplex::%{public}s, IsCallable is %{public}s.",
__func__, ((info.argv[0]->IsCallable()) ? "true" : "false"));
return engine.CreateUndefined();
}
while (errCode) {
if (callerCallBackObj_ == nullptr) {
HILOG_ERROR("JsCallerComplex::%{public}s, param1 is nullptr", __func__);
errCode = false;
break;
}
auto param1 = info.argv[0];
if (param1 == nullptr) {
HILOG_ERROR("JsCallerComplex::%{public}s, param1 is nullptr", __func__);
errCode = false;
break;
}
jsreleaseCallBackObj_ =
std::unique_ptr<NativeReference>(releaseCallBackEngine_.CreateReference(param1, 1));
auto task = [notify = this] (const std::string &str) { notify->OnReleaseNotify(str); };
callerCallBackObj_->SetOnRelease(task);
break;
}
AsyncTask::CompleteCallback complete =
[errCode] (NativeEngine& engine, AsyncTask& task, int32_t status) {
if (errCode) {
task.Resolve(engine, engine.CreateUndefined());
} else {
task.Reject(engine, CreateJsError(engine, -1, "CallerComplex On Release CallBack Failed."));
}
HILOG_DEBUG("JsCallerComplex::%{public}s, %{public}s end", "ReleaseInner::CompleteCallback",
(errCode ? "true" : "false"));
};
NativeValue* lastParam = ((info.argc == ARGC_TWO) ? info.argv[ARGC_ONE] : nullptr);
NativeValue* retsult = nullptr;
AsyncTask::Schedule(engine,
CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &retsult));
HILOG_DEBUG("JsCallerComplex::%{public}s, end", __func__);
return retsult;
}
private:
std::weak_ptr<AbilityContext> context_;
sptr<IRemoteObject> callee_;
NativeEngine& releaseCallBackEngine_;
std::shared_ptr<CallerCallBack> callerCallBackObj_;
std::unique_ptr<NativeReference> jsreleaseCallBackObj_;
std::shared_ptr<AppExecFwk::EventHandler> handler_;
};
} // nameless
NativeValue* CreateJsCallerComplex(
NativeEngine& engine, std::shared_ptr<AbilityContext> context, sptr<IRemoteObject> callee,
std::shared_ptr<CallerCallBack> callerCallBack)
{
HILOG_DEBUG("JsCallerComplex::%{public}s, begin", __func__);
NativeValue* objValue = engine.CreateObject();
NativeObject* object = ConvertNativeValueTo<NativeObject>(objValue);
auto jsCaller = std::make_unique<JsCallerComplex>(engine, context, callee, callerCallBack);
if (jsCaller == nullptr) {
HILOG_ERROR("%{public}s is called, but make_unique<JsCallerComplex> is nullptr", __func__);
return engine.CreateUndefined();
}
auto remoteObj = jsCaller->GetRemoteObject();
if (remoteObj == nullptr) {
HILOG_ERROR("%{public}s is called,remoteObj is nullptr", __func__);
return engine.CreateUndefined();
}
object->SetNativePointer(jsCaller.release(), JsCallerComplex::Finalizer, nullptr);
object->SetProperty("callee", CreateJsCalleeRemoteObject(engine, remoteObj));
BindNativeFunction(engine, *object, "release", JsCallerComplex::JsRelease);
BindNativeFunction(engine, *object, "onRelease", JsCallerComplex::JsSetOnReleaseCallBack);
HILOG_DEBUG("JsCallerComplex::%{public}s, end", __func__);
return objValue;
}
NativeValue* CreateJsCalleeRemoteObject(NativeEngine& engine, sptr<IRemoteObject> callee)
{
napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject(
reinterpret_cast<napi_env>(&engine), callee);
NativeValue* nativeRemoteObject = reinterpret_cast<NativeValue*>(napiRemoteObject);
if (nativeRemoteObject == nullptr) {
HILOG_ERROR("%{public}s is called, but remoteObj is nullptr", __func__);
}
return nativeRemoteObject;
}
} // AbilityRuntime
} // OHOS

View File

@ -1548,5 +1548,17 @@ std::shared_ptr<AbilityRuntime::AbilityContext> AbilityThread::BuildAbilityConte
abilityContextImpl->SetAbilityInfo(abilityInfo);
return abilityContextImpl;
}
sptr<IRemoteObject> AbilityThread::CallRequest()
{
APP_LOGI("AbilityThread::CallRequest start");
if (!currentAbility_) {
APP_LOGI("ability is nullptr.");
return nullptr;
}
return currentAbility_->CallRequest();
}
} // namespace AppExecFwk
} // namespace OHOS

View File

@ -127,6 +127,10 @@ public:
};
virtual void NotifyContinuationResult(const int32_t result) {};
virtual void ContinueAbility(const std::string& deviceId) {};
virtual sptr<IRemoteObject> CallRequest()
{
return sptr<IRemoteObject>(nullptr);
};
};
} // namespace AppExecFwk
} // namespace OHOS

View File

@ -141,6 +141,7 @@ public:
MOCK_METHOD1(GetProcessRunningInfos, int(std::vector<AppExecFwk::RunningProcessInfo> &info));
MOCK_METHOD2(GetWantSenderInfo, int(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info));
MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr<IAbilityConnection> &, const sptr<IRemoteObject> &));
int RemoveMission(int id) override;
@ -248,6 +249,18 @@ public:
return true;
}
virtual int StartAbility(const Want &want, const StartOptions &startOptions,
const sptr<IRemoteObject> &callerToken, int requestCode) override
{
return 0;
}
virtual int ReleaseAbility(
const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element) override
{
return 0;
}
enum RequestCode {
E_STATE_INITIAL = 0,
E_STATE_INACTIVE,

View File

@ -60,6 +60,11 @@ public:
MOCK_METHOD1(ExecuteBatch, std::vector<std::shared_ptr<AppExecFwk::DataAbilityResult>>(const std::vector<std::shared_ptr<AppExecFwk::DataAbilityOperation>> &operation));
MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result));
MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId));
virtual sptr<IRemoteObject> CallRequest()
{
return sptr<IRemoteObject>(nullptr);
};
};
} // namespace AppExecFwk

View File

@ -54,7 +54,7 @@ void AbilityContextTest::SetUpTestCase(void)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_SetUpTestCase start";
OHOS::sptr<OHOS::IRemoteObject> bundleObject = new (std::nothrow) BundleMgrService();
OHOS::sptr<OHOS::IRemoteObject> abilityObject = new (std::nothrow) OHOS::AAFwk::MockAbilityManagerService();
OHOS::sptr<OHOS::IRemoteObject> abilityObject = new (std::nothrow) AAFwk::MockAbilityManagerService();
GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_SetUpTestCase bundleObject->" << bundleObject.GetRefPtr();
GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_SetUpTestCase abilityObject->" << abilityObject.GetRefPtr();

View File

@ -119,6 +119,7 @@ public:
MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector<AbilityRunningInfo> &info));
MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector<ExtensionRunningInfo> &info));
MOCK_METHOD1(GetProcessRunningInfos, int(std::vector<AppExecFwk::RunningProcessInfo> &info));
MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr<IAbilityConnection> &, const sptr<IRemoteObject> &));
int MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst) override;
bool IsFirstInMission(const sptr<IRemoteObject> &token) override;
@ -191,6 +192,17 @@ public:
{
return 0;
}
virtual int StartAbility(const Want &want, const StartOptions &startOptions,
const sptr<IRemoteObject> &callerToken, int requestCode) override
{
return 0;
}
virtual int ReleaseAbility(const sptr<IAbilityConnection> &connect,
const AppExecFwk::ElementName &element) override
{
return 0;
}
virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot)
{
return 0;

View File

@ -115,6 +115,7 @@ public:
MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector<AbilityRunningInfo> &info));
MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector<ExtensionRunningInfo> &info));
MOCK_METHOD1(GetProcessRunningInfos, int(std::vector<AppExecFwk::RunningProcessInfo> &info));
MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr<IAbilityConnection> &, const sptr<IRemoteObject> &));
int MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst) override;
bool IsFirstInMission(const sptr<IRemoteObject> &token) override;
@ -207,6 +208,17 @@ public:
{
return 0;
}
virtual int StartAbility(const Want &want, const StartOptions &startOptions,
const sptr<IRemoteObject> &callerToken, int requestCode) override
{
return 0;
}
virtual int ReleaseAbility(const sptr<IAbilityConnection> &connect,
const AppExecFwk::ElementName &element) override
{
return 0;
}
virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot)
{
return 0;

View File

@ -597,6 +597,24 @@ public:
* @return Returns ERR_OK on success, others on failure.
*/
ErrCode MoveMissionToFront(int32_t missionId);
/**
* Start Ability, connect session with common ability.
*
* @param want, Special want for service type's ability.
* @param connect, Callback used to notify caller the result of connecting or disconnecting.
* @return Returns ERR_OK on success, others on failure.
*/
ErrCode StartAbilityByCall(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callToken);
/**
* Release Ability, disconnect session with common ability.
*
* @param connect, Callback used to notify caller the result of connecting or disconnecting.
* @return Returns ERR_OK on success, others on failure.
*/
ErrCode ReleaseAbility(const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element);
ErrCode GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info);

View File

@ -329,6 +329,32 @@ enum {
* Result(2097217) for clear the application data fail.
*/
CLEAR_APPLICATION_DATA_FAIL,
// for call ability
/**
* Result(2097218) for resolve ability failed, there is no permissions
*/
RESOLVE_CALL_NO_PERMISSIONS,
/**
* Result(2097219) for resolve ability failed, target ability not page or singleton
*/
RESOLVE_CALL_ABILITY_TYPE_ERR,
/**
* Result(2097220) for resolve ability failed, resolve failed.
*/
RESOLVE_CALL_ABILITY_INNER_ERR,
/**
* Result(2097221) for resolve ability failed, resolve failed.
*/
RESOLVE_CALL_ABILITY_VERSION_ERR,
/**
* Result(2097222) for release ability failed, release failed.
*/
RELEASE_CALL_ABILITY_INNER_ERR,
/**
* Result(2097216) for register remote mission listener fail.

View File

@ -544,6 +544,24 @@ public:
virtual int CleanAllMissions() = 0;
virtual int MoveMissionToFront(int32_t missionId) = 0;
/**
* Start Ability, connect session with common ability.
*
* @param want, Special want for service type's ability.
* @param connect, Callback used to notify caller the result of connecting or disconnecting.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int StartAbilityByCall(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken) = 0;
/**
* Release Ability, disconnect session with common ability.
*
* @param connect, Callback used to notify caller the result of connecting or disconnecting.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int ReleaseAbility(const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element) = 0;
virtual int StartUser(int userId) = 0;
@ -832,6 +850,11 @@ public:
START_CONTINUATION = 1101,
NOTIFY_CONTINUATION_RESULT = 1102,
// ipc id for call ability
START_CALL_ABILITY,
RELEASE_CALL_ABILITY,
NOTIFY_COMPLETE_CONTINUATION = 1103,

View File

@ -274,6 +274,9 @@ public:
const std::vector<std::shared_ptr<AppExecFwk::DataAbilityOperation>> &operations) = 0;
virtual void ContinueAbility(const std::string& deviceId) = 0;
virtual void NotifyContinuationResult(const int32_t result) = 0;
virtual sptr<IRemoteObject> CallRequest() = 0;
enum {
// ipc id for scheduling ability to a state of life cycle
SCHEDULE_ABILITY_TRANSACTION = 0,
@ -354,6 +357,9 @@ public:
// ipc id for notify continuation result
NOTIFY_CONTINUATION_RESULT,
// ipc id for scheduling call request
REQUEST_CALL_REMOTE,
// ipc id for continue ability
CONTINUE_ABILITY,

View File

@ -24,6 +24,8 @@ group("napi_packages") {
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/appMgr:napi_app_mgr",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/app_manager:appmanager_napi",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/context:context_napi",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/callee:callee_napi",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/caller:caller_napi",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils:datauriutils",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/extensioncontext:extensioncontext_napi",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility:featureability",

View File

@ -12,9 +12,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Callee = requireNapi("application.Callee")
class Ability {
constructor() {}
constructor() {
this.callee = new Callee("rpc.application.callee");
console.log("Ability::constructor callee is " + typeof this.callee + " " + this.callee);
}
onCreate(want) {}
onDestroy() {}
onWindowStageCreate(windowStage) {}
@ -22,8 +26,12 @@ class Ability {
onForeground(want) {}
onBackground() {}
onWindowStageRestore(windowStage) {}
onCallRequest() {
console.log("Ability::onCallRequest callee is " + typeof this.callee + " " + this.callee);
return this.callee;
}
onContinue(wantParams) {}
onNewWant(want) {}
}
export default Ability
export default Ability

View File

@ -14,6 +14,7 @@
*/
var Context = requireNapi("application.Context")
var Caller = requireNapi("application.Caller")
class AbilityContext extends Context {
constructor(obj) {
@ -26,6 +27,22 @@ class AbilityContext extends Context {
return this.__context_impl__.startAbility(want, options, callback)
}
startAbilityByCall(want) {
if (typeof want !== 'object' || want == null) {
console.log("AbilityContext::startAbilityByCall input param error");
return null;
}
let callee = this.__context_impl__.startAbilityByCall(want);
if (typeof callee === 'object' && callee != null) {
console.log("AbilityContext::startAbilityByCall");
return new Caller(callee);
} else {
console.log("AbilityContext::startAbilityByCall Obtain remoteObject falied");
return null;
}
}
startAbilityForResult(want, callback) {
return this.__context_impl__.startAbilityForResult(want, callback)
}
@ -55,4 +72,4 @@ class AbilityContext extends Context {
}
}
export default AbilityContext
export default AbilityContext

View File

@ -0,0 +1,49 @@
# 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("//ark/ts2abc/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_callee_abc") {
src_js = rebase_path("callee.js")
dst_file = rebase_path(target_out_dir + "/callee.abc")
in_puts = [ "callee.js" ]
out_puts = [ target_out_dir + "/callee.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("callee_js") {
input = "callee.js"
output = target_out_dir + "/callee.o"
}
gen_js_obj("callee_abc") {
input = get_label_info(":gen_callee_abc", "target_out_dir") + "/callee.abc"
output = target_out_dir + "/callee_abc.o"
dep = ":gen_callee_abc"
}
ohos_shared_library("callee_napi") {
sources = [ "callee_module.cpp" ]
deps = [
":callee_abc",
":callee_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module/application"
subsystem_name = "aafwk"
part_name = "ability_runtime"
}

View File

@ -0,0 +1,128 @@
/*
* 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.
*/
var rpc = requireNapi("rpc")
const EVENT_CALL_NOTIFY = 1;
const REQUEST_SUCCESS = 0;
const REQUEST_FAILED = 1;
class Callee extends rpc.RemoteObject {
constructor(des) {
if (typeof des === 'string') {
super(des);
this.callList = new Map();
console.log("Callee constructor is OK " + typeof des);
} else {
console.log("Callee constructor error, des is " + typeof des);
return null;
}
}
onRemoteRequest(code, data, reply, option) {
console.log("Callee onRemoteRequest code [" + typeof code + " " + code + "]");
if (typeof code !== 'number' || typeof data !== 'object' ||
typeof reply !== 'object' || typeof option !== 'object') {
console.log("Callee onRemoteRequest error, code is [" +
typeof code + "], data is [" + typeof data + "], reply is [" +
typeof reply + "], option is [" + typeof option + "]");
return false;
}
console.log("Callee onRemoteRequest code proc");
if (code == EVENT_CALL_NOTIFY) {
if (this.callList == null) {
console.log("Callee onRemoteRequest error, this.callList is nullptr");
return false;
}
let method = data.readString();
console.log("Callee onRemoteRequest method [" + method + "]");
let msgData;
let func = this.callList.get(method);
if (typeof func !== 'function') {
console.log("Callee onRemoteRequest error, get func is " + typeof func);
return false;
}
// data.readSequenceable(msgData);
let result = func(data);
if (typeof result === 'object' && result != null) {
reply.writeInt(REQUEST_SUCCESS);
reply.writeString(typeof result);
reply.writeSequenceable(result);
console.log("Callee onRemoteRequest code proc Packed data");
} else {
reply.writeInt(REQUEST_FAILED);
reply.writeString(typeof result);
console.log("Callee onRemoteRequest error, retval is " + REQUEST_FAILED + ", type is " + typeof result);
}
} else {
console.log("Callee onRemoteRequest error, code is " + code);
return false;
}
console.log("Callee onRemoteRequest code proc success");
return true;
}
on(method, callback) {
if (typeof method !== 'string' || method == "" || typeof callback !== 'function') {
console.log("Callee on error, method is [" + typeof method + "], typeof callback [" + typeof callback + "]");
throw new Error("function input parameter error");
return;
}
if (this.callList == null) {
console.log("Callee on error, this.callList is nullptr");
throw new Error("Function inner container error");
return;
}
if (this.callList.has(method)) {
console.log("Callee on error, this.callList not found " + method);
throw new Error("function is registered");
return;
}
this.callList.set(method, callback);
console.log("Callee on method [" + method + "]");
}
off(method) {
if (typeof method !== 'string' || method == "") {
console.log("Callee off error, method is [" + typeof method + "]");
throw new Error("function input parameter error");
return;
}
if (this.callList == null) {
console.log("Callee off error, this.callList is null");
throw new Error("Function inner container error");
return;
}
if (!this.callList.has(method)) {
console.log("Callee off error, this.callList not found " + method);
throw new Error("function not registered");
return;
}
this.callList.delete(method);
console.log("Callee off method [" + method + "]");
}
}
export default Callee

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 "native_engine/native_engine.h"
extern const char _binary_callee_js_start[];
extern const char _binary_callee_js_end[];
extern const char _binary_callee_abc_start[];
extern const char _binary_callee_abc_end[];
extern "C" __attribute__((constructor))
void NAPI_application_Callee_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "application.Callee",
.fileName = "application/libcallee_napi.so/callee.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default")))
void NAPI_application_Callee_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_callee_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_callee_js_end - _binary_callee_js_start;
}
}
// callee JS register
extern "C" __attribute__((visibility("default")))
void NAPI_application_Callee_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_callee_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_callee_abc_end - _binary_callee_abc_start;
}
}

View File

@ -0,0 +1,49 @@
# 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("//ark/ts2abc/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_caller_abc") {
src_js = rebase_path("caller.js")
dst_file = rebase_path(target_out_dir + "/caller.abc")
in_puts = [ "caller.js" ]
out_puts = [ target_out_dir + "/caller.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("caller_js") {
input = "caller.js"
output = target_out_dir + "/caller.o"
}
gen_js_obj("caller_abc") {
input = get_label_info(":gen_caller_abc", "target_out_dir") + "/caller.abc"
output = target_out_dir + "/caller_abc.o"
dep = ":gen_caller_abc"
}
ohos_shared_library("caller_napi") {
sources = [ "caller_module.cpp" ]
deps = [
":caller_abc",
":caller_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module/application"
subsystem_name = "aafwk"
part_name = "ability_runtime"
}

View File

@ -0,0 +1,133 @@
/*
* 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.
*/
var rpc = requireNapi("rpc")
const EVENT_CALL_NOTIFY = 1;
const REQUEST_SUCCESS = 0;
const REQUEST_FAILED = 1;
class Caller {
constructor(obj) {
console.log("Caller::constructor obj is " + typeof obj);
this.__call_obj__ = obj;
this.releaseCallback = null;
}
call(method, data) {
console.log("Caller call method [" + method + "]");
if (typeof method !== 'string' || typeof data !== 'object') {
console.log("Caller call " + typeof method + " " + typeof data);
throw new Error("function input parameter error");
return;
}
if (this.__call_obj__.callee == null) {
console.log("Caller call this.callee is nullptr");
throw new Error("Function inner object error");
return;
}
let msgData = rpc.MessageParcel.create();
msgData.writeString(method);
let msgReply = rpc.MessageParcel.create();
let option = rpc.MessageOption();
msgData.writeSequenceable(data);
this.__call_obj__.callee.sendRequest(EVENT_CALL_NOTIFY, msgData, msgReply, option)
.then(function (err) {
expect(err).assertEqual(REQUEST_SUCCESS)
console.log("Caller call sendMsg return " + err);
let retval = msgReply.readInt();
if (retval !== REQUEST_SUCCESS) {
let str = msgReply.readString();
console.log("Caller call sendMsg return [" + retval + "] str [" + str + "]");
}
console.log("Caller call msgData SendRequest SUCCESS");
})
.catch(function (e) {
console.log("Caller call sendMsg error catch " + e.code);
})
.finally(() => {
msgData.reclaim();
msgReply.reclaim();
console.log("Caller call sendMsg error finally");
});
console.log("Caller call msgData SendRequest end");
return;
}
callWithResult(method, data) {
if (typeof method !== 'string' || typeof data !== 'object') {
console.log("Caller callWithResult " + typeof method + ", " + typeof data);
return undefined;
}
if (this.__call_obj__.callee == null) {
console.log("Caller callWithResult this.callee is nullptr");
return undefined;
}
let msgData = rpc.MessageParcel.create();
let msgReply = rpc.MessageParcel.create();
let option = rpc.MessageOption();
let reply = undefined;
msgData.writeString(method);
msgData.writeSequenceable(data);
this.__call_obj__.callee.sendRequest(CODE_BASIC, msgData, msgReply, option)
.then(function (err) {
expect(err).assertEqual(REQUEST_SUCCESS)
let retval = msgReply.readInt();
let str = msgReply.readString();
if (retval === REQUEST_SUCCESS && str === 'object') {
// msgReply.readSequenceable(reply);
reply = msgReply;
console.log("Caller callWithResult return data " + str);
} else {
console.log("Caller callWithResult retval is [" + retval + "], str [" + str + "]");
}
console.log("Caller callWithResult sendMsg return " + err);
})
.catch(function (e) {
console.log("Caller callWithResult sendMsg error catch " + e);
})
.finally(() => {
msgData.reclaim();
msgReply.reclaim();
console.log("Caller call sendMsg error finally");
});
return reply;
}
release() {
console.log("Caller release js called.");
this.__call_obj__.release();
}
onRelease(callback) {
console.log("Caller onRelease jscallback called.");
if (typeof callback !== 'function') {
console.log("Caller onRelease " + typeof callback);
throw new Error("function input parameter error");
return;
}
this.__call_obj__.onRelease(callback);
}
}
export default Caller

View File

@ -0,0 +1,56 @@
/*
* 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"
extern const char _binary_caller_js_start[];
extern const char _binary_caller_js_end[];
extern const char _binary_caller_abc_start[];
extern const char _binary_caller_abc_end[];
extern "C" __attribute__((constructor))
void NAPI_application_Caller_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "application.Caller",
.fileName = "application/libcaller_napi.so/caller.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default")))
void NAPI_application_Caller_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_caller_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_caller_js_end - _binary_caller_js_start;
}
}
extern "C" __attribute__((visibility("default")))
void NAPI_application_Caller_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_caller_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_caller_abc_end - _binary_caller_abc_start;
}
}

View File

@ -148,6 +148,7 @@
"test_list": [
"//foundation/aafwk/standard/frameworks/kits/content/cpp/test:unittest",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test:unittest",
"//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test:abilityruntimemoduletest",
"//foundation/aafwk/standard/frameworks/kits/test:moduletest",
"//foundation/aafwk/standard/services/test:moduletest",
"//foundation/aafwk/standard/services:unittest",

View File

@ -90,6 +90,8 @@ abilityms_files = [
"${services_path}/abilitymgr/src/stop_user_callback_proxy.cpp",
"${services_path}/abilitymgr/src/stop_user_callback_stub.cpp",
"${services_path}/abilitymgr/src/kernal_ability_manager.cpp",
"${services_path}/abilitymgr/src/call_container.cpp",
"${services_path}/abilitymgr/src/call_record.cpp",
#multi user
"${services_path}/abilitymgr/src/user_controller.cpp",

View File

@ -520,6 +520,26 @@ public:
virtual int CleanAllMissions() override;
virtual int MoveMissionToFront(int32_t missionId) override;
/**
* Start Ability, connect session with common ability.
*
* @param want, Special want for service type's ability.
* @param connect, Callback used to notify caller the result of connecting or disconnecting.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int StartAbilityByCall(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken) override;
/**
* Release Ability, disconnect session with common ability.
*
* @param connect, Callback used to notify caller the result of connecting or disconnecting.
* @param element, the element of target service.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int ReleaseAbility(
const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element) override;
virtual int StartUser(int userId) override;

View File

@ -645,6 +645,26 @@ public:
*/
virtual void GetSystemMemoryAttr(AppExecFwk::SystemMemoryAttr &memoryInfo) override;
/**
* Start Ability, connect session with common ability.
*
* @param want, Special want for service type's ability.
* @param connect, Callback used to notify caller the result of connecting or disconnecting.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int StartAbilityByCall(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken) override;
/**
* Release Ability, disconnect session with common ability.
*
* @param connect, Callback used to notify caller the result of connecting or disconnecting.
* @param element, the element of target service.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int ReleaseAbility(
const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element) override;
/**
* get service record by element name.
*
@ -653,6 +673,7 @@ public:
std::list<std::shared_ptr<ConnectionRecord>> GetConnectRecordListByCallback(sptr<IAbilityConnection> callback);
void OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord);
void OnCallConnectDied(std::shared_ptr<CallRecord> callRecord);
void GetMaxRestartNum(int &max);
/**
@ -905,6 +926,8 @@ private:
void DumpFuncInit();
bool CheckCallerIsSystemAppByIpc();
bool IsExistFile(const std::string &path);
int CheckCallPermissions(const AbilityRequest &abilityRequest);
void InitConnectManager(int32_t userId, bool switchUser);
void InitDataAbilityManager(int32_t userId, bool switchUser);

View File

@ -123,6 +123,10 @@ private:
int CleanMissionInner(MessageParcel &data, MessageParcel &reply);
int CleanAllMissionsInner(MessageParcel &data, MessageParcel &reply);
int MoveMissionToFrontInner(MessageParcel &data, MessageParcel &reply);
// for new version ability (call ability)
int StartAbilityByCallInner(MessageParcel &data, MessageParcel &reply);
int ReleaseInner(MessageParcel &data, MessageParcel &reply);
int StartUserInner(MessageParcel &data, MessageParcel &reply);
int StopUserInner(MessageParcel &data, MessageParcel &reply);
int SetMissionLabelInner(MessageParcel &data, MessageParcel &reply);

View File

@ -22,6 +22,7 @@
#include <memory>
#include <vector>
#include "ability_connect_callback_interface.h"
#include "ability_info.h"
#include "ability_start_setting.h"
#include "ability_token_stub.h"
@ -29,10 +30,12 @@
#include "app_scheduler.h"
#include "application_info.h"
#include "ability_record_info.h"
#include "call_container.h"
#include "lifecycle_deal.h"
#include "lifecycle_state_info.h"
#include "want.h"
#include "window_info.h"
#include "uri.h"
namespace OHOS {
namespace AAFwk {
@ -43,6 +46,7 @@ class MissionRecord;
class ConnectionRecord;
class Mission;
class MissionList;
class CallContainer;
const std::string ABILITY_TOKEN_NAME = "AbilityToken";
const std::string LINE_SEPARATOR = "\n";
@ -112,6 +116,10 @@ private:
* @class AbilityRequest
* Wrap parameters of starting ability.
*/
enum AbilityCallType {
INVALID_TYPE = 0,
CALL_REQUEST_TYPE,
};
struct AbilityRequest {
Want want;
AppExecFwk::AbilityInfo abilityInfo;
@ -119,7 +127,13 @@ struct AbilityRequest {
int32_t uid = 0;
int requestCode = -1;
bool restart = false;
sptr<IRemoteObject> callerToken;
// call ability
int callerUid = -1;
AbilityCallType callType = AbilityCallType::INVALID_TYPE;
sptr<IRemoteObject> callerToken = nullptr;
sptr<IAbilityConnection> connect = nullptr;
std::shared_ptr<AbilityStartSetting> startSetting = nullptr;
int32_t compatibleVersion = 0;
std::string specifiedFlag;
@ -138,6 +152,11 @@ struct AbilityRequest {
return false;
}
bool IsCallType(const AbilityCallType & type) const
{
return (callType == type);
}
void Dump(std::vector<std::string> &state)
{
std::string dumpInfo = " want [" + want.ToUri() + "]";
@ -151,6 +170,12 @@ struct AbilityRequest {
}
};
// new version
enum ResolveResultType {
OK_NO_REMOTE_OBJ = 0,
OK_HAS_REMOTE_OBJ,
NG_INNER_ERROR,
};
/**
* @class AbilityRecord
* AbilityRecord records ability info and states and used to schedule ability life.
@ -733,41 +758,56 @@ public:
void SetUid(int32_t uid);
int32_t GetUid();
void SetSwitchingPause(bool state);
void SetSwitchingPause(bool state);
bool IsSwitchingPause();
// new version
ResolveResultType Resolve(const AbilityRequest &abilityRequest);
bool Release(const sptr<IAbilityConnection> & connect);
bool IsNeedToCallRequest() const;
bool IsStartedByCall() const;
void SetStartedByCall(const bool isFlag);
bool CallRequest();
bool IsStartToBackground() const;
void SetStartToBackground(const bool flag);
void SetSpecifiedFlag(const std::string &flag);
std::string GetSpecifiedFlag() const;
protected:
void SendEvent(uint32_t msg, uint32_t timeOut);
sptr<Token> token_ = {}; // used to interact with kit and wms
std::unique_ptr<LifecycleDeal> lifecycleDeal_ = {}; // life manager used to schedule life
AbilityState currentState_ = AbilityState::INITIAL; // current life state
Want want_ = {}; // want to start this ability
LifeCycleStateInfo lifeCycleStateInfo_; // target life state info
static int64_t g_abilityRecordEventId_;
int64_t eventId_ = 0; // post event id
private:
/**
* get the type of ability.
*
*/
void GetAbilityTypeString(std::string &typeStr);
void OnSchedulerDied(const wptr<IRemoteObject> &remote);
void SendEvent(uint32_t msg, uint32_t timeOut);
void SetSpecifiedFlag(const std::string &flag);
std::string GetSpecifiedFlag() const;
static int64_t abilityRecordId;
int recordId_ = 0; // record id
Want want_ = {}; // want to start this ability
AppExecFwk::AbilityInfo abilityInfo_ = {}; // the ability info get from BMS
AppExecFwk::ApplicationInfo applicationInfo_ = {}; // the ability info get from BMS
sptr<Token> token_ = {}; // used to interact with kit and wms
std::weak_ptr<MissionRecord> missionRecord_ = {}; // mission of this ability
std::weak_ptr<AbilityRecord> preAbilityRecord_ = {}; // who starts this ability record
std::weak_ptr<AbilityRecord> nextAbilityRecord_ = {}; // ability that started by this ability
std::weak_ptr<AbilityRecord> backAbilityRecord_ = {}; // who back to this ability record
std::unique_ptr<LifecycleDeal> lifecycleDeal_ = {}; // life manager used to schedule life
int64_t startTime_ = 0; // records first time of ability start
bool isReady_ = false; // is ability thread attached?
bool isWindowAttached_ = false; // Is window of this ability attached?
bool isLauncherAbility_ = false; // is launcher?
int64_t eventId_ = 0; // post event id
static int64_t g_abilityRecordEventId_;
sptr<IAbilityScheduler> scheduler_ = {}; // kit scheduler
bool isTerminating_ = false; // is terminating ?
LifeCycleStateInfo lifeCycleStateInfo_; // target life state info
AbilityState currentState_ = AbilityState::INITIAL; // current life state
std::shared_ptr<WindowInfo> windowInfo_; // add window info
bool isCreateByConnect_ = false; // is created by connect ability mode?
bool isToEnd_ = false; // is to end ?
@ -815,7 +855,13 @@ public:
std::weak_ptr<MissionList> missionList_;
std::weak_ptr<Mission> mission_;
int32_t missionId_ = -1;
bool isSwitchingPause_ = false;
bool isSwitchingPause_ = false;
// new version
std::shared_ptr<CallContainer> callContainer_ = nullptr;
bool isStartedByCall_ = false;
bool isStartToBackground_ = false;
int32_t restartCount_ = -1;
int32_t restratMax_ = -1;
std::string specifiedFlag_;
@ -837,4 +883,4 @@ public:
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_ABILITY_RECORD_H
#endif // OHOS_AAFWK_ABILITY_RECORD_H

View File

@ -299,6 +299,8 @@ public:
*/
void NotifyContinuationResult(const int32_t result) override;
sptr<IRemoteObject> CallRequest() override;
private:
bool WriteInterfaceToken(MessageParcel &data);

View File

@ -64,6 +64,8 @@ private:
int MutiWinModeChangedInner(MessageParcel &data, MessageParcel &reply);
int TopActiveAbilityChangedInner(MessageParcel &data, MessageParcel &reply);
int NotifyContinuationResultInner(MessageParcel &data, MessageParcel &reply);
int CallRequestInner(MessageParcel &data, MessageParcel &reply);
int ContinueAbilityInner(MessageParcel &data, MessageParcel &reply);
using RequestFuncType = int (AbilitySchedulerStub::*)(MessageParcel &data, MessageParcel &reply);
std::map<uint32_t, RequestFuncType> requestFuncMap_;

View File

@ -0,0 +1,65 @@
/*
* 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 OHOS_AAFWK_CALL_CONTAINER_H
#define OHOS_AAFWK_CALL_CONTAINER_H
#include <map>
#include <string>
#include <mutex>
#include "ability_connect_callback_interface.h"
#include "call_record.h"
#include "element_name.h"
#include "iremote_object.h"
#include "nocopyable.h"
namespace OHOS {
namespace AAFwk {
class CallRecord;
/**
* @class CallContainer
* CallContainer provides a facility for managing the call records of ability.
*/
class CallContainer : public std::enable_shared_from_this<CallContainer> {
public:
using CallMapType = std::map<sptr<IRemoteObject>, std::shared_ptr<CallRecord>>;
using RecipientMapType = std::map<sptr<IRemoteObject>, sptr<IRemoteObject::DeathRecipient>>;
CallContainer();
virtual ~CallContainer();
void AddCallRecord(const sptr<IAbilityConnection> & connect, const std::shared_ptr<CallRecord>& callRecord);
std::shared_ptr<CallRecord> GetCallRecord(const sptr<IAbilityConnection> & connect) const;
bool RemoveCallRecord(const sptr<IAbilityConnection> & connect);
bool CallRequestDone(const sptr<IRemoteObject> & callStub);
void Dump(std::vector<std::string> &info, const std::string &args = "") const;
bool IsNeedToCallRequest() const;
private:
void RemoveConnectDeathRecipient(const sptr<IAbilityConnection> &connect);
void AddConnectDeathRecipient(const sptr<IAbilityConnection> &connect);
void OnConnectionDied(const wptr<IRemoteObject> & remote);
private:
CallMapType callRecordMap_;
RecipientMapType deathRecipientMap_;
DISALLOW_COPY_AND_MOVE(CallContainer);
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_CALL_CONTAINER_H

View File

@ -0,0 +1,99 @@
/*
* 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 OHOS_AAFWK_CALL_RECORD_H
#define OHOS_AAFWK_CALL_RECORD_H
#include "ability_connect_callback_interface.h"
#include "nocopyable.h"
namespace OHOS {
namespace AAFwk {
class AbilityRecord;
/**
* @class AbilityCallRecipient
* AbilityCallRecipient notices IRemoteBroker died.
*/
class AbilityCallRecipient : public IRemoteObject::DeathRecipient {
public:
using RemoteDiedHandler = std::function<void(const wptr<IRemoteObject> &)>;
AbilityCallRecipient(RemoteDiedHandler handler) : handler_(handler) {};
virtual ~AbilityCallRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject> &__attribute__((unused)) remote) override
{
if (handler_) {
handler_(remote);
}
};
private:
RemoteDiedHandler handler_;
};
/**
* @enum CallState
* CallState defines the state of calling ability.
*/
enum class CallState { INIT, REQUESTING, REQUESTED };
/**
* @class CallRecord
* CallRecord,This class is used to record information about a connection of calling ability.
*/
class CallRecord : public std::enable_shared_from_this<CallRecord> {
public:
CallRecord(const int32_t callerUid, const std::shared_ptr<AbilityRecord> &targetService,
const sptr<IAbilityConnection> &connCallback, const sptr<IRemoteObject> &callToken);
virtual ~CallRecord();
static std::shared_ptr<CallRecord> CreateCallRecord(const int32_t callerUid,
const std::shared_ptr<AbilityRecord> &targetService, const sptr<IAbilityConnection> &connCallback,
const sptr<IRemoteObject> &callToken);
void SetCallStub(const sptr<IRemoteObject> & call);
sptr<IRemoteObject> GetCallStub();
void SetConCallBack(const sptr<IAbilityConnection> &connCallback);
sptr<IAbilityConnection> GetConCallBack() const;
void Dump(std::vector<std::string> &info) const;
bool SchedulerConnectDone();
bool SchedulerDisConnectDone();
void OnCallStubDied(const wptr<IRemoteObject> & remote);
int32_t GetCallerUid() const;
bool IsCallState(const CallState& state) const;
void SetCallState(const CallState& state);
int32_t GetCallRecordId() const;
AppExecFwk::ElementName GetTargetServiceName() const;
sptr<IRemoteObject> GetCallerToken() const;
private:
static int64_t callRecordId;
int recordId_; // record id
int32_t callerUid_; // caller uid
CallState state_; // call state
sptr<IRemoteObject> callRemoteObject_ = nullptr;
sptr<IRemoteObject::DeathRecipient> callDeathRecipient_ = nullptr;
std::weak_ptr<AbilityRecord> service_; // target:service need to be called
sptr<IAbilityConnection> connCallback_ = nullptr; // service connect callback
sptr<IRemoteObject> callerToken_ = nullptr; // caller token
int64_t startTime_ = 0; // records first time of ability start
DISALLOW_COPY_AND_MOVE(CallRecord);
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_CALL_RECORD_H

View File

@ -145,6 +145,14 @@ public:
std::shared_ptr<AbilityRecord> GetAbilityRecordByCaller(
const std::shared_ptr<AbilityRecord> &caller, int requestCode);
/**
* @brief Get the Ability Record By elementName
*
* @param element
* @return std::shared_ptr<AbilityRecord> the ability record which find
*/
std::shared_ptr<AbilityRecord> GetAbilityRecordByName(const AppExecFwk::ElementName &element);
/**
* Get ability token by target mission id.
*

View File

@ -213,6 +213,13 @@ public:
*/
void OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord, int32_t currentUserId);
/**
* @brief handle when call contection died
*
* @param callRecord the died call contection
*/
void OnCallConnectDied(const std::shared_ptr<CallRecord> &callRecord);
/**
* Get mission id by target ability token.
*
@ -268,6 +275,21 @@ public:
void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag);
/**
* resolve the call ipc of ability for schudeling oncall.
*
* @param abilityRequest, target ability request.
*/
int ResolveLocked(const AbilityRequest &abilityRequest);
/**
* release the connection of this call.
*
* @param connect, caller callback ipc.
* @param element, target ability name.
*/
int ReleaseLocked(const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element);
/**
* @brief register snapshotHandler
* @param handler the snapshotHandler
@ -341,6 +363,11 @@ private:
void HandleLoadTimeout(const std::shared_ptr<AbilityRecord> &ability);
void HandleForgroundNewTimeout(const std::shared_ptr<AbilityRecord> &ability);
// new version for call inner function.
int ResolveAbility(const std::shared_ptr<AbilityRecord> &targetAbility, const AbilityRequest &abilityRequest);
std::shared_ptr<AbilityRecord> GetAbilityRecordByName(const AppExecFwk::ElementName &element);
int CallAbilityLocked(const AbilityRequest &abilityRequest);
private:
int userId_;
std::recursive_mutex managerLock_;

View File

@ -98,6 +98,7 @@ AbilityConnectionStub::~AbilityConnectionStub()
int AbilityConnectionStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
HILOG_DEBUG("AbilityConnectionStub::OnRemoteRequest OnAbilityConnectDone called.");
std::u16string descriptor = AbilityConnectionStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {

View File

@ -753,6 +753,23 @@ ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId)
return abms->MoveMissionToFront(missionId);
}
ErrCode AbilityManagerClient::StartAbilityByCall(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callToken)
{
CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED);
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
HILOG_DEBUG("AbilityManagerClient::StartAbilityByCall called.");
return abms->StartAbilityByCall(want, connect, callToken);
}
ErrCode AbilityManagerClient::ReleaseAbility(
const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
{
CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED);
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ReleaseAbility(connect, element);
}
ErrCode AbilityManagerClient::GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info)
{
CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED);

View File

@ -2164,6 +2164,75 @@ int AbilityManagerProxy::UnRegisterMissionListener(const std::string &deviceId,
return reply.ReadInt32();
}
int AbilityManagerProxy::StartAbilityByCall(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
HILOG_DEBUG("AbilityManagerProxy::StartAbilityByCall begin.");
int error;
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!WriteInterfaceToken(data)) {
return INNER_ERR;
}
if (!data.WriteParcelable(&want)) {
HILOG_ERROR("want write failed.");
return ERR_INVALID_VALUE;
}
if (connect == nullptr) {
HILOG_ERROR("resolve ability fail, connect is nullptr");
return ERR_INVALID_VALUE;
}
if (!data.WriteParcelable(connect->AsObject())) {
HILOG_ERROR("resolve write failed.");
return ERR_INVALID_VALUE;
}
if (!data.WriteParcelable(callerToken)) {
HILOG_ERROR("callerToken write failed.");
return INNER_ERR;
}
HILOG_DEBUG("AbilityManagerProxy::StartAbilityByCall SendRequest Call.");
error = Remote()->SendRequest(IAbilityManager::START_CALL_ABILITY, data, reply, option);
if (error != NO_ERROR) {
HILOG_ERROR("Send request error: %{public}d", error);
return error;
}
HILOG_DEBUG("AbilityManagerProxy::StartAbilityByCall end.");
return reply.ReadInt32();
}
int AbilityManagerProxy::ReleaseAbility(const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
{
int error;
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (connect == nullptr) {
HILOG_ERROR("release calll ability fail, connect is nullptr");
return ERR_INVALID_VALUE;
}
if (!WriteInterfaceToken(data)) {
return INNER_ERR;
}
if (!data.WriteParcelable(connect->AsObject())) {
HILOG_ERROR("release ability connect write failed.");
return ERR_INVALID_VALUE;
}
if (!data.WriteParcelable(&element)) {
HILOG_ERROR("element error.");
return ERR_INVALID_VALUE;
}
error = Remote()->SendRequest(IAbilityManager::RELEASE_CALL_ABILITY, data, reply, option);
if (error != NO_ERROR) {
HILOG_ERROR("Send request error: %{public}d", error);
return error;
}
return reply.ReadInt32();
}
int AbilityManagerProxy::RegisterSnapshotHandler(const sptr<ISnapshotHandler>& handler)
{
MessageParcel data;

View File

@ -2079,6 +2079,14 @@ void AbilityManagerService::OnAbilityDied(std::shared_ptr<AbilityRecord> ability
}
}
void AbilityManagerService::OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)
{
CHECK_POINTER(callRecord);
if (currentMissionListManager_) {
currentMissionListManager_->OnCallConnectDied(callRecord);
}
}
void AbilityManagerService::GetMaxRestartNum(int &max)
{
if (amsConfigResolver_) {
@ -2920,6 +2928,104 @@ void AbilityManagerService::StartingSettingsDataAbility()
(void)AcquireDataAbility(uri, true, nullptr);
}
int AbilityManagerService::StartAbilityByCall(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
HILOG_INFO("call ability.");
CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
AbilityRequest abilityRequest;
abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
abilityRequest.callerToken = callerToken;
abilityRequest.startSetting = nullptr;
abilityRequest.want = want;
abilityRequest.connect = connect;
int result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken);
if (result != ERR_OK) {
HILOG_ERROR("Generate ability request error.");
return result;
}
if (!abilityRequest.IsNewVersion()) {
HILOG_ERROR("target ability compatible version is lower than 8.");
return RESOLVE_CALL_ABILITY_VERSION_ERR;
}
result = CheckCallPermissions(abilityRequest);
if (result != ERR_OK) {
HILOG_ERROR("CheckCallPermissions fail, result: %{public}d", result);
return RESOLVE_CALL_NO_PERMISSIONS;
}
return currentMissionListManager_->ResolveLocked(abilityRequest);
}
int AbilityManagerService::ReleaseAbility(
const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
{
HILOG_DEBUG("Release called ability.");
CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
std::string elementName = element.GetURI();
HILOG_DEBUG("try to release called ability, name: %{public}s.", elementName.c_str());
return currentMissionListManager_->ReleaseLocked(connect, element);
}
int AbilityManagerService::CheckCallPermissions(const AbilityRequest &abilityRequest)
{
HILOG_DEBUG("%{public}s begin", __func__);
auto abilityInfo = abilityRequest.abilityInfo;
auto callerUid = abilityRequest.callerUid;
auto targetUid = abilityInfo.applicationInfo.uid;
if (AbilityUtil::ROOT_UID == callerUid) {
HILOG_DEBUG("uid is root,ability cannot be called.");
return RESOLVE_CALL_NO_PERMISSIONS;
}
auto bms = GetBundleManager();
CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
auto isSystemApp = bms->CheckIsSystemAppByUid(callerUid);
if (callerUid != SYSTEM_UID && !isSystemApp) {
HILOG_DEBUG("caller is common app.");
std::string bundleName;
bool result = bms->GetBundleNameForUid(callerUid, bundleName);
if (!result) {
HILOG_ERROR("GetBundleNameForUid frome bms fail.");
return RESOLVE_CALL_NO_PERMISSIONS;
}
if (bundleName != abilityInfo.bundleName && callerUid != targetUid) {
HILOG_ERROR("the bundlename of caller is different from target one, caller: %{public}s "
"target: %{public}s",
bundleName.c_str(),
abilityInfo.bundleName.c_str());
return RESOLVE_CALL_NO_PERMISSIONS;
}
} else {
HILOG_DEBUG("caller is systemapp or system ability.");
}
HILOG_DEBUG("the caller has permission to resolve the callproxy of common ability.");
// check whether the target ability is singleton mode and page type.
if (abilityInfo.type == AppExecFwk::AbilityType::PAGE &&
abilityInfo.launchMode == AppExecFwk::LaunchMode::SINGLETON) {
HILOG_DEBUG("called ability is common ability and singleton.");
} else {
HILOG_ERROR("called ability is not common ability or singleton.");
return RESOLVE_CALL_ABILITY_TYPE_ERR;
}
return ERR_OK;
}
int AbilityManagerService::SetMissionLabel(const sptr<IRemoteObject> &token, const std::string &label)
{
HILOG_DEBUG("%{public}s", __func__);

View File

@ -123,6 +123,8 @@ void AbilityManagerStub::SecondStepInit()
requestFuncMap_[CLEAN_MISSION] = &AbilityManagerStub::CleanMissionInner;
requestFuncMap_[CLEAN_ALL_MISSIONS] = &AbilityManagerStub::CleanAllMissionsInner;
requestFuncMap_[MOVE_MISSION_TO_FRONT] = &AbilityManagerStub::MoveMissionToFrontInner;
requestFuncMap_[START_CALL_ABILITY] = &AbilityManagerStub::StartAbilityByCallInner;
requestFuncMap_[RELEASE_CALL_ABILITY] = &AbilityManagerStub::ReleaseInner;
requestFuncMap_[SET_MISSION_LABEL] = &AbilityManagerStub::SetMissionLabelInner;
requestFuncMap_[START_USER] = &AbilityManagerStub::StartUserInner;
requestFuncMap_[STOP_USER] = &AbilityManagerStub::StopUserInner;
@ -1105,6 +1107,52 @@ int AbilityManagerStub::MoveMissionToFrontInner(MessageParcel &data, MessageParc
return NO_ERROR;
}
int AbilityManagerStub::StartAbilityByCallInner(MessageParcel &data, MessageParcel &reply)
{
HILOG_DEBUG("AbilityManagerStub::StartAbilityByCallInner begin.");
Want *want = data.ReadParcelable<Want>();
if (want == nullptr) {
HILOG_ERROR("want is nullptr");
return ERR_INVALID_VALUE;
}
auto callback = iface_cast<IAbilityConnection>(data.ReadParcelable<IRemoteObject>());
auto callerToken = data.ReadParcelable<IRemoteObject>();
int32_t result = StartAbilityByCall(*want, callback, callerToken);
HILOG_DEBUG("resolve call ability ret = %d", result);
reply.WriteInt32(result);
delete want;
HILOG_DEBUG("AbilityManagerStub::StartAbilityByCallInner end.");
return NO_ERROR;
}
int AbilityManagerStub::ReleaseInner(MessageParcel &data, MessageParcel &reply)
{
auto callback = iface_cast<IAbilityConnection>(data.ReadParcelable<IRemoteObject>());
if (callback == nullptr) {
HILOG_ERROR("callback is nullptr");
return ERR_INVALID_VALUE;
}
auto element = data.ReadParcelable<AppExecFwk::ElementName>();
if (element == nullptr) {
HILOG_ERROR("callback stub receive element is nullptr");
return ERR_INVALID_VALUE;
}
int32_t result = ReleaseAbility(callback, *element);
HILOG_DEBUG("release call ability ret = %d", result);
reply.WriteInt32(result);
return NO_ERROR;
}
int AbilityManagerStub::StartUserInner(MessageParcel &data, MessageParcel &reply)
{
int32_t userId = data.ReadInt32();

View File

@ -124,6 +124,10 @@ std::shared_ptr<AbilityRecord> AbilityRecord::CreateAbilityRecord(const AbilityR
HILOG_INFO("abilityRequest.startSetting...");
abilityRecord->SetStartSetting(abilityRequest.startSetting);
}
if (abilityRequest.IsCallType(AbilityCallType::CALL_REQUEST_TYPE)) {
HILOG_INFO("abilityRequest.callType is CALL_REQUEST_TYPE.");
abilityRecord->SetStartedByCall(true);
}
return abilityRecord;
}
@ -1372,6 +1376,104 @@ void AbilityRecordNew::BackgroundNew(const Closure &task)
lifecycleDeal_->BackgroundNew(want_, lifeCycleStateInfo_);
}
// new version --start
bool AbilityRecord::IsStartedByCall() const
{
return isStartedByCall_;
}
void AbilityRecord::SetStartedByCall(const bool isFlag)
{
isStartedByCall_ = isFlag;
}
bool AbilityRecord::IsStartToBackground() const
{
return isStartToBackground_;
}
void AbilityRecord::SetStartToBackground(const bool flag)
{
isStartToBackground_ = flag;
}
bool AbilityRecord::CallRequest()
{
HILOG_INFO("Call Request.");
CHECK_POINTER_RETURN_BOOL(scheduler_);
CHECK_POINTER_RETURN_BOOL(callContainer_);
// sync call request
sptr<IRemoteObject> callStub = scheduler_->CallRequest();
if (!callStub) {
HILOG_ERROR("call request failed, callstub is nullptr.");
return false;
}
// complete call request
return callContainer_->CallRequestDone(callStub);
}
ResolveResultType AbilityRecord::Resolve(const AbilityRequest &abilityRequest)
{
auto callback = abilityRequest.connect;
if (abilityRequest.callType != AbilityCallType::CALL_REQUEST_TYPE || !callback) {
HILOG_ERROR("only startd by call type can create a call record.");
return ResolveResultType::NG_INNER_ERROR;
}
if (!callContainer_) {
callContainer_ = std::make_shared<CallContainer>();
if (!callContainer_) {
HILOG_ERROR("mark_shared error.");
return ResolveResultType::NG_INNER_ERROR;
}
}
HILOG_DEBUG("create call record for this resolve. callerUid:%{public}d ,targetname:%{public}s",
abilityRequest.callerUid,
abilityRequest.abilityInfo.name.c_str());
std::shared_ptr<CallRecord> callRecord = callContainer_->GetCallRecord(callback);
if (!callRecord) {
callRecord = CallRecord::CreateCallRecord(
abilityRequest.callerUid, shared_from_this(), callback, abilityRequest.callerToken);
if (!callRecord) {
HILOG_ERROR("mark_shared error.");
return ResolveResultType::NG_INNER_ERROR;
}
}
callContainer_->AddCallRecord(callback, callRecord);
if (callRecord->IsCallState(CallState::REQUESTED) && callRecord->GetCallStub()) {
HILOG_DEBUG("this record has requested.");
if (!callRecord->SchedulerConnectDone()) {
HILOG_DEBUG("this callrecord has requested, but callback failed.");
return ResolveResultType::NG_INNER_ERROR;
}
return ResolveResultType::OK_HAS_REMOTE_OBJ;
}
callRecord->SetCallState(CallState::REQUESTING);
return ResolveResultType::OK_NO_REMOTE_OBJ;
}
bool AbilityRecord::Release(const sptr<IAbilityConnection> & connect)
{
HILOG_DEBUG("ability release call record by callback.");
CHECK_POINTER_RETURN_BOOL(callContainer_);
return callContainer_->RemoveCallRecord(connect);
}
bool AbilityRecord::IsNeedToCallRequest() const
{
HILOG_DEBUG("ability release call record by callback.");
CHECK_POINTER_RETURN_BOOL(callContainer_);
return callContainer_->IsNeedToCallRequest();
}
void AbilityRecord::ContinueAbility(const std::string& deviceId)
{
HILOG_INFO("ContinueAbility.");

View File

@ -980,5 +980,39 @@ void AbilitySchedulerProxy::NotifyContinuationResult(int32_t result)
HILOG_ERROR("NotifyContinuationResult fail to SendRequest. err: %d", err);
}
}
sptr<IRemoteObject> AbilitySchedulerProxy::CallRequest()
{
HILOG_INFO("AbilitySchedulerProxy::CallRequest start");
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!WriteInterfaceToken(data)) {
return nullptr;
}
int32_t err = Remote()->SendRequest(IAbilityScheduler::REQUEST_CALL_REMOTE, data, reply, option);
if (err != NO_ERROR) {
HILOG_ERROR("CallRequest fail to SendRequest. err: %d", err);
return nullptr;
}
int32_t result = reply.ReadInt32();
if (result != ERR_OK) {
HILOG_ERROR("CallRequest failed, err %{public}d", result);
return nullptr;
}
auto call = reply.ReadParcelable<IRemoteObject>();
if (!call) {
HILOG_ERROR("CallRequest error");
return nullptr;
}
HILOG_INFO("AbilitySchedulerProxy::CallRequest end");
return call;
}
} // namespace AAFwk
} // namespace OHOS

View File

@ -58,6 +58,7 @@ AbilitySchedulerStub::AbilitySchedulerStub()
requestFuncMap_[SCHEDULE_EXECUTEBATCH] = &AbilitySchedulerStub::ExecuteBatchInner;
requestFuncMap_[TOP_ACTIVE_ABILITY_CHANGED] = &AbilitySchedulerStub::TopActiveAbilityChangedInner;
requestFuncMap_[NOTIFY_CONTINUATION_RESULT] = &AbilitySchedulerStub::NotifyContinuationResultInner;
requestFuncMap_[REQUEST_CALL_REMOTE] = &AbilitySchedulerStub::CallRequestInner;
requestFuncMap_[CONTINUE_ABILITY] = &AbilitySchedulerStub::ContinueAbilityInner;
}
@ -576,6 +577,31 @@ int AbilitySchedulerStub::NotifyContinuationResultInner(MessageParcel &data, Mes
return NO_ERROR;
}
int AbilitySchedulerStub::CallRequestInner(MessageParcel &data, MessageParcel &reply)
{
HILOG_INFO("AbilitySchedulerStub::CallRequestInner start");
sptr<IRemoteObject> call = CallRequest();
if (!call) {
HILOG_ERROR("call request return nullptr.");
return ERR_INVALID_VALUE;
}
if (!reply.WriteInt32(NO_ERROR)) {
HILOG_ERROR("GetAllStackInfo result error");
return ERR_INVALID_VALUE;
}
if (!reply.WriteParcelable(call)) {
HILOG_ERROR("call request write failed.");
return ERR_INVALID_VALUE;
}
HILOG_INFO("AbilitySchedulerStub::CallRequestInner end");
return NO_ERROR;
}
void AbilitySchedulerRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
HILOG_ERROR("recv AbilitySchedulerRecipient death notice");

View File

@ -0,0 +1,189 @@
/*
* 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 "call_container.h"
#include "hilog_wrapper.h"
#include "ability_manager_errors.h"
#include "ability_connect_callback_stub.h"
#include "ability_util.h"
#include "ability_event_handler.h"
#include "ability_manager_service.h"
namespace OHOS {
namespace AAFwk {
CallContainer::CallContainer()
{}
CallContainer::~CallContainer()
{
std::for_each(deathRecipientMap_.begin(),
deathRecipientMap_.end(),
[&](RecipientMapType::reference recipient) {
recipient.first->RemoveDeathRecipient(recipient.second);
});
deathRecipientMap_.clear();
callRecordMap_.clear();
}
void CallContainer::AddCallRecord(const sptr<IAbilityConnection> & connect,
const std::shared_ptr<CallRecord>& callRecord)
{
CHECK_POINTER(callRecord);
CHECK_POINTER(connect);
CHECK_POINTER(connect->AsObject());
auto iter = callRecordMap_.find(connect->AsObject());
if (iter != callRecordMap_.end()) {
RemoveConnectDeathRecipient(connect);
callRecordMap_.erase(callRecordMap_.find(connect->AsObject()));
}
AddConnectDeathRecipient(connect);
callRecord->SetConCallBack(connect);
callRecordMap_.emplace(connect->AsObject(), callRecord);
HILOG_DEBUG("Add call record to callcontainer, target: %{public}s",
callRecord->GetTargetServiceName().GetURI().c_str());
}
std::shared_ptr<CallRecord> CallContainer::GetCallRecord(const sptr<IAbilityConnection> & connect) const
{
CHECK_POINTER_AND_RETURN(connect, nullptr);
CHECK_POINTER_AND_RETURN(connect->AsObject(), nullptr);
auto mapIter = callRecordMap_.find(connect->AsObject());
if (mapIter != callRecordMap_.end()) {
return mapIter->second;
}
return nullptr;
}
bool CallContainer::RemoveCallRecord(const sptr<IAbilityConnection> & connect)
{
HILOG_DEBUG("call container release call record by callback.");
CHECK_POINTER_AND_RETURN(connect, nullptr);
CHECK_POINTER_AND_RETURN(connect->AsObject(), nullptr);
auto iter = callRecordMap_.find(connect->AsObject());
if (iter != callRecordMap_.end()) {
auto callrecord = iter->second;
if (callrecord) {
callrecord->SchedulerDisConnectDone();
}
RemoveConnectDeathRecipient(connect);
callRecordMap_.erase(callRecordMap_.find(connect->AsObject()));
HILOG_DEBUG("remove call record is success.");
return true;
}
if (callRecordMap_.empty()) {
// notify soft resouce service.
HILOG_DEBUG("this ability has no callrecord.");
}
HILOG_WARN("remove call record is not exist.");
return false;
}
void CallContainer::OnConnectionDied(const wptr<IRemoteObject> & remote)
{
HILOG_WARN("Call back is died.");
auto object = remote.promote();
CHECK_POINTER(object);
std::shared_ptr<CallRecord> callRecord = nullptr;
auto mapIter = callRecordMap_.find(object);
if (mapIter != callRecordMap_.end()) {
callRecord = mapIter->second;
}
auto abilityManagerService = DelayedSingleton<AbilityManagerService>::GetInstance();
CHECK_POINTER(abilityManagerService);
auto handler = abilityManagerService->GetEventHandler();
CHECK_POINTER(handler);
auto task = [abilityManagerService, callRecord]() {
abilityManagerService->OnCallConnectDied(callRecord);
};
handler->PostTask(task);
}
bool CallContainer::CallRequestDone(const sptr<IRemoteObject> & callStub)
{
HILOG_INFO("Call Request Done start.");
CHECK_POINTER_AND_RETURN(callStub, false);
std::for_each(callRecordMap_.begin(),
callRecordMap_.end(),
[&callStub](CallMapType::reference service) {
std::shared_ptr<CallRecord> callRecord = service.second;
if (callRecord && callRecord->IsCallState(CallState::REQUESTING)) {
callRecord->SetCallStub(callStub);
callRecord->SchedulerConnectDone();
}
});
HILOG_INFO("Call Request Done end.");
return true;
}
void CallContainer::Dump(std::vector<std::string> &info, const std::string &args) const
{
HILOG_INFO("Dump call records.");
}
bool CallContainer::IsNeedToCallRequest() const
{
for (auto &iter : callRecordMap_) {
auto callRecord = iter.second;
if (callRecord && !callRecord->IsCallState(CallState::REQUESTED)) {
return true;
}
}
return false;
}
void CallContainer::AddConnectDeathRecipient(const sptr<IAbilityConnection> &connect)
{
CHECK_POINTER(connect);
CHECK_POINTER(connect->AsObject());
auto it = deathRecipientMap_.find(connect->AsObject());
if (it != deathRecipientMap_.end()) {
HILOG_ERROR("This death recipient has been added.");
return;
} else {
sptr<IRemoteObject::DeathRecipient> deathRecipient = new AbilityConnectCallbackRecipient(
std::bind(&CallContainer::OnConnectionDied, this, std::placeholders::_1));
connect->AsObject()->AddDeathRecipient(deathRecipient);
deathRecipientMap_.emplace(connect->AsObject(), deathRecipient);
}
}
void CallContainer::RemoveConnectDeathRecipient(const sptr<IAbilityConnection> &connect)
{
CHECK_POINTER(connect);
CHECK_POINTER(connect->AsObject());
auto it = deathRecipientMap_.find(connect->AsObject());
if (it != deathRecipientMap_.end()) {
it->first->RemoveDeathRecipient(it->second);
deathRecipientMap_.erase(it);
return;
}
}
} // namespace AAFwk
} // namesspace OHOS

View File

@ -0,0 +1,181 @@
/*
* 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 "call_record.h"
#include "hilog_wrapper.h"
#include "ability_util.h"
#include "ability_event_handler.h"
#include "ability_manager_service.h"
#include "ability_record.h"
#include "element_name.h"
namespace OHOS {
namespace AAFwk {
int64_t CallRecord::callRecordId = 0;
CallRecord::CallRecord(const int32_t callerUid, const std::shared_ptr<AbilityRecord> &targetService,
const sptr<IAbilityConnection> &connCallback, const sptr<IRemoteObject> &callToken)
: callerUid_(callerUid),
state_(CallState::INIT),
service_(targetService),
connCallback_(connCallback),
callerToken_(callToken)
{
recordId_ = callRecordId++;
startTime_ = AbilityUtil::SystemTimeMillis();
}
CallRecord::~CallRecord()
{
if (callRemoteObject_ && callDeathRecipient_) {
callRemoteObject_->RemoveDeathRecipient(callDeathRecipient_);
}
}
std::shared_ptr<CallRecord> CallRecord::CreateCallRecord(const int32_t callerUid,
const std::shared_ptr<AbilityRecord> &targetService, const sptr<IAbilityConnection> &connCallback,
const sptr<IRemoteObject> &callToken)
{
auto callRecord = std::make_shared<CallRecord>(callerUid, targetService, connCallback, callToken);
CHECK_POINTER_AND_RETURN(callRecord, nullptr);
callRecord->SetCallState(CallState::INIT);
return callRecord;
}
void CallRecord::SetCallStub(const sptr<IRemoteObject> & call)
{
CHECK_POINTER(call);
callRemoteObject_ = call;
HILOG_DEBUG("SetCallStub complete.");
if (callDeathRecipient_ == nullptr) {
callDeathRecipient_ =
new AbilityCallRecipient(std::bind(&CallRecord::OnCallStubDied, this, std::placeholders::_1));
}
callRemoteObject_->AddDeathRecipient(callDeathRecipient_);
}
sptr<IRemoteObject> CallRecord::GetCallStub()
{
return callRemoteObject_;
}
void CallRecord::SetConCallBack(const sptr<IAbilityConnection> &connCallback)
{
connCallback_ = connCallback;
}
sptr<IAbilityConnection> CallRecord::GetConCallBack() const
{
return connCallback_;
}
AppExecFwk::ElementName CallRecord::GetTargetServiceName() const
{
std::shared_ptr<AbilityRecord> tmpService = service_.lock();
if (tmpService) {
const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo();
AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name);
return element;
}
return AppExecFwk::ElementName();
}
sptr<IRemoteObject> CallRecord::GetCallerToken() const
{
return callerToken_;
}
bool CallRecord::SchedulerConnectDone()
{
HILOG_DEBUG("Scheduler Connect Done by callback. id:%{public}d", recordId_);
std::shared_ptr<AbilityRecord> tmpService = service_.lock();
if (!callRemoteObject_ || !connCallback_ || !tmpService) {
HILOG_ERROR("callstub or connCallback is nullptr, can't scheduler connect done.");
return false;
}
const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo();
AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name);
connCallback_->OnAbilityConnectDone(element, callRemoteObject_, ERR_OK);
state_ = CallState::REQUESTED;
HILOG_DEBUG("element: %{public}s, result: %{public}d. connectstate:%{public}d.", element.GetURI().c_str(),
ERR_OK, state_);
return true;
}
bool CallRecord::SchedulerDisConnectDone()
{
HILOG_DEBUG("Scheduler disconnect Done by callback. id:%{public}d", recordId_);
std::shared_ptr<AbilityRecord> tmpService = service_.lock();
if (!connCallback_ || !tmpService) {
HILOG_ERROR("callstub or connCallback is nullptr, can't scheduler connect done.");
return false;
}
const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo();
AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name);
connCallback_->OnAbilityDisconnectDone(element, ERR_OK);
return true;
}
void CallRecord::OnCallStubDied(const wptr<IRemoteObject> & remote)
{
HILOG_WARN("callstub is died. id:%{public}d", recordId_);
auto object = remote.promote();
CHECK_POINTER(object);
auto abilityManagerService = DelayedSingleton<AbilityManagerService>::GetInstance();
CHECK_POINTER(abilityManagerService);
auto handler = abilityManagerService->GetEventHandler();
CHECK_POINTER(handler);
auto task = [abilityManagerService, callRecord = shared_from_this()]() {
abilityManagerService->OnCallConnectDied(callRecord);
};
handler->PostTask(task);
}
void CallRecord::Dump(std::vector<std::string> &info) const
{
HILOG_DEBUG("CallRecord::Dump is called");
}
int32_t CallRecord::GetCallerUid() const
{
return callerUid_;
}
bool CallRecord::IsCallState(const CallState& state) const
{
return (state_ == state);
}
void CallRecord::SetCallState(const CallState& state)
{
state_ = state;
}
int CallRecord::GetCallRecordId() const
{
return recordId_;
}
} // namespace AAFwk
} // namespace OHOS

View File

@ -204,6 +204,20 @@ std::shared_ptr<AbilityRecord> MissionList::GetAbilityRecordByCaller(
return nullptr;
}
std::shared_ptr<AbilityRecord> MissionList::GetAbilityRecordByName(const AppExecFwk::ElementName &element)
{
for (auto mission : missions_) {
if (mission) {
const AppExecFwk::AbilityInfo &abilityInfo = mission->GetAbilityRecord()->GetAbilityInfo();
AppExecFwk::ElementName localElement(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name);
if (localElement == element) {
return mission->GetAbilityRecord();
}
}
}
return nullptr;
}
sptr<IRemoteObject> MissionList::GetAbilityTokenByMissionId(int32_t missionId)
{
for (auto mission : missions_) {

View File

@ -559,6 +559,18 @@ int MissionListManager::AttachAbilityThread(const sptr<IAbilityScheduler> &sched
handler->RemoveEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecord->GetEventId());
abilityRecord->SetScheduler(scheduler);
if (abilityRecord->IsStartedByCall()) {
// started by callability, directly move to background.
abilityRecord->SetStartToBackground(true);
MoveToBackgroundTask(abilityRecord);
return ERR_OK;
}
if (abilityRecord->IsNeedToCallRequest()) {
abilityRecord->CallRequest();
}
DelayedSingleton<AppScheduler>::GetInstance()->MoveToForground(token);
return ERR_OK;
@ -784,6 +796,14 @@ void MissionListManager::CompleteBackground(const std::shared_ptr<AbilityRecord>
terminateAbility->Terminate(timeoutTask);
}
}
// new version. started by caller, sdheduler call request
if (abilityRecord->IsStartedByCall() && abilityRecord->IsStartToBackground() && abilityRecord->IsReady()) {
HILOG_DEBUG("call request after completing backgroud state");
abilityRecord->CallRequest();
abilityRecord->SetStartToBackground(false);
}
auto mission = abilityRecord->GetMission();
if (!mission) {
HILOG_ERROR("snapshot: GetMission failed");
@ -1604,6 +1624,150 @@ void MissionListManager::DumpMission(int missionId, std::vector<std::string> &in
innerMissionInfo.Dump(info);
}
int MissionListManager::ResolveLocked(const AbilityRequest &abilityRequest)
{
HILOG_INFO("%{public}s, resolve ability_name:%{public}s",
__func__,
abilityRequest.want.GetElement().GetURI().c_str());
if (!abilityRequest.IsCallType(AbilityCallType::CALL_REQUEST_TYPE)) {
HILOG_ERROR("%{public}s, resolve ability_name:", __func__);
return RESOLVE_CALL_ABILITY_INNER_ERR;
}
return CallAbilityLocked(abilityRequest);
}
int MissionListManager::CallAbilityLocked(const AbilityRequest &abilityRequest)
{
HILOG_INFO("call ability.");
std::lock_guard<std::recursive_mutex> guard(managerLock_);
// allow to start ability by called type without loading ui.
if (!abilityRequest.IsCallType(AbilityCallType::CALL_REQUEST_TYPE)) {
HILOG_ERROR("start ability not by call.");
return ERR_INVALID_VALUE;
}
// Get target mission and ability record.
std::shared_ptr<AbilityRecord> targetAbilityRecord;
std::shared_ptr<Mission> targetMission;
GetTargetMissionAndAbility(abilityRequest, targetMission, targetAbilityRecord);
if (!targetMission || !targetAbilityRecord) {
HILOG_ERROR("Failed to get mission or record.");
return ERR_INVALID_VALUE;
}
targetAbilityRecord->AddCallerRecord(abilityRequest.callerToken, abilityRequest.requestCode);
targetAbilityRecord->SetLaunchReason(LaunchReason::LAUNCHREASON_CALL);
// mission is first created, add mission to default call mission list.
// other keep in current mission list.
if (!targetMission->GetMissionList()) {
defaultSingleList_->AddMissionToTop(targetMission);
}
// new version started by call type
auto ret = ResolveAbility(targetAbilityRecord, abilityRequest);
if (ret == ResolveResultType::OK_HAS_REMOTE_OBJ) {
HILOG_DEBUG("target ability has been resolved.");
return ERR_OK;
} else if (ret == ResolveResultType::NG_INNER_ERROR) {
HILOG_ERROR("resolve failed, error: %{public}d.", RESOLVE_CALL_ABILITY_INNER_ERR);
return RESOLVE_CALL_ABILITY_INNER_ERR;
}
// schedule target ability
std::string element = targetAbilityRecord->GetWant().GetElement().GetURI();
HILOG_DEBUG("load ability record: %{public}s", element.c_str());
// flag the first ability.
auto currentTopAbility = GetCurrentTopAbilityLocked();
if (!currentTopAbility) {
targetAbilityRecord->SetLauncherRoot();
}
return targetAbilityRecord->LoadAbility();
}
int MissionListManager::ReleaseLocked(const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
{
HILOG_DEBUG("release ability.");
CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
std::lock_guard<std::recursive_mutex> guard(managerLock_);
std::shared_ptr<AbilityRecord> abilityRecord = GetAbilityRecordByName(element);
CHECK_POINTER_AND_RETURN(abilityRecord, RELEASE_CALL_ABILITY_INNER_ERR);
if (!abilityRecord->Release(connect)) {
HILOG_ERROR("ability release call record failed.");
return RELEASE_CALL_ABILITY_INNER_ERR;
}
return ERR_OK;
}
int MissionListManager::ResolveAbility(
const std::shared_ptr<AbilityRecord> &targetAbility, const AbilityRequest &abilityRequest)
{
HILOG_DEBUG("targetAbilityRecord resolve call record.");
CHECK_POINTER_AND_RETURN(targetAbility, ResolveResultType::NG_INNER_ERROR);
ResolveResultType result = targetAbility->Resolve(abilityRequest);
switch (result) {
case ResolveResultType::NG_INNER_ERROR:
case ResolveResultType::OK_HAS_REMOTE_OBJ:
return result;
default:
break;
}
if (targetAbility->IsReady()) {
HILOG_DEBUG("targetAbility is ready, directly scheduler call request.");
if (targetAbility->CallRequest()) {
return ResolveResultType::OK_HAS_REMOTE_OBJ;
}
}
HILOG_DEBUG("targetAbility need to call request after lifecycle.");
return result;
}
std::shared_ptr<AbilityRecord> MissionListManager::GetAbilityRecordByName(const AppExecFwk::ElementName &element)
{
// find in currentMissionLists_
for (auto missionList : currentMissionLists_) {
if (missionList != nullptr) {
auto ability = missionList->GetAbilityRecordByName(element);
if (ability != nullptr) {
return ability;
}
}
}
// find in lanucheMissionList_
auto ability = launcherList_->GetAbilityRecordByName(element);
if (ability != nullptr) {
return ability;
}
// find in default singlelist_
return defaultSingleList_->GetAbilityRecordByName(element);
}
void MissionListManager::OnCallConnectDied(const std::shared_ptr<CallRecord> &callRecord)
{
HILOG_INFO("On callConnect died.");
CHECK_POINTER(callRecord);
std::lock_guard<std::recursive_mutex> guard(managerLock_);
AppExecFwk::ElementName element = callRecord->GetTargetServiceName();
auto abilityRecord = GetAbilityRecordByName(element);
CHECK_POINTER(abilityRecord);
abilityRecord->Release(callRecord->GetConCallBack());
}
void MissionListManager::OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag)
{
std::lock_guard<std::recursive_mutex> guard(managerLock_);

View File

@ -34,6 +34,8 @@ ohos_source_set("abilityms_test_source") {
"${services_path}/abilitymgr/src/ability_start_setting.cpp",
"${services_path}/abilitymgr/src/ability_token_stub.cpp",
"${services_path}/abilitymgr/src/ams_configuration_parameter.cpp",
"${services_path}/abilitymgr/src/call_container.cpp",
"${services_path}/abilitymgr/src/call_record.cpp",
"${services_path}/abilitymgr/src/caller_info.cpp",
"${services_path}/abilitymgr/src/connection_record.cpp",
"${services_path}/abilitymgr/src/data_ability_caller_recipient.cpp",

View File

@ -101,6 +101,10 @@ public:
{};
virtual void ContinueAbility(const std::string& deviceId) override
{};
virtual sptr<IRemoteObject> CallRequest() override
{
return sptr<IRemoteObject>(nullptr);
};
private:
AbilityResult result_;
};

View File

@ -141,6 +141,11 @@ public:
return std::vector<std::shared_ptr<AppExecFwk::DataAbilityResult>>();
}
virtual sptr<IRemoteObject> CallRequest()
{
return sptr<IRemoteObject>(nullptr);
}
int code_ = 0;
};
} // namespace AAFwk

View File

@ -326,6 +326,16 @@ public:
{
return 0;
}
virtual int StartAbility(const Want &want, const StartOptions &startOptions,
const sptr<IRemoteObject> &callerToken, int requestCode) override
{
return 0;
}
virtual int ReleaseAbility(const sptr<IAbilityConnection> &connect,
const AppExecFwk::ElementName &element) override
{
return 0;
}
virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot)
{
return 0;
@ -387,6 +397,7 @@ public:
MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector<AbilityRunningInfo> &info));
MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector<ExtensionRunningInfo> &info));
MOCK_METHOD1(GetProcessRunningInfos, int(std::vector<AppExecFwk::RunningProcessInfo> &info));
MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr<IAbilityConnection> &, const sptr<IRemoteObject> &));
};
} // namespace AAFwk
} // namespace OHOS

View File

@ -58,6 +58,7 @@ public:
MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector<AbilityRunningInfo> &info));
MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector<ExtensionRunningInfo> &info));
MOCK_METHOD1(GetProcessRunningInfos, int(std::vector<AppExecFwk::RunningProcessInfo> &info));
MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr<IAbilityConnection> &, const sptr<IRemoteObject> &));
int InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
@ -373,6 +374,17 @@ public:
{
return 0;
}
virtual int StartAbility(const Want &want, const StartOptions &startOptions,
const sptr<IRemoteObject> &callerToken, int requestCode) override
{
return 0;
}
virtual int ReleaseAbility(const sptr<IAbilityConnection> &connect,
const AppExecFwk::ElementName &element) override
{
return 0;
}
virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot)
{
return 0;

View File

@ -133,6 +133,10 @@ public:
{}
virtual void ContinueAbility(const std::string& deviceId) override
{}
virtual sptr<IRemoteObject> CallRequest() override
{
return sptr<IRemoteObject>(nullptr);
}
};
} // namespace AAFwk
} // namespace OHOS

View File

@ -764,7 +764,16 @@ public:
{
return true;
}
virtual int StartAbilityByCall(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken) override
{
return 0;
}
virtual int ReleaseAbility(
const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element) override
{
return 0;
}
private:
Semaphore sem_;
};

View File

@ -113,6 +113,7 @@ public:
MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector<AbilityRunningInfo> &info));
MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector<ExtensionRunningInfo> &info));
MOCK_METHOD1(GetProcessRunningInfos, int(std::vector<AppExecFwk::RunningProcessInfo> &info));
MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr<IAbilityConnection> &, const sptr<IRemoteObject> &));
virtual int StartUser(int userId) override
{
@ -141,6 +142,16 @@ public:
{
return 0;
}
virtual int StartAbility(const Want &want, const StartOptions &startOptions,
const sptr<IRemoteObject> &callerToken, int requestCode) override
{
return 0;
}
virtual int ReleaseAbility(const sptr<IAbilityConnection> &connect,
const AppExecFwk::ElementName &element) override
{
return 0;
}
virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot)
{
return 0;

View File

@ -107,6 +107,10 @@ public:
Uri urivalue("");
return urivalue;
}
virtual sptr<IRemoteObject> CallRequest() override
{
return sptr<IRemoteObject>(nullptr);
}
};
} // namespace AAFwk
} // namespace OHOS

View File

@ -53,6 +53,11 @@ public:
const std::vector<std::shared_ptr<AppExecFwk::DataAbilityOperation>> &operations));
MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result));
MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId));
virtual sptr<IRemoteObject> CallRequest()
{
return sptr<IRemoteObject>(nullptr);
}
};
} // namespace AAFwk
} // namespace OHOS

View File

@ -41,6 +41,8 @@ ohos_moduletest("ability_mgr_module_test") {
"//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_stack_manager.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_token_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/call_container.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/call_record.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/caller_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/connection_record.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/data_ability_manager.cpp",

View File

@ -43,6 +43,8 @@ ohos_moduletest("AbilityRecordModuleTest") {
"${services_path}/abilitymgr/src/ability_stack_manager.cpp",
"${services_path}/abilitymgr/src/ability_token_stub.cpp",
"${services_path}/abilitymgr/src/app_scheduler.cpp",
"${services_path}/abilitymgr/src/call_container.cpp",
"${services_path}/abilitymgr/src/call_record.cpp",
"${services_path}/abilitymgr/src/caller_info.cpp",
"${services_path}/abilitymgr/src/connection_record.cpp",
"${services_path}/abilitymgr/src/data_ability_manager.cpp",

View File

@ -41,6 +41,8 @@ ohos_moduletest("ability_stack_module_test") {
"//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_stack_manager.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_token_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/call_container.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/call_record.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/caller_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/connection_record.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/data_ability_manager.cpp",

View File

@ -166,6 +166,23 @@ public:
{
return 0;
}
virtual int StartAbility(const Want &want, const StartOptions &startOptions,
const sptr<IRemoteObject> &callerToken, int requestCode)
{
return 0;
}
virtual int StartAbilityByCall(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
return 0;
}
virtual int ReleaseAbility(const sptr<IAbilityConnection> &connect,
const AppExecFwk::ElementName &element)
{
return 0;
}
virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot)
{
return 0;