From 1c2b4fcab7e6380b4665aa0d640df1fb05570fdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Wed, 19 Jan 2022 15:00:26 +0800 Subject: [PATCH 01/77] code check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- .../common/include/bgtaskmgr_inner_errors.h | 3 +- .../common/include/bgtaskmgr_log_wrapper.h | 1 - frameworks/common/include/ipc_util.h | 8 ++-- frameworks/include/background_task_manager.h | 1 - .../include/background_task_mgr_proxy.h | 2 +- frameworks/include/background_task_mgr_stub.h | 3 +- frameworks/include/expired_callback_stub.h | 3 +- frameworks/include/ibackground_task_mgr.h | 2 +- frameworks/include/iexpired_callback.h | 1 - frameworks/src/background_task_manager.cpp | 10 ++--- frameworks/src/background_task_mgr_proxy.cpp | 10 +++-- frameworks/src/background_task_mgr_stub.cpp | 24 +++++++----- .../src/background_task_subscriber_proxy.cpp | 2 +- .../src/background_task_subscriber_stub.cpp | 8 ++-- frameworks/src/expired_callback_stub.cpp | 3 +- .../include/background_task_mgr_helper.h | 1 - .../include/background_task_subscriber.h | 3 +- .../innerkits/include/delay_suspend_info.h | 28 ++++++++++---- .../innerkits/include/expired_callback.h | 3 +- .../src/background_task_mgr_helper.cpp | 1 - .../src/background_task_subscriber.cpp | 12 +++--- .../innerkits/src/delay_suspend_info.cpp | 2 - interfaces/innerkits/src/expired_callback.cpp | 1 - .../innerkits/src/transient_task_app_info.cpp | 2 +- interfaces/kits/napi/include/common.h | 10 ++--- interfaces/kits/napi/include/init.h | 1 - .../kits/napi/include/request_suspend_delay.h | 4 -- .../kits/napi/src/cancel_suspend_delay.cpp | 1 - interfaces/kits/napi/src/common.cpp | 13 +++++-- .../napi/src/get_remaining_delay_time.cpp | 3 +- interfaces/kits/napi/src/init.cpp | 2 - .../kits/napi/src/request_suspend_delay.cpp | 2 - .../include/background_task_mgr_service.h | 5 +-- .../core/src/background_task_mgr_service.cpp | 11 ++---- .../background_task_mgr_service_test.cpp | 9 ++--- .../unittest/bg_transient_task_mgr_test.cpp | 11 +++--- .../test/unittest/mock/mock_event_handler.cpp | 2 - .../include/bg_transient_task_mgr.h | 4 +- .../transient_task/include/decision_maker.h | 18 ++++----- .../include/delay_suspend_info_ex.h | 2 +- services/transient_task/include/event_info.h | 4 +- services/transient_task/include/key_info.h | 9 ++--- .../include/pkg_delay_suspend_info.h | 2 +- .../transient_task/include/time_provider.h | 2 +- .../src/bg_transient_task_mgr.cpp | 6 +-- .../transient_task/src/decision_maker.cpp | 4 +- .../src/delay_suspend_info_ex.cpp | 4 +- .../src/device_info_manager.cpp | 37 +++++++++---------- services/transient_task/src/event_hub.cpp | 2 +- .../src/pkg_delay_suspend_info.cpp | 4 +- .../transient_task/src/suspend_controller.cpp | 4 +- services/transient_task/src/watchdog.cpp | 2 +- utils/dump/include/bgtaskmgr_shell_command.h | 4 +- utils/dump/src/bgtaskmgr_shell_command.cpp | 4 +- 54 files changed, 152 insertions(+), 168 deletions(-) diff --git a/frameworks/common/include/bgtaskmgr_inner_errors.h b/frameworks/common/include/bgtaskmgr_inner_errors.h index 78195172..0551efeb 100644 --- a/frameworks/common/include/bgtaskmgr_inner_errors.h +++ b/frameworks/common/include/bgtaskmgr_inner_errors.h @@ -37,7 +37,7 @@ enum : int { // Offset of background task manager sub-system's errcode base. constexpr ErrCode BGTASK_COMMON_ERR_OFFSET = ErrCodeOffset(SUBSYS_IAWARE, BGTASK_MODULE_COMMON); -//Bgtask Common Error Code Defined. +// Bgtask Common Error Code Defined. enum : int { ERR_BGTASK_SERVICE_NOT_READY = BGTASK_COMMON_ERR_OFFSET + 1, ERR_BGTASK_SERVICE_NOT_CONNECTED, @@ -48,7 +48,6 @@ enum : int { ERR_BGTASK_NOT_ALLOWED, ERR_BGTASK_OBJECT_EXISTS, }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_COMMON_INCLUDE_BGTASKMGR_INNER_ERRORS_H \ No newline at end of file diff --git a/frameworks/common/include/bgtaskmgr_log_wrapper.h b/frameworks/common/include/bgtaskmgr_log_wrapper.h index 3ebfd5e5..7bbe7e86 100644 --- a/frameworks/common/include/bgtaskmgr_log_wrapper.h +++ b/frameworks/common/include/bgtaskmgr_log_wrapper.h @@ -22,7 +22,6 @@ namespace OHOS { namespace BackgroundTaskMgr { - #ifndef LOG_DOMAIN #define LOG_DOMAIN 0xD001800 #endif diff --git a/frameworks/common/include/ipc_util.h b/frameworks/common/include/ipc_util.h index db7286d0..27d718ef 100644 --- a/frameworks/common/include/ipc_util.h +++ b/frameworks/common/include/ipc_util.h @@ -30,7 +30,7 @@ namespace BackgroundTaskMgr { BGTASK_LOGE("Failed to read "#data); \ return; \ } \ - } while(0) \ + } while(0) #define READ_PARCEL_WITH_RET(in, type, data, ret) \ do { \ @@ -38,7 +38,7 @@ namespace BackgroundTaskMgr { BGTASK_LOGE("Failed to read "#data); \ return (ret); \ } \ - } while(0) \ + } while(0) #define WRITE_PARCEL(out, type, data) \ do { \ @@ -46,7 +46,7 @@ namespace BackgroundTaskMgr { BGTASK_LOGE("Failed to write "#data); \ return; \ } \ - } while(0) \ + } while(0) #define WRITE_PARCEL_WITH_RET(out, type, data, ret) \ do { \ @@ -54,7 +54,7 @@ namespace BackgroundTaskMgr { BGTASK_LOGE("Failed to write "#data); \ return (ret); \ } \ - } while(0) \ + } while(0) static inline sptr GetSystemService(const std::string &name) { diff --git a/frameworks/include/background_task_manager.h b/frameworks/include/background_task_manager.h index 2e11363a..4e747596 100644 --- a/frameworks/include/background_task_manager.h +++ b/frameworks/include/background_task_manager.h @@ -65,7 +65,6 @@ private: sptr backgroundTaskMgrProxy_; sptr recipient_; }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_INCLUDE_BACKGROUND_TASK_MANAGER_H \ No newline at end of file diff --git a/frameworks/include/background_task_mgr_proxy.h b/frameworks/include/background_task_mgr_proxy.h index 4507218e..77187965 100644 --- a/frameworks/include/background_task_mgr_proxy.h +++ b/frameworks/include/background_task_mgr_proxy.h @@ -29,7 +29,7 @@ public: ~BackgroundTaskMgrProxy() override; DISALLOW_COPY_AND_MOVE(BackgroundTaskMgrProxy); - ErrCode RequestSuspendDelay(const std::u16string& reason, + ErrCode RequestSuspendDelay(const std::u16string& reason, const sptr& callback, std::shared_ptr &delayInfo) override; ErrCode CancelSuspendDelay(int32_t requestId) override; ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) override; diff --git a/frameworks/include/background_task_mgr_stub.h b/frameworks/include/background_task_mgr_stub.h index fe13308d..94750b40 100644 --- a/frameworks/include/background_task_mgr_stub.h +++ b/frameworks/include/background_task_mgr_stub.h @@ -33,7 +33,8 @@ public: ErrCode OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; private: - static const std::map> interfaces_; + static const std::map> interfaces_; ErrCode HandleRequestSuspendDelay(MessageParcel& data, MessageParcel& reply); ErrCode HandleCancelSuspendDelay(MessageParcel& data, MessageParcel& reply); ErrCode HandleGetRemainingDelayTime(MessageParcel& data, MessageParcel& reply); diff --git a/frameworks/include/expired_callback_stub.h b/frameworks/include/expired_callback_stub.h index f8eb0864..e935e203 100644 --- a/frameworks/include/expired_callback_stub.h +++ b/frameworks/include/expired_callback_stub.h @@ -22,7 +22,7 @@ namespace OHOS { namespace BackgroundTaskMgr { -class ExpiredCallbackStub : public IRemoteStub{ +class ExpiredCallbackStub : public IRemoteStub { public: ExpiredCallbackStub(); ~ExpiredCallbackStub() override; @@ -32,7 +32,6 @@ public: private: int32_t HandleOnExpired(MessageParcel& data); }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_INCLUDE_EXPIRED_CALLBACK_STUB_H \ No newline at end of file diff --git a/frameworks/include/ibackground_task_mgr.h b/frameworks/include/ibackground_task_mgr.h index 06de1cb9..d1ef00a8 100644 --- a/frameworks/include/ibackground_task_mgr.h +++ b/frameworks/include/ibackground_task_mgr.h @@ -35,7 +35,7 @@ public: ~IBackgroundTaskMgr() override = default; DISALLOW_COPY_AND_MOVE(IBackgroundTaskMgr); - virtual ErrCode RequestSuspendDelay(const std::u16string& reason, + virtual ErrCode RequestSuspendDelay(const std::u16string& reason, const sptr& callback, std::shared_ptr &delayInfo) = 0; virtual ErrCode CancelSuspendDelay(int32_t requestId) = 0; virtual ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) = 0; diff --git a/frameworks/include/iexpired_callback.h b/frameworks/include/iexpired_callback.h index f416098e..78d8a4c7 100644 --- a/frameworks/include/iexpired_callback.h +++ b/frameworks/include/iexpired_callback.h @@ -37,7 +37,6 @@ protected: ON_EXPIRED = FIRST_CALL_TRANSACTION, }; }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_INCLUDE_IEXPIRED_CALLBACK_H \ No newline at end of file diff --git a/frameworks/src/background_task_manager.cpp b/frameworks/src/background_task_manager.cpp index 4400d725..5066e3a0 100644 --- a/frameworks/src/background_task_manager.cpp +++ b/frameworks/src/background_task_manager.cpp @@ -24,9 +24,9 @@ namespace OHOS { namespace BackgroundTaskMgr { -BackgroundTaskManager::BackgroundTaskManager(){} +BackgroundTaskManager::BackgroundTaskManager() {} -BackgroundTaskManager::~BackgroundTaskManager(){} +BackgroundTaskManager::~BackgroundTaskManager() {} ErrCode BackgroundTaskManager::CancelSuspendDelay(int32_t requestId) { @@ -38,7 +38,7 @@ ErrCode BackgroundTaskManager::CancelSuspendDelay(int32_t requestId) } ErrCode BackgroundTaskManager::RequestSuspendDelay(const std::u16string &reason, - const ExpiredCallback &callback, std::shared_ptr &delayInfo) + const ExpiredCallback &callback, std::shared_ptr &delayInfo) { if (!GetBackgroundTaskManagerProxy()) { BGTASK_LOGE("GetBackgroundTaskManagerProxy failed."); @@ -120,7 +120,7 @@ bool BackgroundTaskManager::GetBackgroundTaskManagerProxy() if (recipient_ == nullptr) { return false; } - backgroundTaskMgrProxy_->AsObject()->AddDeathRecipient(recipient_); + backgroundTaskMgrProxy_->AsObject()->AddDeathRecipient(recipient_); return true; } @@ -145,7 +145,7 @@ ErrCode BackgroundTaskManager::ShellDump(const std::vector &dumpOpt BackgroundTaskManager::BgTaskMgrDeathRecipient::BgTaskMgrDeathRecipient(BackgroundTaskManager &backgroundTaskManager) : backgroundTaskManager_(backgroundTaskManager) {}; -BackgroundTaskManager::BgTaskMgrDeathRecipient::~BgTaskMgrDeathRecipient(){}; +BackgroundTaskManager::BgTaskMgrDeathRecipient::~BgTaskMgrDeathRecipient() {}; void BackgroundTaskManager::BgTaskMgrDeathRecipient::OnRemoteDied(const wptr &remote) { diff --git a/frameworks/src/background_task_mgr_proxy.cpp b/frameworks/src/background_task_mgr_proxy.cpp index 513109f2..046891da 100644 --- a/frameworks/src/background_task_mgr_proxy.cpp +++ b/frameworks/src/background_task_mgr_proxy.cpp @@ -28,8 +28,8 @@ BackgroundTaskMgrProxy::BackgroundTaskMgrProxy(const sptr& impl) :IRemoteProxy(impl) {} BackgroundTaskMgrProxy::~BackgroundTaskMgrProxy() {} -ErrCode BackgroundTaskMgrProxy::RequestSuspendDelay(const std::u16string& reason, - const sptr& callback, std::shared_ptr &delayInfo) +ErrCode BackgroundTaskMgrProxy::RequestSuspendDelay(const std::u16string& reason, + const sptr& callback, std::shared_ptr &delayInfo) { if (callback == nullptr) { BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s callback is null", __func__); @@ -187,7 +187,8 @@ ErrCode BackgroundTaskMgrProxy::UnsubscribeBackgroundTask(const sptr &dumpOption, std::vector &dumpInfo) +ErrCode BackgroundTaskMgrProxy::ShellDump(const std::vector &dumpOption, + std::vector &dumpInfo) { MessageParcel data; MessageParcel reply; @@ -218,7 +219,8 @@ ErrCode BackgroundTaskMgrProxy::ShellDump(const std::vector &dumpOp return result; } -ErrCode BackgroundTaskMgrProxy::InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply) +ErrCode BackgroundTaskMgrProxy::InnerTransact(uint32_t code, MessageOption &flags, + MessageParcel &data, MessageParcel &reply) { auto remote = Remote(); if (remote == nullptr) { diff --git a/frameworks/src/background_task_mgr_stub.cpp b/frameworks/src/background_task_mgr_stub.cpp index 48735805..cb936f9f 100644 --- a/frameworks/src/background_task_mgr_stub.cpp +++ b/frameworks/src/background_task_mgr_stub.cpp @@ -29,20 +29,27 @@ namespace BackgroundTaskMgr { const std::map> BackgroundTaskMgrStub::interfaces_ = { {BackgroundTaskMgrStub::REQUEST_SUSPEND_DELAY, - std::bind(&BackgroundTaskMgrStub::HandleRequestSuspendDelay, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + std::bind(&BackgroundTaskMgrStub::HandleRequestSuspendDelay, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {BackgroundTaskMgrStub::CANCEL_SUSPEND_DELAY, - std::bind(&BackgroundTaskMgrStub::HandleCancelSuspendDelay, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + std::bind(&BackgroundTaskMgrStub::HandleCancelSuspendDelay, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {BackgroundTaskMgrStub::GET_REMAINING_DELAY_TIME, - std::bind(&BackgroundTaskMgrStub::HandleGetRemainingDelayTime, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + std::bind(&BackgroundTaskMgrStub::HandleGetRemainingDelayTime, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {BackgroundTaskMgrStub::SUBSCRIBE_BACKGROUND_TASK, - std::bind(&BackgroundTaskMgrStub::HandleSubscribeBackgroundTask, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + std::bind(&BackgroundTaskMgrStub::HandleSubscribeBackgroundTask, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {BackgroundTaskMgrStub::UNSUBSCRIBE_BACKGROUND_TASK, - std::bind(&BackgroundTaskMgrStub::HandleUnsubscribeBackgroundTask, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + std::bind(&BackgroundTaskMgrStub::HandleUnsubscribeBackgroundTask, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {BackgroundTaskMgrStub::SHELL_DUMP, - std::bind(&BackgroundTaskMgrStub::HandleShellDump, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + std::bind(&BackgroundTaskMgrStub::HandleShellDump, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, }; -ErrCode BackgroundTaskMgrStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +ErrCode BackgroundTaskMgrStub::OnRemoteRequest(uint32_t code, + MessageParcel& data, MessageParcel& reply, MessageOption& option) { std::u16string descriptor = BackgroundTaskMgrStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); @@ -95,9 +102,7 @@ ErrCode BackgroundTaskMgrStub::HandleRequestSuspendDelay(MessageParcel& data, Me ErrCode BackgroundTaskMgrStub::HandleCancelSuspendDelay(MessageParcel& data, MessageParcel& reply) { int32_t id = data.ReadInt32(); - ErrCode result = CancelSuspendDelay(id); - if (!reply.WriteInt32(result)) { BGTASK_LOGE("Write result failed, ErrCode=%{public}d", result); return ERR_BGTASK_PARCELABLE_FAILED; @@ -163,7 +168,6 @@ ErrCode BackgroundTaskMgrStub::HandleShellDump(MessageParcel& data, MessageParce std::vector bgtaskmgrInfo; ErrCode result = ShellDump(dumpOption, bgtaskmgrInfo); - if (!reply.WriteInt32(result)) { BGTASK_LOGE("Write result failed, ErrCode=%{public}d", result); return ERR_BGTASK_PARCELABLE_FAILED; diff --git a/frameworks/src/background_task_subscriber_proxy.cpp b/frameworks/src/background_task_subscriber_proxy.cpp index 9f022bf0..cdd0a363 100644 --- a/frameworks/src/background_task_subscriber_proxy.cpp +++ b/frameworks/src/background_task_subscriber_proxy.cpp @@ -52,7 +52,7 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskStart(const std::shared_ptr& info) +void BackgroundTaskSubscriberProxy::OnTransientTaskEnd(const std::shared_ptr& info) { sptr remote = Remote(); if (remote == nullptr) { diff --git a/frameworks/src/background_task_subscriber_stub.cpp b/frameworks/src/background_task_subscriber_stub.cpp index 5bcb0088..c92ad604 100644 --- a/frameworks/src/background_task_subscriber_stub.cpp +++ b/frameworks/src/background_task_subscriber_stub.cpp @@ -36,13 +36,13 @@ int BackgroundTaskSubscriberStub::OnRemoteRequest(uint32_t code, std::u16string descriptor = BackgroundTaskSubscriberStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { - BGTASK_LOGE("BackgroundTaskSubscriberStub::%{public}s local descriptor not match remote.", __func__); + BGTASK_LOGE("Local descriptor not match remote."); return ERR_TRANSACTION_FAILED; } auto uid = IPCSkeleton::GetCallingUid(); if (uid >= APP_FIRST_UID) { - BGTASK_LOGE("BackgroundTaskSubscriberStub::OnRemoteRequest failed, illegal calling uid %d.", uid); + BGTASK_LOGE("OnRemoteRequest failed, illegal calling uid %d.", uid); return ERR_INVALID_DATA; } @@ -62,7 +62,7 @@ int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskStart(MessageParcel& { auto info = TransientTaskAppInfo::Unmarshalling(data); if (info == nullptr) { - BGTASK_LOGE("BackgroundTaskSubscriberStub::%{public}s read parcel failed.",__func__); + BGTASK_LOGE("Read parcel failed."); return ERR_INVALID_DATA; } OnTransientTaskStart(info); @@ -73,7 +73,7 @@ int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskEnd(MessageParcel& da { auto info = TransientTaskAppInfo::Unmarshalling(data); if (info == nullptr) { - BGTASK_LOGE("BackgroundTaskSubscriberStub::%{public}s read parcel failed.",__func__); + BGTASK_LOGE("Read parcel failed."); return ERR_INVALID_DATA; } OnTransientTaskEnd(info); diff --git a/frameworks/src/expired_callback_stub.cpp b/frameworks/src/expired_callback_stub.cpp index f4806115..3582ee00 100644 --- a/frameworks/src/expired_callback_stub.cpp +++ b/frameworks/src/expired_callback_stub.cpp @@ -24,7 +24,8 @@ namespace BackgroundTaskMgr { ExpiredCallbackStub::ExpiredCallbackStub() {} ExpiredCallbackStub::~ExpiredCallbackStub() {} -int ExpiredCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +int ExpiredCallbackStub::OnRemoteRequest(uint32_t code, + MessageParcel& data, MessageParcel& reply, MessageOption& option) { std::u16string descriptor = ExpiredCallbackStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); diff --git a/interfaces/innerkits/include/background_task_mgr_helper.h b/interfaces/innerkits/include/background_task_mgr_helper.h index b8954469..036369bd 100644 --- a/interfaces/innerkits/include/background_task_mgr_helper.h +++ b/interfaces/innerkits/include/background_task_mgr_helper.h @@ -38,7 +38,6 @@ public: */ static ErrCode UnsubscribeBackgroundTask(const BackgroundTaskSubscriber &subscriber); }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_BACKGROUND_TASK_MGR_HELPER_H \ No newline at end of file diff --git a/interfaces/innerkits/include/background_task_subscriber.h b/interfaces/innerkits/include/background_task_subscriber.h index 5238938a..8a885575 100644 --- a/interfaces/innerkits/include/background_task_subscriber.h +++ b/interfaces/innerkits/include/background_task_subscriber.h @@ -53,7 +53,7 @@ private: class BackgroundTaskSubscriberImpl final : public BackgroundTaskSubscriberStub { public: BackgroundTaskSubscriberImpl(BackgroundTaskSubscriber &subscriber); - ~BackgroundTaskSubscriberImpl(){}; + ~BackgroundTaskSubscriberImpl() {}; void OnTransientTaskStart(const std::shared_ptr& info) override; void OnTransientTaskEnd(const std::shared_ptr& info) override; @@ -69,7 +69,6 @@ private: friend class BackgroundTaskManager; }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_BACKGROUND_TASK_SUBSCRIBER_H \ No newline at end of file diff --git a/interfaces/innerkits/include/delay_suspend_info.h b/interfaces/innerkits/include/delay_suspend_info.h index 490e22f1..876300d4 100644 --- a/interfaces/innerkits/include/delay_suspend_info.h +++ b/interfaces/innerkits/include/delay_suspend_info.h @@ -26,17 +26,31 @@ public: bool Marshalling(Parcel& out) const override; - inline bool IsSameRequestId(int32_t requestId) const { return requestId_ == requestId; } - inline int32_t GetRequestId() const { return requestId_; } - inline int32_t GetActualDelayTime() const { return actualDelayTime_; } - inline void SetRequestId(int32_t id) { requestId_ = id; } - inline void SetActualDelayTime(int32_t time) { actualDelayTime_ = time; } + inline bool IsSameRequestId(int32_t requestId) const { + return requestId_ == requestId; + } + + inline int32_t GetRequestId() const { + return requestId_; + } + + inline int32_t GetActualDelayTime() const { + return actualDelayTime_; + } + + inline void SetRequestId(int32_t id) { + requestId_ = id; + } + + inline void SetActualDelayTime(int32_t time) { + actualDelayTime_ = time; + } private: bool ReadFromParcel(Parcel& in); - int32_t requestId_{-1}; - int32_t actualDelayTime_{0}; + int32_t requestId_ {-1}; + int32_t actualDelayTime_ {0}; }; } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/interfaces/innerkits/include/expired_callback.h b/interfaces/innerkits/include/expired_callback.h index f6c00412..68b6d4f4 100644 --- a/interfaces/innerkits/include/expired_callback.h +++ b/interfaces/innerkits/include/expired_callback.h @@ -44,7 +44,7 @@ private: class ExpiredCallbackImpl final : public ExpiredCallbackStub { public: ExpiredCallbackImpl(ExpiredCallback &callback); - ~ExpiredCallbackImpl(){}; + ~ExpiredCallbackImpl() {}; void OnExpired() override; public: @@ -59,7 +59,6 @@ private: friend class BackgroundTaskManager; }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_EXPIRED_CALLBACK_H \ No newline at end of file diff --git a/interfaces/innerkits/src/background_task_mgr_helper.cpp b/interfaces/innerkits/src/background_task_mgr_helper.cpp index 56e6ec10..5b57143d 100644 --- a/interfaces/innerkits/src/background_task_mgr_helper.cpp +++ b/interfaces/innerkits/src/background_task_mgr_helper.cpp @@ -31,6 +31,5 @@ ErrCode BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(const BackgroundTaskS { return DelayedSingleton::GetInstance()->UnsubscribeBackgroundTask(subscriber); } - } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/src/background_task_subscriber.cpp b/interfaces/innerkits/src/background_task_subscriber.cpp index 127c9f7e..9f33825e 100644 --- a/interfaces/innerkits/src/background_task_subscriber.cpp +++ b/interfaces/innerkits/src/background_task_subscriber.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace BackgroundTaskMgr { - BackgroundTaskSubscriber::BackgroundTaskSubscriber() { impl_ = new BackgroundTaskSubscriberImpl(*this); @@ -31,18 +30,19 @@ const sptr BackgroundTas return impl_; } -BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::BackgroundTaskSubscriberImpl(BackgroundTaskSubscriber &subscriber) - : subscriber_(subscriber) {} +BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl:: + BackgroundTaskSubscriberImpl(BackgroundTaskSubscriber &subscriber) : subscriber_(subscriber) {} -void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnTransientTaskStart(const std::shared_ptr& info) +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl:: + OnTransientTaskStart(const std::shared_ptr& info) { subscriber_.OnTransientTaskStart(info); } -void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnTransientTaskEnd(const std::shared_ptr& info) +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl:: + OnTransientTaskEnd(const std::shared_ptr& info) { subscriber_.OnTransientTaskEnd(info); } - } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/src/delay_suspend_info.cpp b/interfaces/innerkits/src/delay_suspend_info.cpp index 2ef7d0e5..bb2f392c 100644 --- a/interfaces/innerkits/src/delay_suspend_info.cpp +++ b/interfaces/innerkits/src/delay_suspend_info.cpp @@ -15,8 +15,6 @@ #include "delay_suspend_info.h" -#include - #include "ipc_util.h" #include "transient_task_log.h" diff --git a/interfaces/innerkits/src/expired_callback.cpp b/interfaces/innerkits/src/expired_callback.cpp index 02b37e6f..a7a43225 100644 --- a/interfaces/innerkits/src/expired_callback.cpp +++ b/interfaces/innerkits/src/expired_callback.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace BackgroundTaskMgr { - ExpiredCallback::ExpiredCallback() { impl_ = new ExpiredCallbackImpl(*this); diff --git a/interfaces/innerkits/src/transient_task_app_info.cpp b/interfaces/innerkits/src/transient_task_app_info.cpp index 052f8c7c..4f06dd7f 100644 --- a/interfaces/innerkits/src/transient_task_app_info.cpp +++ b/interfaces/innerkits/src/transient_task_app_info.cpp @@ -41,7 +41,7 @@ bool TransientTaskAppInfo::ReadFromParcel(MessageParcel& in) std::shared_ptr TransientTaskAppInfo::Unmarshalling(MessageParcel& in) { auto transientAppInfo = std::make_shared(); - if(!transientAppInfo->ReadFromParcel(in)) { + if (!transientAppInfo->ReadFromParcel(in)) { return nullptr; } return transientAppInfo; diff --git a/interfaces/kits/napi/include/common.h b/interfaces/kits/napi/include/common.h index feaf784c..00a13bb2 100644 --- a/interfaces/kits/napi/include/common.h +++ b/interfaces/kits/napi/include/common.h @@ -13,6 +13,9 @@ * limitations under the License. */ +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_COMMON_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_COMMON_H + #include #include "errors.h" @@ -21,13 +24,8 @@ #include "delay_suspend_info.h" -#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_COMMON_H -#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_COMMON_H - namespace OHOS { namespace BackgroundTaskMgr { -const std::int32_t STR_MAX_SIZE = 64; - struct CallbackPromiseInfo { napi_ref callback = nullptr; napi_deferred deferred = nullptr; @@ -36,7 +34,6 @@ struct CallbackPromiseInfo { }; class Common { - public: static napi_value NapiGetboolean(napi_env env, const bool &isValue); @@ -70,7 +67,6 @@ public: static napi_value SetDelaySuspendInfo( const napi_env &env, std::shared_ptr& delaySuspendInfo, napi_value &result); }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_COMMON_H \ No newline at end of file diff --git a/interfaces/kits/napi/include/init.h b/interfaces/kits/napi/include/init.h index 520a0817..435dccc6 100644 --- a/interfaces/kits/napi/include/init.h +++ b/interfaces/kits/napi/include/init.h @@ -45,7 +45,6 @@ napi_module _module = { .nm_priv = ((void *)0), .reserved = {0} }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_INIT_H \ No newline at end of file diff --git a/interfaces/kits/napi/include/request_suspend_delay.h b/interfaces/kits/napi/include/request_suspend_delay.h index b6a84912..f118c3df 100644 --- a/interfaces/kits/napi/include/request_suspend_delay.h +++ b/interfaces/kits/napi/include/request_suspend_delay.h @@ -24,7 +24,6 @@ namespace OHOS { namespace BackgroundTaskMgr { - class CallbackInstance : public ExpiredCallback { public: CallbackInstance(); @@ -49,10 +48,7 @@ struct CallbackInstancesInfo { CallbackInstance *callback = nullptr; }; -static std::mutex mutex_; - napi_value RequestSuspendDelay(napi_env env, napi_callback_info info); - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_REQUEST_SUSPEND_DELAY_H \ No newline at end of file diff --git a/interfaces/kits/napi/src/cancel_suspend_delay.cpp b/interfaces/kits/napi/src/cancel_suspend_delay.cpp index f8192fe8..c67bf73f 100644 --- a/interfaces/kits/napi/src/cancel_suspend_delay.cpp +++ b/interfaces/kits/napi/src/cancel_suspend_delay.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace BackgroundTaskMgr { - static const int32_t CANCEL_SUSPEND_DELAY_PARAMS = 1; napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, int32_t &requestId) diff --git a/interfaces/kits/napi/src/common.cpp b/interfaces/kits/napi/src/common.cpp index ff5fbe8e..95f0a343 100644 --- a/interfaces/kits/napi/src/common.cpp +++ b/interfaces/kits/napi/src/common.cpp @@ -20,6 +20,9 @@ namespace OHOS { namespace BackgroundTaskMgr { +const std::int32_t STR_MAX_SIZE = 64; +const std::int32_t EXPIRE_CALLBACK_PARAM_NUM = 1; +const std::int32_t ASYNC_CALLBACK_PARAM_NUM = 2; napi_value Common::NapiGetboolean(napi_env env, const bool &isValue) { @@ -53,10 +56,11 @@ void Common::SetCallback( napi_value callback = nullptr; napi_value resultout = nullptr; napi_get_reference_value(env, callbackIn, &callback); - napi_value results[2] = {nullptr}; + napi_value results[ASYNC_CALLBACK_PARAM_NUM] = {nullptr}; results[0] = GetCallbackErrorValue(env, errorCode); results[1] = result; - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, 2, &results[0], &resultout)); + NAPI_CALL_RETURN_VOID(env, + napi_call_function(env, undefined, callback, ASYNC_CALLBACK_PARAM_NUM, &results[0], &resultout)); } void Common::SetCallback(const napi_env &env, const napi_ref &callbackIn, const napi_value &result) @@ -69,7 +73,8 @@ void Common::SetCallback(const napi_env &env, const napi_ref &callbackIn, const napi_value res = nullptr; res = GetExpireCallbackValue(env, 0, result); napi_get_reference_value(env, callbackIn, &callback); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, 1, &res, &resultout)); + NAPI_CALL_RETURN_VOID(env, + napi_call_function(env, undefined, callback, EXPIRE_CALLBACK_PARAM_NUM, &res, &resultout)); } napi_value Common::GetExpireCallbackValue(napi_env env, int errCode, const napi_value &value) @@ -171,7 +176,7 @@ void Common::PaddingCallbackPromiseInfo( } napi_value Common::SetDelaySuspendInfo( - const napi_env &env, std::shared_ptr& delaySuspendInfo, napi_value &result) + const napi_env &env, std::shared_ptr& delaySuspendInfo, napi_value &result) { if (delaySuspendInfo == nullptr) { BGTASK_LOGI("delaySuspendInfo is nullptr"); diff --git a/interfaces/kits/napi/src/get_remaining_delay_time.cpp b/interfaces/kits/napi/src/get_remaining_delay_time.cpp index 6a3d63d0..8a23a642 100644 --- a/interfaces/kits/napi/src/get_remaining_delay_time.cpp +++ b/interfaces/kits/napi/src/get_remaining_delay_time.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace BackgroundTaskMgr { - static const int32_t GET_REMAINING_DELAY_TIME_MIN_PARAMS = 1; static const int32_t GET_REMAINING_DELAY_TIME_PARAMS = 2; @@ -37,7 +36,7 @@ struct AsyncCallbackInfoGetRemainingDelayTime { struct GetRemainingDelayTimeParamsInfo { int32_t requestId; napi_ref callback = nullptr; -}; +}; napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetRemainingDelayTimeParamsInfo ¶ms) { diff --git a/interfaces/kits/napi/src/init.cpp b/interfaces/kits/napi/src/init.cpp index af89ddb1..03918a74 100644 --- a/interfaces/kits/napi/src/init.cpp +++ b/interfaces/kits/napi/src/init.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace BackgroundTaskMgr { - EXTERN_C_START napi_value BackgroundTaskMgrInit(napi_env env, napi_value exports) @@ -59,6 +58,5 @@ __attribute__((constructor)) void RegisterModule(void) napi_module_register(&_module); } EXTERN_C_END - } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/src/request_suspend_delay.cpp b/interfaces/kits/napi/src/request_suspend_delay.cpp index 7d7ffe68..3d5bed19 100644 --- a/interfaces/kits/napi/src/request_suspend_delay.cpp +++ b/interfaces/kits/napi/src/request_suspend_delay.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace BackgroundTaskMgr { - static const int32_t REQUEST_SUSPEND_DELAY_PARAMS = 2; CallbackInstance::CallbackInstance() @@ -122,6 +121,5 @@ napi_value RequestSuspendDelay(napi_env env, napi_callback_info info) } return result; } - } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/services/core/include/background_task_mgr_service.h b/services/core/include/background_task_mgr_service.h index 8653b81a..edcdf06b 100644 --- a/services/core/include/background_task_mgr_service.h +++ b/services/core/include/background_task_mgr_service.h @@ -40,7 +40,7 @@ enum class ServiceRunningState { }; class BackgroundTaskMgrService final : public SystemAbility, public BackgroundTaskMgrStub, - public std::enable_shared_from_this{ + public std::enable_shared_from_this { DISALLOW_COPY_AND_MOVE(BackgroundTaskMgrService); DECLARE_SYSTEM_ABILITY(BackgroundTaskMgrService); DECLARE_DELAYED_SINGLETON(BackgroundTaskMgrService); @@ -49,7 +49,7 @@ public: void OnStart() override final; void OnStop() override final; - ErrCode RequestSuspendDelay(const std::u16string& reason, + ErrCode RequestSuspendDelay(const std::u16string& reason, const sptr& callback, std::shared_ptr &delayInfo) override; ErrCode CancelSuspendDelay(int32_t requestId) override; ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) override; @@ -68,7 +68,6 @@ private: private: ServiceRunningState state_ {ServiceRunningState::STATE_NOT_START}; }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CORE_INCLUDE_BACKGROUND_TASK_MGR_SERVICE_H \ No newline at end of file diff --git a/services/core/src/background_task_mgr_service.cpp b/services/core/src/background_task_mgr_service.cpp index 67beb581..7b1f9894 100644 --- a/services/core/src/background_task_mgr_service.cpp +++ b/services/core/src/background_task_mgr_service.cpp @@ -16,8 +16,6 @@ #include "background_task_mgr_service.h" #include -#include -#include #include "ability_manager_client.h" #include "bundle_constants.h" @@ -29,7 +27,6 @@ namespace OHOS { namespace BackgroundTaskMgr { - namespace { static const std::string TRANSIENT_TASK_DUMP = "-T"; const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility( @@ -71,8 +68,8 @@ void BackgroundTaskMgrService::OnStop() BGTASK_LOGI("background task manager stop"); } -ErrCode BackgroundTaskMgrService::RequestSuspendDelay(const std::u16string& reason, - const sptr& callback, std::shared_ptr &delayInfo) +ErrCode BackgroundTaskMgrService::RequestSuspendDelay(const std::u16string& reason, + const sptr& callback, std::shared_ptr &delayInfo) { return DelayedSingleton::GetInstance()->RequestSuspendDelay(reason, callback, delayInfo); } @@ -117,7 +114,8 @@ void BackgroundTaskMgrService::HandleSubscriberDeath(const wptr& DelayedSingleton::GetInstance()->HandleSubscriberDeath(remote); } -ErrCode BackgroundTaskMgrService::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) +ErrCode BackgroundTaskMgrService::ShellDump(const std::vector &dumpOption, + std::vector &dumpInfo) { ErrCode ret = ERR_OK; if (dumpOption[0] == TRANSIENT_TASK_DUMP) { @@ -125,6 +123,5 @@ ErrCode BackgroundTaskMgrService::ShellDump(const std::vector &dump } return ret; } - } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/services/test/unittest/background_task_mgr_service_test.cpp b/services/test/unittest/background_task_mgr_service_test.cpp index d1e44697..fb641cc2 100644 --- a/services/test/unittest/background_task_mgr_service_test.cpp +++ b/services/test/unittest/background_task_mgr_service_test.cpp @@ -25,13 +25,12 @@ using namespace testing::ext; namespace OHOS { namespace BackgroundTaskMgr { - class BackgroundTaskMgrServiceTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){}; + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; + void TearDown() {}; }; /** diff --git a/services/test/unittest/bg_transient_task_mgr_test.cpp b/services/test/unittest/bg_transient_task_mgr_test.cpp index 8d5e554f..01283a6c 100644 --- a/services/test/unittest/bg_transient_task_mgr_test.cpp +++ b/services/test/unittest/bg_transient_task_mgr_test.cpp @@ -15,7 +15,7 @@ #include #include -#include +#include #define private public #include "bg_transient_task_mgr.h" @@ -25,7 +25,6 @@ using namespace testing::ext; namespace OHOS { namespace BackgroundTaskMgr { - class TestBackgroundTaskSubscriber : public BackgroundTaskSubscriber { public: void OnTransientTaskStart(const std::shared_ptr& info) override @@ -36,10 +35,10 @@ public: class BgTransientTaskMgrTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){}; + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; + void TearDown() {}; }; /** diff --git a/services/test/unittest/mock/mock_event_handler.cpp b/services/test/unittest/mock/mock_event_handler.cpp index 07edc8ba..e317c0c5 100644 --- a/services/test/unittest/mock/mock_event_handler.cpp +++ b/services/test/unittest/mock/mock_event_handler.cpp @@ -14,11 +14,9 @@ */ #include "event_handler.h" -#include namespace OHOS { namespace AppExecFwk { - std::shared_ptr EventHandler::Current() { const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); diff --git a/services/transient_task/include/bg_transient_task_mgr.h b/services/transient_task/include/bg_transient_task_mgr.h index 6903e344..61f286be 100644 --- a/services/transient_task/include/bg_transient_task_mgr.h +++ b/services/transient_task/include/bg_transient_task_mgr.h @@ -13,8 +13,8 @@ * limitations under the License. */ - #ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_TRANSIENT_TASK_INCLUDE_BG_TRANSIENT_TASK_MGR_H - #define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_TRANSIENT_TASK_INCLUDE_BG_TRANSIENT_TASK_MGR_H +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_TRANSIENT_TASK_INCLUDE_BG_TRANSIENT_TASK_MGR_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_TRANSIENT_TASK_INCLUDE_BG_TRANSIENT_TASK_MGR_H #include #include diff --git a/services/transient_task/include/decision_maker.h b/services/transient_task/include/decision_maker.h index f1a12b92..4a7fd28e 100644 --- a/services/transient_task/include/decision_maker.h +++ b/services/transient_task/include/decision_maker.h @@ -69,18 +69,18 @@ private: DecisionMaker &decisionMaker_; }; - private: - class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient { - public: - AppMgrDeathRecipient(DecisionMaker &decisionMaker) : decisionMaker_(decisionMaker) {} +private: + class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient { + public: + AppMgrDeathRecipient(DecisionMaker &decisionMaker) : decisionMaker_(decisionMaker) {} - ~AppMgrDeathRecipient() {}; + ~AppMgrDeathRecipient() {}; - virtual void OnRemoteDied(const wptr &object) override; + virtual void OnRemoteDied(const wptr &object) override; - private: - DecisionMaker &decisionMaker_; - }; + private: + DecisionMaker &decisionMaker_; + }; private: int32_t NewDelaySuspendRequestId(); diff --git a/services/transient_task/include/delay_suspend_info_ex.h b/services/transient_task/include/delay_suspend_info_ex.h index 929de153..492bc550 100644 --- a/services/transient_task/include/delay_suspend_info_ex.h +++ b/services/transient_task/include/delay_suspend_info_ex.h @@ -48,7 +48,7 @@ public: } private: - const int32_t ADVANCE_TIME = 6 * MSEC_PER_SEC; //6s + const int32_t ADVANCE_TIME = 6 * MSEC_PER_SEC; // 6s int32_t pid_ {-1}; int64_t baseTime_ {0}; int64_t spendTime_ {0}; diff --git a/services/transient_task/include/event_info.h b/services/transient_task/include/event_info.h index dd3f17f7..7f13e8fe 100644 --- a/services/transient_task/include/event_info.h +++ b/services/transient_task/include/event_info.h @@ -21,9 +21,9 @@ #include -#include "event_info.h" #include "common_event_manager.h" #include "common_event_support.h" +#include "event_info.h" #include "want.h" namespace OHOS { @@ -38,7 +38,7 @@ enum EventId { EVENT_MAX, }; -class EventInfo{ +class EventInfo { public: EventInfo() {} virtual ~EventInfo() = default; diff --git a/services/transient_task/include/key_info.h b/services/transient_task/include/key_info.h index 80dbd402..8df78694 100644 --- a/services/transient_task/include/key_info.h +++ b/services/transient_task/include/key_info.h @@ -16,12 +16,11 @@ #ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_TRANSIENT_TASK_INCLUDE_KEY_INFO_H #define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_TRANSIENT_TASK_INCLUDE_KEY_INFO_H -#include #include namespace OHOS { namespace BackgroundTaskMgr { -class KeyInfo{ +class KeyInfo { public: KeyInfo(const std::string& pkg, const int32_t& uid, const int32_t& pid = -1): pkg_(pkg), uid_(uid), pid_(pid) {} ~KeyInfo() = default; @@ -41,7 +40,7 @@ public: return (pkg == pkg_ && uid == uid_); } - inline const std::string& GetPkg() const + inline const std::string& GetPkg() const { return pkg_; } @@ -67,14 +66,12 @@ private: int32_t pid_ {-1}; }; -struct KeyInfoComp -{ +struct KeyInfoComp { bool operator()(const std::shared_ptr x, const std::shared_ptr y) const { return (x->GetPkg() < y->GetPkg()) || ((x->GetPkg() == y->GetPkg()) && (x->GetUid() < y->GetUid())); } }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_TRANSIENT_TASK_INCLUDE_KEY_INFO_H \ No newline at end of file diff --git a/services/transient_task/include/pkg_delay_suspend_info.h b/services/transient_task/include/pkg_delay_suspend_info.h index 5524a3a6..684550a2 100644 --- a/services/transient_task/include/pkg_delay_suspend_info.h +++ b/services/transient_task/include/pkg_delay_suspend_info.h @@ -76,7 +76,7 @@ private: int32_t baseTime_ {0}; bool isCounting_ {false}; shared_ptr timerManager_ {nullptr}; - vector> requestList_; + vector> requestList_; }; } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/services/transient_task/include/time_provider.h b/services/transient_task/include/time_provider.h index e6a6eaee..f9798fa9 100644 --- a/services/transient_task/include/time_provider.h +++ b/services/transient_task/include/time_provider.h @@ -26,7 +26,7 @@ enum ClockType { CLOCK_TYPE_MONOTONIC = CLOCK_MONOTONIC, }; -enum TimeConstant : int64_t { +enum TimeConstant : int64_t { NSEC_PER_MIN = 60000000000LL, NSEC_PER_SEC = 1000000000LL, NSEC_PER_MSEC = 1000000LL, diff --git a/services/transient_task/src/bg_transient_task_mgr.cpp b/services/transient_task/src/bg_transient_task_mgr.cpp index c8873305..39c38325 100644 --- a/services/transient_task/src/bg_transient_task_mgr.cpp +++ b/services/transient_task/src/bg_transient_task_mgr.cpp @@ -169,8 +169,8 @@ ErrCode BgTransientTaskMgr::RequestSuspendDelay(const std::u16string& reason, BGTASK_LOGE("request suspend failed, callback is already exists, not allow."); return ERR_BGTASK_NOT_ALLOWED; } - BGTASK_LOGI("request suspend success, pkg : %{public}s, uid : %{public}d, requestId: %{public}d, delayTime: %{public}d", - name.c_str(), uid, infoEx->GetRequestId(), infoEx->GetActualDelayTime()); + BGTASK_LOGI("request suspend success, pkg : %{public}s, uid : %{public}d, requestId: %{public}d," + "delayTime: %{public}d", name.c_str(), uid, infoEx->GetRequestId(), infoEx->GetActualDelayTime()); expiredCallbackMap_[infoEx->GetRequestId()] = callback; keyInfoMap_[infoEx->GetRequestId()] = keyInfo; if (callbackDeathRecipient_ != nullptr) { @@ -382,7 +382,7 @@ void BgTransientTaskMgr::HandleSubscriberDeath(const wptr& remote void BgTransientTaskMgr::HandleRequestExpired(const int32_t requestId) { BGTASK_LOGI("request expired, id : %{public}d", requestId); - + std::lock_guard lock(expiredCallbackLock_); auto callbackIter = expiredCallbackMap_.find(requestId); if (callbackIter == expiredCallbackMap_.end()) { diff --git a/services/transient_task/src/decision_maker.cpp b/services/transient_task/src/decision_maker.cpp index 13a4a7ac..b038c631 100644 --- a/services/transient_task/src/decision_maker.cpp +++ b/services/transient_task/src/decision_maker.cpp @@ -27,7 +27,6 @@ using namespace std; namespace OHOS { namespace BackgroundTaskMgr { - DecisionMaker::DecisionMaker(const shared_ptr& timerManager, const shared_ptr& device) { timerManager_ = timerManager; @@ -98,7 +97,8 @@ void DecisionMaker::AppMgrDeathRecipient::OnRemoteDied(const wptr decisionMaker_.GetAppMgrProxy(); } -void DecisionMaker::ApplicationStateObserver::OnForegroundApplicationChanged(const AppExecFwk::AppStateData &appStateData) +void DecisionMaker::ApplicationStateObserver:: + OnForegroundApplicationChanged(const AppExecFwk::AppStateData &appStateData) { lock_guard lock(decisionMaker_.lock_); diff --git a/services/transient_task/src/delay_suspend_info_ex.cpp b/services/transient_task/src/delay_suspend_info_ex.cpp index b0b659d9..dcd0ce4d 100644 --- a/services/transient_task/src/delay_suspend_info_ex.cpp +++ b/services/transient_task/src/delay_suspend_info_ex.cpp @@ -42,14 +42,14 @@ int32_t DelaySuspendInfoEx::GetAdvanceCallbackTime() void DelaySuspendInfoEx::StartAccounting() { - if(baseTime_ == 0) { + if (baseTime_ == 0) { baseTime_ = TimeProvider::GetCurrentTime(); } } void DelaySuspendInfoEx::StopAccounting() { - if(baseTime_ != 0) { + if (baseTime_ != 0) { spendTime_ += TimeProvider::GetCurrentTime() - baseTime_; baseTime_ = 0; } diff --git a/services/transient_task/src/device_info_manager.cpp b/services/transient_task/src/device_info_manager.cpp index fdbbfe0f..e9426f1b 100644 --- a/services/transient_task/src/device_info_manager.cpp +++ b/services/transient_task/src/device_info_manager.cpp @@ -31,26 +31,25 @@ void DeviceInfoManager::OnInputEvent(const EventInfo& eventInfo) } switch (eventInfo.GetEventId()) { - case EVENT_SCREEN_ON: - isScreenOn_ = true; - break; - case EVENT_SCREEN_OFF: - isScreenOn_ = false; - isScreenUnlock_ = false; - break; - case EVENT_SCREEN_UNLOCK: - isScreenUnlock_ = true; - break; - case EVENT_BATTERY_LOW: - isLowPowerMode_ = true; - break; - case EVENT_BATTERY_OKAY: - isLowPowerMode_ = false; - break; - default: - break; + case EVENT_SCREEN_ON: + isScreenOn_ = true; + break; + case EVENT_SCREEN_OFF: + isScreenOn_ = false; + isScreenUnlock_ = false; + break; + case EVENT_SCREEN_UNLOCK: + isScreenUnlock_ = true; + break; + case EVENT_BATTERY_LOW: + isLowPowerMode_ = true; + break; + case EVENT_BATTERY_OKAY: + isLowPowerMode_ = false; + break; + default: + break; } } - } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/services/transient_task/src/event_hub.cpp b/services/transient_task/src/event_hub.cpp index 5151119e..eec5c649 100644 --- a/services/transient_task/src/event_hub.cpp +++ b/services/transient_task/src/event_hub.cpp @@ -38,7 +38,7 @@ static std::map g_actionMap = { std::shared_ptr EventHub::RegisterEvent(InputManager& inputManager) { auto skill = std::make_shared(); - for(auto &actionPair : g_actionMap) { + for (auto &actionPair : g_actionMap) { skill->AddEvent(actionPair.first); } auto info = std::make_shared(*skill); diff --git a/services/transient_task/src/pkg_delay_suspend_info.cpp b/services/transient_task/src/pkg_delay_suspend_info.cpp index bb011bb1..a1341886 100644 --- a/services/transient_task/src/pkg_delay_suspend_info.cpp +++ b/services/transient_task/src/pkg_delay_suspend_info.cpp @@ -36,7 +36,7 @@ bool PkgDelaySuspendInfo::IsAllowRequest() } UpdateQuota(); - if(quota_ >= MIN_ALLOW_QUOTA_TIME) { + if (quota_ >= MIN_ALLOW_QUOTA_TIME) { return true; } @@ -125,7 +125,7 @@ void PkgDelaySuspendInfo::StopAccountingAll() isCounting_ = false; } -void PkgDelaySuspendInfo::UpdateQuota(bool reset) +void PkgDelaySuspendInfo::UpdateQuota(bool reset) { spendTime_ = isCounting_ ? (TimeProvider::GetCurrentTime() - baseTime_) : 0; quota_ -= spendTime_; diff --git a/services/transient_task/src/suspend_controller.cpp b/services/transient_task/src/suspend_controller.cpp index e2bfa097..cabd951f 100644 --- a/services/transient_task/src/suspend_controller.cpp +++ b/services/transient_task/src/suspend_controller.cpp @@ -24,13 +24,13 @@ namespace BackgroundTaskMgr { void SuspendController::RequestSuspendDelay(const std::shared_ptr& key) { // do delayed suspend - BGTASK_LOGI("Add delayed suspend app uid: %{public}d, name: %{public}s",key->GetUid(), key->GetPkg().c_str()); + BGTASK_LOGI("Add delayed suspend app uid: %{public}d, name: %{public}s", key->GetUid(), key->GetPkg().c_str()); } void SuspendController::CancelSuspendDelay(const std::shared_ptr& key) { // cancel delayed suspend - BGTASK_LOGI("Remove delayed suspend app uid: %{public}d, name: %{public}s",key->GetUid(), key->GetPkg().c_str()); + BGTASK_LOGI("Remove delayed suspend app uid: %{public}d, name: %{public}s", key->GetUid(), key->GetPkg().c_str()); } } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/services/transient_task/src/watchdog.cpp b/services/transient_task/src/watchdog.cpp index 70db2b9a..4be8f1ad 100644 --- a/services/transient_task/src/watchdog.cpp +++ b/services/transient_task/src/watchdog.cpp @@ -66,7 +66,7 @@ void Watchdog::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event) } else { BGTASK_LOGI("handle application background, kill it, requestId: %{public}d", requestId); // do kill - if(!KillApplicationByUid(info->GetPkg(), info->GetUid())) { + if (!KillApplicationByUid(info->GetPkg(), info->GetUid())) { BGTASK_LOGE("fail to kill running application"); } } diff --git a/utils/dump/include/bgtaskmgr_shell_command.h b/utils/dump/include/bgtaskmgr_shell_command.h index 1d20d35c..2f5fb540 100644 --- a/utils/dump/include/bgtaskmgr_shell_command.h +++ b/utils/dump/include/bgtaskmgr_shell_command.h @@ -22,11 +22,10 @@ namespace OHOS { namespace BackgroundTaskMgr { - class BgtaskmgrShellCommand : public ShellCommand { public: BgtaskmgrShellCommand(int argc, char *argv[]); - ~BgtaskmgrShellCommand() override{}; + ~BgtaskmgrShellCommand() override {}; private: ErrCode CreateCommandMap() override; @@ -38,7 +37,6 @@ private: private: std::shared_ptr btm_; }; - } // namespace BackgroundTaskMgr } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_UTILS_DUMP_INCLUDE_BGTASKMGR_SHELL_COMMAND_H \ No newline at end of file diff --git a/utils/dump/src/bgtaskmgr_shell_command.cpp b/utils/dump/src/bgtaskmgr_shell_command.cpp index 0b3ff2e5..3e6a44dd 100644 --- a/utils/dump/src/bgtaskmgr_shell_command.cpp +++ b/utils/dump/src/bgtaskmgr_shell_command.cpp @@ -28,7 +28,6 @@ namespace OHOS { namespace BackgroundTaskMgr { namespace { - static const struct option OPTIONS[] = { {"help", no_argument, nullptr, 'h'}, {"transient", no_argument, nullptr, 'T'}, @@ -125,6 +124,5 @@ ErrCode BgtaskmgrShellCommand::RunAsDumpCommand() return ret; } - } // namespace BackgroundTaskMgr -} // namespace OHOS +} // namespace OHOS \ No newline at end of file -- Gitee From 59fce98af95e84cbf8f2e66f64ef4382828fbe85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Wed, 19 Jan 2022 15:31:13 +0800 Subject: [PATCH 02/77] code check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- frameworks/common/include/ipc_util.h | 8 ++++---- frameworks/src/background_task_mgr_stub.cpp | 12 ++++++------ interfaces/innerkits/include/delay_suspend_info.h | 15 ++++++++++----- .../innerkits/src/background_task_subscriber.cpp | 12 ++++++------ services/transient_task/src/decision_maker.cpp | 4 ++-- 5 files changed, 28 insertions(+), 23 deletions(-) diff --git a/frameworks/common/include/ipc_util.h b/frameworks/common/include/ipc_util.h index 27d718ef..98d25f33 100644 --- a/frameworks/common/include/ipc_util.h +++ b/frameworks/common/include/ipc_util.h @@ -30,7 +30,7 @@ namespace BackgroundTaskMgr { BGTASK_LOGE("Failed to read "#data); \ return; \ } \ - } while(0) + } while (0) #define READ_PARCEL_WITH_RET(in, type, data, ret) \ do { \ @@ -38,7 +38,7 @@ namespace BackgroundTaskMgr { BGTASK_LOGE("Failed to read "#data); \ return (ret); \ } \ - } while(0) + } while (0) #define WRITE_PARCEL(out, type, data) \ do { \ @@ -46,7 +46,7 @@ namespace BackgroundTaskMgr { BGTASK_LOGE("Failed to write "#data); \ return; \ } \ - } while(0) + } while (0) #define WRITE_PARCEL_WITH_RET(out, type, data, ret) \ do { \ @@ -54,7 +54,7 @@ namespace BackgroundTaskMgr { BGTASK_LOGE("Failed to write "#data); \ return (ret); \ } \ - } while(0) + } while (0) static inline sptr GetSystemService(const std::string &name) { diff --git a/frameworks/src/background_task_mgr_stub.cpp b/frameworks/src/background_task_mgr_stub.cpp index cb936f9f..b48904f9 100644 --- a/frameworks/src/background_task_mgr_stub.cpp +++ b/frameworks/src/background_task_mgr_stub.cpp @@ -30,22 +30,22 @@ const std::map BackgroundTas return impl_; } -BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl:: - BackgroundTaskSubscriberImpl(BackgroundTaskSubscriber &subscriber) : subscriber_(subscriber) {} +BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::BackgroundTaskSubscriberImpl( + BackgroundTaskSubscriber &subscriber) : subscriber_(subscriber) {} -void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl:: - OnTransientTaskStart(const std::shared_ptr& info) +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnTransientTaskStart( + const std::shared_ptr& info) { subscriber_.OnTransientTaskStart(info); } -void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl:: - OnTransientTaskEnd(const std::shared_ptr& info) +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnTransientTaskEnd( + const std::shared_ptr& info) { subscriber_.OnTransientTaskEnd(info); } diff --git a/services/transient_task/src/decision_maker.cpp b/services/transient_task/src/decision_maker.cpp index b038c631..7d16d212 100644 --- a/services/transient_task/src/decision_maker.cpp +++ b/services/transient_task/src/decision_maker.cpp @@ -97,8 +97,8 @@ void DecisionMaker::AppMgrDeathRecipient::OnRemoteDied(const wptr decisionMaker_.GetAppMgrProxy(); } -void DecisionMaker::ApplicationStateObserver:: - OnForegroundApplicationChanged(const AppExecFwk::AppStateData &appStateData) +void DecisionMaker::ApplicationStateObserver::OnForegroundApplicationChanged( + const AppExecFwk::AppStateData &appStateData) { lock_guard lock(decisionMaker_.lock_); -- Gitee From a0d9dc097a3ca69ee9ad0c630930620e6da1d4a5 Mon Sep 17 00:00:00 2001 From: njupthan Date: Wed, 19 Jan 2022 08:35:38 +0000 Subject: [PATCH 03/77] Fix atomic ability part name change Signed-off-by: njupthan --- services/BUILD.gn | 3 ++- services/test/unittest/BUILD.gn | 3 ++- test/systemtest/BUILD.gn | 3 ++- utils/dump/BUILD.gn | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/services/BUILD.gn b/services/BUILD.gn index d7f3ff19..4d83b174 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -47,7 +47,8 @@ ohos_shared_library("bgtaskmgr_service") { ] external_deps = [ - "aafwk_standard:want", + "ability_runtime:app_manager", + "ability_runtime:want", "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", "ces_standard:cesfwk_innerkits", diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 32ec7123..f4c3cd38 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -42,7 +42,8 @@ ohos_unittest("bgtask_unit_test") { ] external_deps = [ - "aafwk_standard:want", + "ability_runtime:app_manager", + "ability_runtime:want", "appexecfwk_standard:appexecfwk_base", "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", diff --git a/test/systemtest/BUILD.gn b/test/systemtest/BUILD.gn index 45a1939d..94ba225c 100644 --- a/test/systemtest/BUILD.gn +++ b/test/systemtest/BUILD.gn @@ -46,7 +46,8 @@ ohos_systemtest("BgtaskDumpTest") { ] external_deps = [ - "aafwk_standard:want", + "ability_runtime:app_manager", + "ability_runtime:want", "appexecfwk_standard:appexecfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/utils/dump/BUILD.gn b/utils/dump/BUILD.gn index f5af1671..007f7aec 100644 --- a/utils/dump/BUILD.gn +++ b/utils/dump/BUILD.gn @@ -40,7 +40,7 @@ ohos_executable("bgtask") { configs = [] external_deps = [ - "aafwk_standard:want", + "ability_runtime:want", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "samgr_standard:samgr_proxy", -- Gitee From 5485e3d898683bff2fd0b2a1ffaaad2eb07a952e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 20 Jan 2022 09:58:08 +0800 Subject: [PATCH 04/77] code check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- bundle.json | 2 +- services/transient_task/include/event_info.h | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/bundle.json b/bundle.json index 12a70c53..8bbaabf2 100644 --- a/bundle.json +++ b/bundle.json @@ -23,7 +23,7 @@ "ram": "10240KB", "deps": { "components": [ - "aafwk_standard", + "ability_runtime", "appexecfwk_standard", "ces_standard", "hiviewdfx_hilog_native", diff --git a/services/transient_task/include/event_info.h b/services/transient_task/include/event_info.h index 7f13e8fe..434d8f18 100644 --- a/services/transient_task/include/event_info.h +++ b/services/transient_task/include/event_info.h @@ -23,9 +23,10 @@ #include "common_event_manager.h" #include "common_event_support.h" -#include "event_info.h" #include "want.h" +#include "event_info.h" + namespace OHOS { namespace BackgroundTaskMgr { enum EventId { -- Gitee From 4d15a6fb9e3e7be7d50d09e9b0b68d0fb50daef8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 20 Jan 2022 11:17:54 +0800 Subject: [PATCH 05/77] NAPI check requestId MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- frameworks/src/background_task_mgr_proxy.cpp | 2 +- interfaces/kits/napi/include/common.h | 2 +- interfaces/kits/napi/src/cancel_suspend_delay.cpp | 6 +++++- interfaces/kits/napi/src/common.cpp | 9 ++++++++- interfaces/kits/napi/src/get_remaining_delay_time.cpp | 7 ++++++- 5 files changed, 21 insertions(+), 5 deletions(-) diff --git a/frameworks/src/background_task_mgr_proxy.cpp b/frameworks/src/background_task_mgr_proxy.cpp index 046891da..5c7ef321 100644 --- a/frameworks/src/background_task_mgr_proxy.cpp +++ b/frameworks/src/background_task_mgr_proxy.cpp @@ -27,7 +27,7 @@ namespace BackgroundTaskMgr { BackgroundTaskMgrProxy::BackgroundTaskMgrProxy(const sptr& impl) :IRemoteProxy(impl) {} BackgroundTaskMgrProxy::~BackgroundTaskMgrProxy() {} - + ErrCode BackgroundTaskMgrProxy::RequestSuspendDelay(const std::u16string& reason, const sptr& callback, std::shared_ptr &delayInfo) { diff --git a/interfaces/kits/napi/include/common.h b/interfaces/kits/napi/include/common.h index 00a13bb2..37c94d6c 100644 --- a/interfaces/kits/napi/include/common.h +++ b/interfaces/kits/napi/include/common.h @@ -18,10 +18,10 @@ #include -#include "errors.h" #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "bgtaskmgr_inner_errors.h" #include "delay_suspend_info.h" namespace OHOS { diff --git a/interfaces/kits/napi/src/cancel_suspend_delay.cpp b/interfaces/kits/napi/src/cancel_suspend_delay.cpp index c67bf73f..e0f5c619 100644 --- a/interfaces/kits/napi/src/cancel_suspend_delay.cpp +++ b/interfaces/kits/napi/src/cancel_suspend_delay.cpp @@ -33,7 +33,11 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[0] :requestId if (Common::GetInt32NumberValue(env, argv[0], requestId) == nullptr) { - BGTASK_LOGE("ParseParameters failed, requestId is nullptr "); + BGTASK_LOGE("ParseParameters failed, requestId is nullptr."); + return nullptr; + } + if (requestId <= 0) { + BGTASK_LOGE("ParseParameters failed, requestId is illegal."); return nullptr; } return Common::NapiGetNull(env); diff --git a/interfaces/kits/napi/src/common.cpp b/interfaces/kits/napi/src/common.cpp index 95f0a343..9846f9e3 100644 --- a/interfaces/kits/napi/src/common.cpp +++ b/interfaces/kits/napi/src/common.cpp @@ -117,12 +117,19 @@ napi_value Common::GetCallbackErrorValue(napi_env env, int errCode) napi_value Common::JSParaError(const napi_env &env, const napi_ref &callback) { if (callback) { + SetCallback(env, callback, ERR_BGTASK_INVALID_PARAM, nullptr); return Common::NapiGetNull(env); } else { napi_value promise = nullptr; napi_deferred deferred = nullptr; napi_create_promise(env, &deferred, &promise); - napi_resolve_deferred(env, deferred, Common::NapiGetNull(env)); + + napi_value res = nullptr; + napi_value eCode = nullptr; + NAPI_CALL(env, napi_create_int32(env, ERR_BGTASK_INVALID_PARAM, &eCode)); + NAPI_CALL(env, napi_create_object(env, &res)); + NAPI_CALL(env, napi_set_named_property(env, res, "data", eCode)); + napi_reject_deferred(env, deferred, res); return promise; } } diff --git a/interfaces/kits/napi/src/get_remaining_delay_time.cpp b/interfaces/kits/napi/src/get_remaining_delay_time.cpp index 8a23a642..88c2deeb 100644 --- a/interfaces/kits/napi/src/get_remaining_delay_time.cpp +++ b/interfaces/kits/napi/src/get_remaining_delay_time.cpp @@ -48,7 +48,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[0] : requestId if (Common::GetInt32NumberValue(env, argv[0], params.requestId) == nullptr) { - BGTASK_LOGE("ParseParameters failed, requestId is nullptr "); + BGTASK_LOGE("ParseParameters failed, requestId is nullptr."); return nullptr; } @@ -59,6 +59,11 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, argv[1], 1, ¶ms.callback); } + + if (params.requestId <= 0) { + BGTASK_LOGE("ParseParameters failed, requestId is illegal."); + return nullptr; + } return Common::NapiGetNull(env); } -- Gitee From 4d1dabc87e4fbd912b97cc36a605ff8680983e66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 20 Jan 2022 11:32:12 +0800 Subject: [PATCH 06/77] gn check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- interfaces/innerkits/BUILD.gn | 2 -- 1 file changed, 2 deletions(-) diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index cde19ed5..80009c8f 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -17,8 +17,6 @@ import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") config("bgtaskmgr_public_config") { include_dirs = [ "include", - "//utils/native/base/include", - "//utils/system/safwk/native/include", ] } -- Gitee From 9a6ea7e08c4c90bc27c36db19f44ed27820ccb4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 20 Jan 2022 11:47:00 +0800 Subject: [PATCH 07/77] gn fromat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- interfaces/innerkits/BUILD.gn | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index 80009c8f..c5215865 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -15,9 +15,7 @@ import("//build/ohos.gni") import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") config("bgtaskmgr_public_config") { - include_dirs = [ - "include", - ] + include_dirs = [ "include" ] } ohos_shared_library("bgtaskmgr_innerkits") { -- Gitee From 9e923eb69e40f70cb627d22d9fd9c83f71fee40a Mon Sep 17 00:00:00 2001 From: zhengjun Date: Sat, 22 Jan 2022 10:05:24 +0800 Subject: [PATCH 08/77] =?UTF-8?q?bundle=5Fframework=E9=83=A8=E4=BB=B6?= =?UTF-8?q?=E6=A0=87=E5=87=86=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhengjun --- services/BUILD.gn | 2 +- services/test/unittest/BUILD.gn | 4 ++-- test/systemtest/BUILD.gn | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/BUILD.gn b/services/BUILD.gn index 4d83b174..7d4241af 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -49,8 +49,8 @@ ohos_shared_library("bgtaskmgr_service") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index f4c3cd38..e4008cb4 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -44,9 +44,9 @@ ohos_unittest("bgtask_unit_test") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/test/systemtest/BUILD.gn b/test/systemtest/BUILD.gn index 94ba225c..f538d70a 100644 --- a/test/systemtest/BUILD.gn +++ b/test/systemtest/BUILD.gn @@ -48,7 +48,7 @@ ohos_systemtest("BgtaskDumpTest") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:appexecfwk_core", + "bundle_framework:appexecfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "samgr_standard:samgr_proxy", -- Gitee From f39a36a0958b83d13e3ef0c8bc94b7393991181b Mon Sep 17 00:00:00 2001 From: zero-cyc Date: Tue, 25 Jan 2022 11:24:33 +0800 Subject: [PATCH 09/77] chenlien@huawei.com Signed-off-by: zero-cyc Change-Id: Iaf74b1d748d0434b701d8575ffccbf29e7845bf7 --- services/BUILD.gn | 2 +- services/test/unittest/BUILD.gn | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/BUILD.gn b/services/BUILD.gn index 7d4241af..bcb64745 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -49,9 +49,9 @@ ohos_shared_library("bgtaskmgr_service") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index e4008cb4..1bc96012 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -44,10 +44,10 @@ ohos_unittest("bgtask_unit_test") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", -- Gitee From 0c5719f5a415eb5cea38c3630720b0bdce953879 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Wed, 26 Jan 2022 10:38:21 +0800 Subject: [PATCH 10/77] add TDD tc.require MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- .../transient_task_jsunit.test.js | 8 ++++---- .../background_task_mgr_service_test.cpp | 2 +- .../test/unittest/bg_transient_task_mgr_test.cpp | 16 ++++++++-------- .../transient_task/src/bg_transient_task_mgr.cpp | 3 ++- test/systemtest/bgtask_dump_test.cpp | 14 ++++++++------ 5 files changed, 23 insertions(+), 20 deletions(-) diff --git a/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js b/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js index 589a9364..22997910 100644 --- a/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js +++ b/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js @@ -49,7 +49,7 @@ describe("TransientTaskJsTest", function () { * @tc.name: TransientTaskJsTest001 * @tc.desc: test request a suspend delay * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86K AR000GH86N AR000GH86L */ it("TransientTaskJsTest001", 0, async function (done) { console.info('----------------------TransientTaskJsTest001---------------------------'); @@ -69,7 +69,7 @@ describe("TransientTaskJsTest", function () { * @tc.name: TransientTaskJsTest002 * @tc.desc: test transient task more than three * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86K AR000GH86L AR000GH86N */ it("TransientTaskJsTest002", 0, async function (done) { console.info('----------------------TransientTaskJsTest002---------------------------'); @@ -94,7 +94,7 @@ describe("TransientTaskJsTest", function () { * @tc.name: TransientTaskJsTest003 * @tc.desc: test getRemainingDelayTime Promise * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86M AR000GH860 AR000GH86L */ it("TransientTaskJsTest003", 0, async function (done) { function callback() {} @@ -126,7 +126,7 @@ describe("TransientTaskJsTest", function () { * @tc.name: TransientTaskJsTest004 * @tc.desc: test getRemainingDelayTime Callback * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86M AR000GH860 AR000GH86L */ it("TransientTaskJsTest004", 0, async function (done) { function callback() {} diff --git a/services/test/unittest/background_task_mgr_service_test.cpp b/services/test/unittest/background_task_mgr_service_test.cpp index fb641cc2..45f36042 100644 --- a/services/test/unittest/background_task_mgr_service_test.cpp +++ b/services/test/unittest/background_task_mgr_service_test.cpp @@ -37,7 +37,7 @@ public: * @tc.name: BackgroundTaskMgrServiceTest_001 * @tc.desc: Test BackgroundTaskMgrService service ready. * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86O AR000GH86Q */ HWTEST_F(BackgroundTaskMgrServiceTest, BackgroundTaskMgrServiceTest_001, TestSize.Level1) { diff --git a/services/test/unittest/bg_transient_task_mgr_test.cpp b/services/test/unittest/bg_transient_task_mgr_test.cpp index 01283a6c..cc10fb3a 100644 --- a/services/test/unittest/bg_transient_task_mgr_test.cpp +++ b/services/test/unittest/bg_transient_task_mgr_test.cpp @@ -45,7 +45,7 @@ public: * @tc.name: SubscribeTransientTask_001 * @tc.desc: subscribe transient task event. * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_001, TestSize.Level1) { @@ -58,7 +58,7 @@ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_001, TestSize.Level1) * @tc.name: SubscribeTransientTask_002 * @tc.desc: subscribe transient task event. * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_002, TestSize.Level1) { @@ -70,7 +70,7 @@ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_002, TestSize.Level1) * @tc.name: SubscribeTransientTask_003 * @tc.desc: subscribe transient task event. * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_003, TestSize.Level1) { @@ -86,7 +86,7 @@ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_003, TestSize.Level1) * @tc.name: UnsubscribeTransientTask_001 * @tc.desc: unsubscribe transient task event. * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_001, TestSize.Level1) { @@ -104,7 +104,7 @@ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_001, TestSize.Level1) * @tc.name: UnsubscribeTransientTask_002 * @tc.desc: unsubscribe transient task event. * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_002, TestSize.Level1) { @@ -117,7 +117,7 @@ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_002, TestSize.Level1) * @tc.name: UnsubscribeTransientTask_003 * @tc.desc: unsubscribe transient task event. * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_003, TestSize.Level1) { @@ -129,7 +129,7 @@ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_003, TestSize.Level1) * @tc.name: Marshalling_001 * @tc.desc: marshalling transient task app info. * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86Q */ HWTEST_F(BgTransientTaskMgrTest, Marshalling_001, TestSize.Level1) { @@ -144,7 +144,7 @@ HWTEST_F(BgTransientTaskMgrTest, Marshalling_001, TestSize.Level1) * @tc.name: Unmarshalling_001 * @tc.desc: unmarshalling transient task app info. * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000GH86Q */ HWTEST_F(BgTransientTaskMgrTest, Unmarshalling_001, TestSize.Level1) { diff --git a/services/transient_task/src/bg_transient_task_mgr.cpp b/services/transient_task/src/bg_transient_task_mgr.cpp index 39c38325..57f959d3 100644 --- a/services/transient_task/src/bg_transient_task_mgr.cpp +++ b/services/transient_task/src/bg_transient_task_mgr.cpp @@ -49,7 +49,7 @@ static const std::string CANCEL_DUMP_OPTION = "DUMP_CANCEL"; constexpr int32_t BG_INVALID_REMAIN_TIME = -1; constexpr int32_t WATCHDOG_DELAY_TIME = 6 * MSEC_PER_SEC; -constexpr int32_t SERVICE_WAIT_TIME = 5000; +constexpr int32_t SERVICE_WAIT_TIME = 2000; } BgTransientTaskMgr::BgTransientTaskMgr() {} @@ -75,6 +75,7 @@ void BgTransientTaskMgr::InitNecessaryState() = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemAbilityManager == nullptr || systemAbilityManager->CheckSystemAbility(APP_MGR_SERVICE_ID) == nullptr + || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr || systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr) { BGTASK_LOGI("request system service is not ready yet!"); std::function InitNecessaryStateFunc = std::bind(&BgTransientTaskMgr::InitNecessaryState, this); diff --git a/test/systemtest/bgtask_dump_test.cpp b/test/systemtest/bgtask_dump_test.cpp index 317cef9b..5ddb9b98 100644 --- a/test/systemtest/bgtask_dump_test.cpp +++ b/test/systemtest/bgtask_dump_test.cpp @@ -57,9 +57,10 @@ void BgtaskDumpTest::TearDown() {} /* - * @tc.number: BgtaskDumpTest_GetServiceObject_001 - * @tc.name: Get Service Object - * @tc.desc: + * @tc.name: BgtaskDumpTest_GetServiceObject_001 + * @tc.desc: Get Service Object + * @tc.type: FUNC + * @tc.require: AR000GH86Q */ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_GetServiceObject_001, Function | MediumTest | Level0) { @@ -73,9 +74,10 @@ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_GetServiceObject_001, Function | MediumT } /* - * @tc.number: BgtaskDumpTest_ShellDump_001 - * @tc.name: Shell Dump - * @tc.desc: + * @tc.name: BgtaskDumpTest_ShellDump_001 + * @tc.desc: Shell dump + * @tc.type: FUNC + * @tc.require: AR000GH86V */ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_001, Function | MediumTest | Level0) { -- Gitee From 1c433183464cee10e889b4865d44c74dbdeba9c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Tue, 8 Feb 2022 19:13:13 +0800 Subject: [PATCH 11/77] change tdd output path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- interfaces/test/unittest/BUILD.gn | 2 +- services/test/unittest/BUILD.gn | 2 +- test/systemtest/BUILD.gn | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn index d8264267..a130cd20 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/BUILD.gn @@ -12,7 +12,7 @@ # limitations under the License. import("//build/test.gni") -module_output_path = "background_task_manager/interfaces" +module_output_path = "background_task_mgr/interfaces" ohos_js_unittest("TransientTaskJsTest") { module_out_path = module_output_path diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 1bc96012..39eb7fef 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -15,7 +15,7 @@ import("//build/ohos.gni") import("//build/test.gni") import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") -module_output_path = "background_task_manager/unittest" +module_output_path = "background_task_mgr/unittest" ohos_unittest("bgtask_unit_test") { module_out_path = module_output_path diff --git a/test/systemtest/BUILD.gn b/test/systemtest/BUILD.gn index f538d70a..93e1c24a 100644 --- a/test/systemtest/BUILD.gn +++ b/test/systemtest/BUILD.gn @@ -20,7 +20,7 @@ config("system_test_config") { configs = [] } -module_output_path = "background_task_manager/systemtest" +module_output_path = "background_task_mgr/systemtest" ohos_systemtest("BgtaskDumpTest") { module_out_path = module_output_path -- Gitee From a92f5da96f7639223e74b1d8f5ae833a54783117 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 10 Feb 2022 09:40:42 +0800 Subject: [PATCH 12/77] modify syscap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- bundle.json | 2 +- .../kits/js/@ohos.backgroundTaskManager.d.ts | 14 +++++--------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/bundle.json b/bundle.json index 8bbaabf2..71dd0c25 100644 --- a/bundle.json +++ b/bundle.json @@ -12,7 +12,7 @@ "component": { "name": "background_task_mgr", "subsystem": "resourceschedule", - "syscap": [ "SystemCapability.Ressched.BackgroundTaskMgr" ], + "syscap": [ "SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask" ], "features": [], "adapted_system_type": [ "mini", diff --git a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts index 85bd32ad..312b9e67 100644 --- a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts +++ b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts @@ -28,8 +28,7 @@ declare namespace backgroundTaskManager { * * @name DelaySuspendInfo * @since 7 - * @sysCap SystemCapability.Ressched.BackgroundTaskMgr - * @devices phone, tv, wearable, tablet, car + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask */ interface DelaySuspendInfo { /** @@ -46,8 +45,7 @@ declare namespace backgroundTaskManager { * Cancels delayed transition to the suspended state. * * @since 7 - * @sysCap SystemCapability.Ressched.BackgroundTaskMgr - * @devices phone, tv, wearable, tablet, car + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask * @param requestId Indicates the identifier of the delay request. */ function cancelSuspendDelay(requestId: number): void; @@ -56,8 +54,7 @@ declare namespace backgroundTaskManager { * Obtains the remaining time before an application enters the suspended state. * * @since 7 - * @sysCap SystemCapability.Ressched.BackgroundTaskMgr - * @devices phone, tv, wearable, tablet, car + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask * @param requestId Indicates the identifier of the delay request. * @return The remaining delay time */ @@ -68,8 +65,7 @@ declare namespace backgroundTaskManager { * Requests delayed transition to the suspended state. * * @since 7 - * @sysCap SystemCapability.Ressched.BackgroundTaskMgr - * @devices phone, tv, wearable, tablet, car + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask * @param reason Indicates the reason for delayed transition to the suspended state. * @param callback The callback delay time expired. * @return Info of delay request @@ -77,4 +73,4 @@ declare namespace backgroundTaskManager { function requestSuspendDelay(reason: string, callback: Callback): DelaySuspendInfo; } -export default backgroundTaskManager; \ No newline at end of file +export default backgroundTaskManager; -- Gitee From 0c518df83b142700e07ac4121c11cfff7cc14001 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 10 Feb 2022 09:48:42 +0800 Subject: [PATCH 13/77] modify syscap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- interfaces/kits/js/@ohos.backgroundTaskManager.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts index 312b9e67..2d7daf12 100644 --- a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts +++ b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts @@ -19,8 +19,7 @@ import { AsyncCallback , Callback} from './basic'; * Manages background tasks. * * @since 7 - * @sysCap SystemCapability.Ressched.BackgroundTaskMgr - * @devices phone, tv, wearable, tablet, car + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask */ declare namespace backgroundTaskManager { /** -- Gitee From 1177ce6d2b13eee7836d655d1037bf311f7074ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 10 Feb 2022 10:36:44 +0800 Subject: [PATCH 14/77] modify syscap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- bundle.json | 2 +- interfaces/kits/js/@ohos.backgroundTaskManager.d.ts | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/bundle.json b/bundle.json index 71dd0c25..1c3d60dd 100644 --- a/bundle.json +++ b/bundle.json @@ -12,7 +12,7 @@ "component": { "name": "background_task_mgr", "subsystem": "resourceschedule", - "syscap": [ "SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask" ], + "syscap": [ "SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask" ], "features": [], "adapted_system_type": [ "mini", diff --git a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts index 2d7daf12..955f2fd0 100644 --- a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts +++ b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts @@ -19,7 +19,7 @@ import { AsyncCallback , Callback} from './basic'; * Manages background tasks. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask */ declare namespace backgroundTaskManager { /** @@ -27,7 +27,7 @@ declare namespace backgroundTaskManager { * * @name DelaySuspendInfo * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask */ interface DelaySuspendInfo { /** @@ -44,7 +44,7 @@ declare namespace backgroundTaskManager { * Cancels delayed transition to the suspended state. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask * @param requestId Indicates the identifier of the delay request. */ function cancelSuspendDelay(requestId: number): void; @@ -53,7 +53,7 @@ declare namespace backgroundTaskManager { * Obtains the remaining time before an application enters the suspended state. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask * @param requestId Indicates the identifier of the delay request. * @return The remaining delay time */ @@ -64,7 +64,7 @@ declare namespace backgroundTaskManager { * Requests delayed transition to the suspended state. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskMgr.TransientTask + * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask * @param reason Indicates the reason for delayed transition to the suspended state. * @param callback The callback delay time expired. * @return Info of delay request -- Gitee From 26d6c64ba90f85f438b779e189e59841d6900ddb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 10 Feb 2022 11:54:08 +0800 Subject: [PATCH 15/77] change AR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- test/systemtest/bgtask_dump_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/systemtest/bgtask_dump_test.cpp b/test/systemtest/bgtask_dump_test.cpp index 5ddb9b98..276fd0ac 100644 --- a/test/systemtest/bgtask_dump_test.cpp +++ b/test/systemtest/bgtask_dump_test.cpp @@ -77,7 +77,7 @@ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_GetServiceObject_001, Function | MediumT * @tc.name: BgtaskDumpTest_ShellDump_001 * @tc.desc: Shell dump * @tc.type: FUNC - * @tc.require: AR000GH86V + * @tc.require: AR000GH85V */ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_001, Function | MediumTest | Level0) { @@ -91,4 +91,4 @@ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_001, Function | MediumTest | L } } } // namespace BackgroundTaskMgr -} // namespace OHOS \ No newline at end of file +} // namespace OHOS -- Gitee From fb5365c872ff1a9e126e07d89d93c547edb314f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 10 Feb 2022 14:16:17 +0800 Subject: [PATCH 16/77] modify syscap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- interfaces/kits/js/@ohos.backgroundTaskManager.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts index 955f2fd0..cbe6ae70 100644 --- a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts +++ b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts @@ -19,7 +19,7 @@ import { AsyncCallback , Callback} from './basic'; * Manages background tasks. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask */ declare namespace backgroundTaskManager { /** @@ -27,7 +27,7 @@ declare namespace backgroundTaskManager { * * @name DelaySuspendInfo * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask */ interface DelaySuspendInfo { /** @@ -44,7 +44,7 @@ declare namespace backgroundTaskManager { * Cancels delayed transition to the suspended state. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask * @param requestId Indicates the identifier of the delay request. */ function cancelSuspendDelay(requestId: number): void; @@ -53,7 +53,7 @@ declare namespace backgroundTaskManager { * Obtains the remaining time before an application enters the suspended state. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask * @param requestId Indicates the identifier of the delay request. * @return The remaining delay time */ @@ -64,7 +64,7 @@ declare namespace backgroundTaskManager { * Requests delayed transition to the suspended state. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask * @param reason Indicates the reason for delayed transition to the suspended state. * @param callback The callback delay time expired. * @return Info of delay request -- Gitee From d4895b71ae883100b52178446534c1e3344e129f Mon Sep 17 00:00:00 2001 From: njupthan Date: Thu, 10 Feb 2022 08:55:45 +0000 Subject: [PATCH 17/77] Fix atomic ability part name change Signed-off-by: njupthan --- interfaces/BUILD.gn | 10 +++++----- services/BUILD.gn | 2 +- services/test/unittest/BUILD.gn | 2 +- test/systemtest/BUILD.gn | 3 +-- utils/dump/BUILD.gn | 2 +- 5 files changed, 9 insertions(+), 10 deletions(-) diff --git a/interfaces/BUILD.gn b/interfaces/BUILD.gn index ac31b132..2bfd25a4 100644 --- a/interfaces/BUILD.gn +++ b/interfaces/BUILD.gn @@ -12,8 +12,8 @@ # limitations under the License. group("bgtaskmgr_interfaces") { - deps = [ - "kits:backgroundtaskmanager", - "innerkits:bgtaskmgr_innerkits", - ] -} \ No newline at end of file + deps = [ + "innerkits:bgtaskmgr_innerkits", + "kits:backgroundtaskmanager", + ] +} diff --git a/services/BUILD.gn b/services/BUILD.gn index bcb64745..2e90ee0b 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -47,8 +47,8 @@ ohos_shared_library("bgtaskmgr_service") { ] external_deps = [ + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:want", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", "eventhandler:libeventhandler", diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 39eb7fef..8475be68 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -42,8 +42,8 @@ ohos_unittest("bgtask_unit_test") { ] external_deps = [ + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", diff --git a/test/systemtest/BUILD.gn b/test/systemtest/BUILD.gn index 93e1c24a..9864fe06 100644 --- a/test/systemtest/BUILD.gn +++ b/test/systemtest/BUILD.gn @@ -46,8 +46,7 @@ ohos_systemtest("BgtaskDumpTest") { ] external_deps = [ - "ability_runtime:app_manager", - "ability_runtime:want", + "ability_base:want", "bundle_framework:appexecfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/utils/dump/BUILD.gn b/utils/dump/BUILD.gn index 007f7aec..af8ccb0e 100644 --- a/utils/dump/BUILD.gn +++ b/utils/dump/BUILD.gn @@ -40,7 +40,7 @@ ohos_executable("bgtask") { configs = [] external_deps = [ - "ability_runtime:want", + "ability_base:want", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "samgr_standard:samgr_proxy", -- Gitee From 98a5aebb39454f5ec99855f7afa0fa87f7a8f749 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Thu, 10 Feb 2022 23:52:57 +0800 Subject: [PATCH 18/77] add continuous task feature Signed-off-by: zhangxin_T --- bundle.json | 8 +- frameworks/BUILD.gn | 8 + .../common/include/bgtaskmgr_inner_errors.h | 8 + .../common/include/continuous_task_log.h | 25 + frameworks/include/background_task_manager.h | 5 + .../include/background_task_mgr_proxy.h | 2 + frameworks/include/background_task_mgr_stub.h | 2 + .../background_task_subscriber_proxy.h | 4 + .../include/background_task_subscriber_stub.h | 9 +- frameworks/include/ibackground_task_mgr.h | 6 + .../include/ibackground_task_subscriber.h | 13 +- frameworks/src/background_task_manager.cpp | 29 + frameworks/src/background_task_mgr_proxy.cpp | 66 ++ frameworks/src/background_task_mgr_stub.cpp | 36 + .../src/background_task_subscriber_proxy.cpp | 114 +++ .../src/background_task_subscriber_stub.cpp | 56 +- interfaces/innerkits/BUILD.gn | 16 +- .../innerkits/include/background_mode.h | 38 + .../include/background_task_mgr_helper.h | 18 + .../include/background_task_subscriber.h | 56 +- .../include/continuous_task_callback_info.h | 48 + .../innerkits/include/continuous_task_param.h | 46 + .../src/background_task_mgr_helper.cpp | 11 + .../src/background_task_subscriber.cpp | 96 +- .../src/continuous_task_callback_info.cpp | 98 ++ .../innerkits/src/continuous_task_param.cpp | 113 +++ interfaces/kits/BUILD.gn | 6 + .../kits/js/@ohos.backgroundTaskManager.d.ts | 109 +++ .../include/bg_continuous_task_napi_module.h | 28 + interfaces/kits/napi/include/init.h | 2 + .../src/bg_continuous_task_napi_module.cpp | 458 ++++++++++ interfaces/kits/napi/src/init.cpp | 38 + interfaces/test/unittest/BUILD.gn | 11 +- .../continuous_task_jsunittest/config.json | 74 ++ .../continuous_task_jsunit.test.js | 386 ++++++++ resources/BUILD.gn | 33 + resources/BackgroundTaskResources.p7b | Bin 0 -> 3401 bytes resources/main/config.json | 33 + .../main/resources/base/element/string.json | 44 + .../main/resources/zh_CN/element/string.json | 44 + services/BUILD.gn | 15 + .../include/app_state_observer.h | 55 ++ .../include/bg_continuous_task_mgr.h | 145 +++ .../include/bundle_manager_helper.h | 54 ++ .../include/continuous_task_record.h | 73 ++ .../include/remote_death_recipient.h | 48 + .../include/system_event_observer.h | 48 + .../include/task_notification_subscriber.h | 60 ++ .../src/app_state_observer.cpp | 134 +++ .../src/bg_continuous_task_mgr.cpp | 854 ++++++++++++++++++ .../src/bundle_manager_helper.cpp | 132 +++ .../src/continuous_task_record.cpp | 92 ++ .../src/system_event_observer.cpp | 90 ++ .../src/task_notification_subscriber.cpp | 134 +++ .../include/background_task_mgr_service.h | 3 + .../core/src/background_task_mgr_service.cpp | 30 +- services/test/unittest/BUILD.gn | 8 + .../unittest/bg_continuous_task_mgr_test.cpp | 184 ++++ .../mock/mock_bundle_manager_helper.cpp | 72 ++ .../mock/mock_notification_helper.cpp | 54 ++ .../unittest/mock/mock_resource_manager.cpp | 207 +++++ test/systemtest/bgtask_dump_test.cpp | 18 + utils/BUILD.gn | 1 + utils/bgtask_observer/BUILD.gn | 52 ++ .../bgtask_observer/include/bgtask_observer.h | 39 + utils/bgtask_observer/src/bgtask_observer.cpp | 70 ++ utils/bgtask_observer/src/main.cpp | 102 +++ utils/dump/src/bgtaskmgr_shell_command.cpp | 17 +- 68 files changed, 4968 insertions(+), 20 deletions(-) create mode 100644 frameworks/common/include/continuous_task_log.h create mode 100644 interfaces/innerkits/include/background_mode.h create mode 100644 interfaces/innerkits/include/continuous_task_callback_info.h create mode 100644 interfaces/innerkits/include/continuous_task_param.h create mode 100644 interfaces/innerkits/src/continuous_task_callback_info.cpp create mode 100644 interfaces/innerkits/src/continuous_task_param.cpp create mode 100644 interfaces/kits/napi/include/bg_continuous_task_napi_module.h create mode 100644 interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp create mode 100644 interfaces/test/unittest/continuous_task_jsunittest/config.json create mode 100644 interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js create mode 100644 resources/BUILD.gn create mode 100644 resources/BackgroundTaskResources.p7b create mode 100644 resources/main/config.json create mode 100644 resources/main/resources/base/element/string.json create mode 100644 resources/main/resources/zh_CN/element/string.json create mode 100644 services/continuous_task/include/app_state_observer.h create mode 100644 services/continuous_task/include/bg_continuous_task_mgr.h create mode 100644 services/continuous_task/include/bundle_manager_helper.h create mode 100644 services/continuous_task/include/continuous_task_record.h create mode 100644 services/continuous_task/include/remote_death_recipient.h create mode 100644 services/continuous_task/include/system_event_observer.h create mode 100644 services/continuous_task/include/task_notification_subscriber.h create mode 100644 services/continuous_task/src/app_state_observer.cpp create mode 100644 services/continuous_task/src/bg_continuous_task_mgr.cpp create mode 100644 services/continuous_task/src/bundle_manager_helper.cpp create mode 100644 services/continuous_task/src/continuous_task_record.cpp create mode 100644 services/continuous_task/src/system_event_observer.cpp create mode 100644 services/continuous_task/src/task_notification_subscriber.cpp create mode 100644 services/test/unittest/bg_continuous_task_mgr_test.cpp create mode 100644 services/test/unittest/mock/mock_bundle_manager_helper.cpp create mode 100644 services/test/unittest/mock/mock_notification_helper.cpp create mode 100644 services/test/unittest/mock/mock_resource_manager.cpp create mode 100644 utils/bgtask_observer/BUILD.gn create mode 100644 utils/bgtask_observer/include/bgtask_observer.h create mode 100644 utils/bgtask_observer/src/bgtask_observer.cpp create mode 100644 utils/bgtask_observer/src/main.cpp diff --git a/bundle.json b/bundle.json index 1c3d60dd..2a8e1896 100644 --- a/bundle.json +++ b/bundle.json @@ -12,7 +12,10 @@ "component": { "name": "background_task_mgr", "subsystem": "resourceschedule", - "syscap": [ "SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask" ], + "syscap": [ + "SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask", + "SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask" + ], "features": [], "adapted_system_type": [ "mini", @@ -43,7 +46,8 @@ "//foundation/resourceschedule/background_task_mgr/services:bgtaskmgr_service", "//foundation/resourceschedule/background_task_mgr/sa_profile:bgtaskmgr_sa_profile", "//foundation/resourceschedule/background_task_mgr/sa_profile:bgtaskmgr_service_init", - "//foundation/resourceschedule/background_task_mgr/utils:bgtaskmgr_dump" + "//foundation/resourceschedule/background_task_mgr/utils:bgtaskmgr_dump", + "//foundation/resourceschedule/background_task_mgr/resources:bgtaskmgr_resources" ], "inner_kits": [ { diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn index 9795b083..656ea94e 100644 --- a/frameworks/BUILD.gn +++ b/frameworks/BUILD.gn @@ -25,6 +25,8 @@ config("bgtaskmgr_public_config") { ohos_shared_library("bgtaskmgr_fwk") { sources = [ "${bgtaskmgr_interfaces_path}/innerkits/src/background_task_subscriber.cpp", + "${bgtaskmgr_interfaces_path}/innerkits/src/continuous_task_callback_info.cpp", + "${bgtaskmgr_interfaces_path}/innerkits/src/continuous_task_param.cpp", "${bgtaskmgr_interfaces_path}/innerkits/src/delay_suspend_info.cpp", "${bgtaskmgr_interfaces_path}/innerkits/src/expired_callback.cpp", "${bgtaskmgr_interfaces_path}/innerkits/src/transient_task_app_info.cpp", @@ -38,9 +40,15 @@ ohos_shared_library("bgtaskmgr_fwk") { "src/expired_callback_stub.cpp", ] + deps = [ + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + ] + public_configs = [ ":bgtaskmgr_public_config" ] external_deps = [ + "ability_runtime:want", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/frameworks/common/include/bgtaskmgr_inner_errors.h b/frameworks/common/include/bgtaskmgr_inner_errors.h index 0551efeb..7ebc4b8d 100644 --- a/frameworks/common/include/bgtaskmgr_inner_errors.h +++ b/frameworks/common/include/bgtaskmgr_inner_errors.h @@ -47,6 +47,14 @@ enum : int { ERR_BGTASK_INVALID_PARAM, ERR_BGTASK_NOT_ALLOWED, ERR_BGTASK_OBJECT_EXISTS, + ERR_BGTASK_METHOD_CALLED_FAILED, + ERR_BGTASK_NON_SYSTEM_APP, + ERR_BGTASK_SYS_NOT_READY, + ERR_BGTASK_TASK_ERR, + ERR_BGTASK_PERMISSION_DENIED, + ERR_BGTASK_NOTIFICATION_ERR, + ERR_BGTASK_INVALID_BGMODE, + ERR_BGTASK_NO_MEMORY, }; } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/frameworks/common/include/continuous_task_log.h b/frameworks/common/include/continuous_task_log.h new file mode 100644 index 00000000..db3f7e91 --- /dev/null +++ b/frameworks/common/include/continuous_task_log.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_COMMON_INCLUDE_CONTINUOUS_TASK_LOG_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_COMMON_INCLUDE_CONTINUOUS_TASK_LOG_H + +#ifndef BGTASK_MGR_LOG_TAG +#define BGTASK_MGR_LOG_TAG "CONTINUOUS_TASK" +#endif + +#include "bgtaskmgr_log_wrapper.h" + +#endif \ No newline at end of file diff --git a/frameworks/include/background_task_manager.h b/frameworks/include/background_task_manager.h index 4e747596..ff8bdf18 100644 --- a/frameworks/include/background_task_manager.h +++ b/frameworks/include/background_task_manager.h @@ -20,6 +20,7 @@ #include "expired_callback.h" #include "ibackground_task_mgr.h" #include "iremote_object.h" +#include "want_agent.h" namespace OHOS { namespace BackgroundTaskMgr { @@ -36,6 +37,10 @@ public: ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime); + ErrCode RequestStartBackgroundRunning(const ContinuousTaskParam &taskParam); + + ErrCode RequestStopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken); + void ResetBackgroundTaskManagerProxy(); ErrCode SubscribeBackgroundTask(const BackgroundTaskSubscriber &subscriber); diff --git a/frameworks/include/background_task_mgr_proxy.h b/frameworks/include/background_task_mgr_proxy.h index 77187965..aa602586 100644 --- a/frameworks/include/background_task_mgr_proxy.h +++ b/frameworks/include/background_task_mgr_proxy.h @@ -33,6 +33,8 @@ public: const sptr& callback, std::shared_ptr &delayInfo) override; ErrCode CancelSuspendDelay(int32_t requestId) override; ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) override; + ErrCode StartBackgroundRunning(const sptr taskParam) override; + ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken) override; ErrCode SubscribeBackgroundTask(const sptr& subscriber) override; ErrCode UnsubscribeBackgroundTask(const sptr& subscriber) override; ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) override; diff --git a/frameworks/include/background_task_mgr_stub.h b/frameworks/include/background_task_mgr_stub.h index 94750b40..98aaa398 100644 --- a/frameworks/include/background_task_mgr_stub.h +++ b/frameworks/include/background_task_mgr_stub.h @@ -38,6 +38,8 @@ private: ErrCode HandleRequestSuspendDelay(MessageParcel& data, MessageParcel& reply); ErrCode HandleCancelSuspendDelay(MessageParcel& data, MessageParcel& reply); ErrCode HandleGetRemainingDelayTime(MessageParcel& data, MessageParcel& reply); + ErrCode HandleStartBackgroundRunning(MessageParcel &data, MessageParcel &reply); + ErrCode HandleStopBackgroundRunning(MessageParcel &data, MessageParcel &reply); ErrCode HandleSubscribeBackgroundTask(MessageParcel& data, MessageParcel& reply); ErrCode HandleUnsubscribeBackgroundTask(MessageParcel& data, MessageParcel& reply); ErrCode HandleShellDump(MessageParcel& data, MessageParcel& reply); diff --git a/frameworks/include/background_task_subscriber_proxy.h b/frameworks/include/background_task_subscriber_proxy.h index fc4101af..0f5ffd04 100644 --- a/frameworks/include/background_task_subscriber_proxy.h +++ b/frameworks/include/background_task_subscriber_proxy.h @@ -29,8 +29,12 @@ public: ~BackgroundTaskSubscriberProxy() override; DISALLOW_COPY_AND_MOVE(BackgroundTaskSubscriberProxy); + void OnConnected() override; + void OnDisconnected() override; void OnTransientTaskStart(const std::shared_ptr& info) override; void OnTransientTaskEnd(const std::shared_ptr& info) override; + void OnContinuousTaskStart(const sptr &continuousTaskCallbackInfo) override; + void OnContinuousTaskStop(const sptr &continuousTaskCallbackInfo) override; private: static inline BrokerDelegator delegator_; diff --git a/frameworks/include/background_task_subscriber_stub.h b/frameworks/include/background_task_subscriber_stub.h index dac0d283..a72025c9 100644 --- a/frameworks/include/background_task_subscriber_stub.h +++ b/frameworks/include/background_task_subscriber_stub.h @@ -18,6 +18,7 @@ #include +#include "bgtaskmgr_inner_errors.h" #include "ibackground_task_subscriber.h" namespace OHOS { @@ -30,8 +31,12 @@ public: int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; private: - int32_t HandleOnTransientTaskStart(MessageParcel& data); - int32_t HandleOnTransientTaskEnd(MessageParcel& data); + ErrCode HandleOnConnected(MessageParcel &data); + ErrCode HandleOnDisconnected(MessageParcel &data); + ErrCode HandleOnTransientTaskStart(MessageParcel& data); + ErrCode HandleOnTransientTaskEnd(MessageParcel& data); + ErrCode HandleOnContinuousTaskStart(MessageParcel &data); + ErrCode HandleOnContinuousTaskCancel(MessageParcel &data); }; } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/frameworks/include/ibackground_task_mgr.h b/frameworks/include/ibackground_task_mgr.h index d1ef00a8..256f9cf9 100644 --- a/frameworks/include/ibackground_task_mgr.h +++ b/frameworks/include/ibackground_task_mgr.h @@ -23,9 +23,11 @@ #include #include "bgtaskmgr_inner_errors.h" +#include "continuous_task_param.h" #include "delay_suspend_info.h" #include "iexpired_callback.h" #include "ibackground_task_subscriber.h" +#include "want_agent.h" namespace OHOS { namespace BackgroundTaskMgr { @@ -39,6 +41,8 @@ public: const sptr& callback, std::shared_ptr &delayInfo) = 0; virtual ErrCode CancelSuspendDelay(int32_t requestId) = 0; virtual ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) = 0; + virtual ErrCode StartBackgroundRunning(const sptr taskParam) = 0; + virtual ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken) = 0; virtual ErrCode SubscribeBackgroundTask(const sptr& subscriber) = 0; virtual ErrCode UnsubscribeBackgroundTask(const sptr& subscriber) = 0; virtual ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) = 0; @@ -51,6 +55,8 @@ protected: REQUEST_SUSPEND_DELAY = MIN_TRANSACTION_ID, CANCEL_SUSPEND_DELAY, GET_REMAINING_DELAY_TIME, + START_BACKGROUND_RUNNING, + STOP_BACKGROUND_RUNNING, SUBSCRIBE_BACKGROUND_TASK, UNSUBSCRIBE_BACKGROUND_TASK, SHELL_DUMP, diff --git a/frameworks/include/ibackground_task_subscriber.h b/frameworks/include/ibackground_task_subscriber.h index 60348ab6..265e376b 100644 --- a/frameworks/include/ibackground_task_subscriber.h +++ b/frameworks/include/ibackground_task_subscriber.h @@ -20,6 +20,7 @@ #include #include +#include "continuous_task_callback_info.h" #include "transient_task_app_info.h" namespace OHOS { @@ -30,15 +31,23 @@ public: ~IBackgroundTaskSubscriber() override = default; DISALLOW_COPY_AND_MOVE(IBackgroundTaskSubscriber); + virtual void OnConnected() = 0; + virtual void OnDisconnected() = 0; virtual void OnTransientTaskStart(const std::shared_ptr& info) = 0; virtual void OnTransientTaskEnd(const std::shared_ptr& info) = 0; + virtual void OnContinuousTaskStart(const sptr &continuousTaskCallbackInfo) = 0; + virtual void OnContinuousTaskStop(const sptr &continuousTaskCallbackInfo) = 0; public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.resourceschedule.IBackgroundTaskSubscriber"); protected: enum InterfaceId : uint32_t { - ON_TRANSIENT_TASK_START = FIRST_CALL_TRANSACTION, - ON_TRANSIENT_TASK_END + ON_CONNECTED = FIRST_CALL_TRANSACTION, + ON_DISCONNECTED, + ON_TRANSIENT_TASK_START, + ON_TRANSIENT_TASK_END, + ON_CONTINUOUS_TASK_START, + ON_CONTINUOUS_TASK_STOP, }; }; } // namespace BackgroundTaskMgr diff --git a/frameworks/src/background_task_manager.cpp b/frameworks/src/background_task_manager.cpp index 5066e3a0..ded9427f 100644 --- a/frameworks/src/background_task_manager.cpp +++ b/frameworks/src/background_task_manager.cpp @@ -62,6 +62,35 @@ ErrCode BackgroundTaskManager::GetRemainingDelayTime(int32_t requestId, int32_t return backgroundTaskMgrProxy_->GetRemainingDelayTime(requestId, delayTime); } +ErrCode BackgroundTaskManager::RequestStartBackgroundRunning(const ContinuousTaskParam &taskParam) +{ + BGTASK_LOGI("begin"); + if (!GetBackgroundTaskManagerProxy()) { + BGTASK_LOGE("GetBackgroundTaskManagerProxy failed."); + return ERR_BGTASK_SERVICE_NOT_CONNECTED; + } + + sptr taskParamPtr = new (std::nothrow) ContinuousTaskParam(taskParam); + if (taskParamPtr == nullptr) { + BGTASK_LOGE("Failed to create continuous task param"); + return ERR_BGTASK_NO_MEMORY; + } + BGTASK_LOGI("end"); + return backgroundTaskMgrProxy_->StartBackgroundRunning(taskParamPtr); +} + +ErrCode BackgroundTaskManager::RequestStopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + BGTASK_LOGI("begin"); + if (!GetBackgroundTaskManagerProxy()) { + BGTASK_LOGE("GetBackgroundTaskManagerProxy failed."); + return ERR_BGTASK_SERVICE_NOT_CONNECTED; + } + BGTASK_LOGI("end"); + return backgroundTaskMgrProxy_->StopBackgroundRunning(abilityName, abilityToken); +} + ErrCode BackgroundTaskManager::SubscribeBackgroundTask(const BackgroundTaskSubscriber &subscriber) { if (!GetBackgroundTaskManagerProxy()) { diff --git a/frameworks/src/background_task_mgr_proxy.cpp b/frameworks/src/background_task_mgr_proxy.cpp index 5c7ef321..deead535 100644 --- a/frameworks/src/background_task_mgr_proxy.cpp +++ b/frameworks/src/background_task_mgr_proxy.cpp @@ -125,6 +125,72 @@ ErrCode BackgroundTaskMgrProxy::GetRemainingDelayTime(int32_t requestId, int32_t return result; } +ErrCode BackgroundTaskMgrProxy::StartBackgroundRunning(const sptr taskParam) +{ + BGTASK_LOGI("begin"); + if (taskParam == nullptr) { + return ERR_BGTASK_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(taskParam)) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + + ErrCode result = InnerTransact(START_BACKGROUND_RUNNING, option, data, reply); + if (result != ERR_OK) { + BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + return ERR_BGTASK_TRANSACT_FAILED; + } + if (!reply.ReadInt32(result)) { + BGTASK_LOGI("fail: read result failed."); + return ERR_BGTASK_PARCELABLE_FAILED; + } + BGTASK_LOGI("end"); + return result; +} + +ErrCode BackgroundTaskMgrProxy::StopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + BGTASK_LOGI("begin"); + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + + if (!data.WriteString(abilityName)) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(abilityToken)) { + BGTASK_LOGE("parcel ability token failed"); + return ERR_BGTASK_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + + ErrCode result = InnerTransact(STOP_BACKGROUND_RUNNING, option, data, reply); + if (result != ERR_OK) { + BGTASK_LOGE("[StopBackgroundRunning] fail: transact ErrCode=%{public}d", result); + return ERR_BGTASK_TRANSACT_FAILED; + } + if (!reply.ReadInt32(result)) { + BGTASK_LOGE("[StopBackgroundRunning] fail: read result failed."); + return ERR_BGTASK_PARCELABLE_FAILED; + } + BGTASK_LOGI("end"); + return result; +} + ErrCode BackgroundTaskMgrProxy::SubscribeBackgroundTask(const sptr& subscriber) { if (subscriber == nullptr) { diff --git a/frameworks/src/background_task_mgr_stub.cpp b/frameworks/src/background_task_mgr_stub.cpp index b48904f9..1b4bef13 100644 --- a/frameworks/src/background_task_mgr_stub.cpp +++ b/frameworks/src/background_task_mgr_stub.cpp @@ -37,6 +37,12 @@ const std::map taskParam = data.ReadParcelable(); + if (taskParam == nullptr) { + BGTASK_LOGE("ContinuousTaskParam ReadParcelable failed"); + return ERR_BGTASK_PARCELABLE_FAILED; + } + ErrCode result = StartBackgroundRunning(taskParam); + if (!reply.WriteInt32(result)) { + BGTASK_LOGE("write result failed, ErrCode=%{public}d", result); + return ERR_BGTASK_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode BackgroundTaskMgrStub::HandleStopBackgroundRunning(MessageParcel &data, MessageParcel &reply) +{ + std::string abilityName; + if (!data.ReadString(abilityName)) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + sptr abilityToken = data.ReadParcelable(); + ErrCode result = StopBackgroundRunning(abilityName, abilityToken); + if (!reply.WriteInt32(result)) { + BGTASK_LOGE("write result failed, ErrCode=%{public}d", result); + return ERR_BGTASK_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode BackgroundTaskMgrStub::HandleSubscribeBackgroundTask(MessageParcel& data, MessageParcel& reply) { sptr subscriber = data.ReadRemoteObject(); diff --git a/frameworks/src/background_task_subscriber_proxy.cpp b/frameworks/src/background_task_subscriber_proxy.cpp index cdd0a363..1e2d253f 100644 --- a/frameworks/src/background_task_subscriber_proxy.cpp +++ b/frameworks/src/background_task_subscriber_proxy.cpp @@ -25,6 +25,50 @@ BackgroundTaskSubscriberProxy::BackgroundTaskSubscriberProxy(const sptr(impl) {} BackgroundTaskSubscriberProxy::~BackgroundTaskSubscriberProxy() {} +void BackgroundTaskSubscriberProxy::OnConnected() +{ + sptr remote = Remote(); + if (remote == nullptr) { + BGTASK_LOGE("remote is dead."); + return; + } + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { + BGTASK_LOGE("[OnConnected] fail: write interface token failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode ret = remote->SendRequest(ON_CONNECTED, data, reply, option); + if (ret!= ERR_OK) { + BGTASK_LOGE("SendRequest failed, error code: %d", ret); + return; + } +} + +void BackgroundTaskSubscriberProxy::OnDisconnected() +{ + sptr remote = Remote(); + if (remote == nullptr) { + BGTASK_LOGE("remote is dead."); + return; + } + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { + BGTASK_LOGE("[OnDisconnected] fail: write interface token failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode ret = remote->SendRequest(ON_DISCONNECTED, data, reply, option); + if (ret != ERR_OK) { + BGTASK_LOGE("SendRequest failed, error code: %d", ret); + return; + } +} + void BackgroundTaskSubscriberProxy::OnTransientTaskStart(const std::shared_ptr& info) { sptr remote = Remote(); @@ -78,5 +122,75 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskEnd(const std::shared_ptr &continuousTaskCallbackInfo) +{ + BGTASK_LOGI("begin"); + sptr remote = Remote(); + if (remote == nullptr) { + BGTASK_LOGE("remote is dead."); + return; + } + if (continuousTaskCallbackInfo == nullptr) { + BGTASK_LOGE("continuousTaskCallbackInfo is nullptr."); + return; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { + BGTASK_LOGE("write interface token failed."); + return; + } + + if (!data.WriteParcelable(continuousTaskCallbackInfo)) { + BGTASK_LOGI("write continuousTaskCallbackInfo failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = remote->SendRequest(ON_CONTINUOUS_TASK_START, data, reply, option); + if (result != ERR_OK) { + BGTASK_LOGE("SendRequest error"); + return; + } + BGTASK_LOGI("end"); +} + +void BackgroundTaskSubscriberProxy::OnContinuousTaskStop( + const sptr &continuousTaskCallbackInfo) +{ + BGTASK_LOGI("begin"); + sptr remote = Remote(); + if (remote == nullptr) { + BGTASK_LOGE("remote is dead."); + return; + } + if (continuousTaskCallbackInfo == nullptr) { + BGTASK_LOGE("continuousTaskCallbackInfo is nullptr."); + return; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { + BGTASK_LOGE("write interface token failed."); + return; + } + + if (!data.WriteParcelable(continuousTaskCallbackInfo)) { + BGTASK_LOGE("write notification failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = remote->SendRequest(ON_CONTINUOUS_TASK_STOP, data, reply, option); + if (result != ERR_OK) { + BGTASK_LOGE("SendRequest error"); + return; + } + BGTASK_LOGI("end"); +} } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/frameworks/src/background_task_subscriber_stub.cpp b/frameworks/src/background_task_subscriber_stub.cpp index c92ad604..13aa9c45 100644 --- a/frameworks/src/background_task_subscriber_stub.cpp +++ b/frameworks/src/background_task_subscriber_stub.cpp @@ -47,18 +47,42 @@ int BackgroundTaskSubscriberStub::OnRemoteRequest(uint32_t code, } switch (code) { + case ON_CONNECTED: { + return HandleOnConnected(data); + } + case ON_DISCONNECTED: { + return HandleOnDisconnected(data); + } case ON_TRANSIENT_TASK_START: { return HandleOnTransientTaskStart(data); } case ON_TRANSIENT_TASK_END: { return HandleOnTransientTaskEnd(data); } + case ON_CONTINUOUS_TASK_START: { + return HandleOnContinuousTaskStart(data); + } + case ON_CONTINUOUS_TASK_STOP: { + return HandleOnContinuousTaskCancel(data); + } default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } } -int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskStart(MessageParcel& data) +ErrCode BackgroundTaskSubscriberStub::HandleOnConnected(MessageParcel &data) +{ + OnConnected(); + return ERR_OK; +} + +ErrCode BackgroundTaskSubscriberStub::HandleOnDisconnected(MessageParcel &data) +{ + OnDisconnected(); + return ERR_OK; +} + +ErrCode BackgroundTaskSubscriberStub::HandleOnTransientTaskStart(MessageParcel& data) { auto info = TransientTaskAppInfo::Unmarshalling(data); if (info == nullptr) { @@ -69,7 +93,7 @@ int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskStart(MessageParcel& return ERR_NONE; } -int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskEnd(MessageParcel& data) +ErrCode BackgroundTaskSubscriberStub::HandleOnTransientTaskEnd(MessageParcel& data) { auto info = TransientTaskAppInfo::Unmarshalling(data); if (info == nullptr) { @@ -79,5 +103,33 @@ int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskEnd(MessageParcel& da OnTransientTaskEnd(info); return ERR_NONE; } + +ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskStart(MessageParcel &data) +{ + BGTASK_LOGI("begin"); + sptr continuousTaskCallbackInfo = data.ReadParcelable(); + if (!continuousTaskCallbackInfo) { + BGTASK_LOGE("ContinuousTaskCallbackInfo ReadParcelable failed"); + return ERR_BGTASK_PARCELABLE_FAILED; + } + + OnContinuousTaskStart(continuousTaskCallbackInfo); + BGTASK_LOGI("end"); + return ERR_OK; +} + +ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskCancel(MessageParcel &data) +{ + BGTASK_LOGI("begin"); + sptr continuousTaskCallbackInfo = data.ReadParcelable(); + if (!continuousTaskCallbackInfo) { + BGTASK_LOGE("ContinuousTaskCallbackInfo ReadParcelable failed"); + return ERR_BGTASK_PARCELABLE_FAILED; + } + + OnContinuousTaskStop(continuousTaskCallbackInfo); + BGTASK_LOGI("end"); + return ERR_OK; +} } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index c5215865..d8643ec8 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos.gni") import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") -config("bgtaskmgr_public_config") { +config("bgtaskmgr_innerkits_public_config") { include_dirs = [ "include" ] } @@ -22,16 +22,26 @@ ohos_shared_library("bgtaskmgr_innerkits") { sources = [ "src/background_task_mgr_helper.cpp", "src/background_task_subscriber.cpp", + "src/continuous_task_callback_info.cpp", + "src/continuous_task_param.cpp", "src/delay_suspend_info.cpp", "src/expired_callback.cpp", "src/transient_task_app_info.cpp", ] - public_configs = [ ":bgtaskmgr_public_config" ] + public_configs = [ + ":bgtaskmgr_innerkits_public_config", + "//foundation/resourceschedule/background_task_mgr/frameworks:bgtaskmgr_public_config", + ] - deps = [ "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk" ] + public_deps = [ + "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + ] external_deps = [ + "ability_runtime:want", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/interfaces/innerkits/include/background_mode.h b/interfaces/innerkits/include/background_mode.h new file mode 100644 index 00000000..eaeb3051 --- /dev/null +++ b/interfaces/innerkits/include/background_mode.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_BACKGROUND_MODE_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_BACKGROUND_MODE_H + +namespace OHOS { +namespace BackgroundTaskMgr { +class BackgroundMode { +public: + virtual ~BackgroundMode() = default; + enum Type : uint32_t { + DATA_TRANSFER = 1, + AUDIO_PLAYBACK, + AUDIO_RECORDING, + LOCATION, + BLUETOOTH_INTERACTION, + MULTI_DEVICE_CONNECTION, + WIFI_INTERACTION, + VOIP, + TASK_KEEPING, + }; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/innerkits/include/background_task_mgr_helper.h b/interfaces/innerkits/include/background_task_mgr_helper.h index 036369bd..55b4a877 100644 --- a/interfaces/innerkits/include/background_task_mgr_helper.h +++ b/interfaces/innerkits/include/background_task_mgr_helper.h @@ -22,6 +22,24 @@ namespace OHOS { namespace BackgroundTaskMgr { class BackgroundTaskMgrHelper { public: + /** + * request service to keep running background + * + * @param taskParam request params. + * @return Returns ERR_OK on success, others on failure. + */ + static ErrCode RequestStartBackgroundRunning(const ContinuousTaskParam &taskParam); + + /** + * request service to stop running background + * + * @param abilityName ability name of the requester ability + * @param abilityToken ability token to mark an unique running ability instance + * @return Returns ERR_OK on success, others on failure. + */ + static ErrCode RequestStopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken); + /** * Subscribes background task event. * diff --git a/interfaces/innerkits/include/background_task_subscriber.h b/interfaces/innerkits/include/background_task_subscriber.h index 8a885575..701f7407 100644 --- a/interfaces/innerkits/include/background_task_subscriber.h +++ b/interfaces/innerkits/include/background_task_subscriber.h @@ -35,37 +35,87 @@ public: */ virtual ~BackgroundTaskSubscriber(); + /** + * Called back when the subscriber is connected to Background Task Manager Service. + */ + virtual void OnConnected(); + + /** + * Called back when the subscriber is disconnected from Background Task Manager Service. + */ + virtual void OnDisconnected(); + /** * Called back when a transient task start. * * @param info Transient task app info. **/ - virtual void OnTransientTaskStart(const std::shared_ptr& info) = 0; + virtual void OnTransientTaskStart(const std::shared_ptr& info); /** * Called back when a transient task end. * * @param info Transient task app info. **/ - virtual void OnTransientTaskEnd(const std::shared_ptr& info) = 0; + virtual void OnTransientTaskEnd(const std::shared_ptr& info); + + /** + * Called back when a continuous task start. + * + * @param info Transient task app info. + **/ + virtual void OnContinuousTaskStart(const std::shared_ptr &continuousTaskCallbackInfo); + + /** + * Called back when a continuous task end. + * + * @param info Transient task app info. + **/ + virtual void OnContinuousTaskStop(const std::shared_ptr &continuousTaskCallbackInfo); + + /** + * Called back when the Background Task Manager Service has died. + */ + virtual void OnRemoteDied(const wptr &object); private: class BackgroundTaskSubscriberImpl final : public BackgroundTaskSubscriberStub { + public: + class DeathRecipient final : public IRemoteObject::DeathRecipient { + public: + DeathRecipient(BackgroundTaskSubscriberImpl &subscriberImpl); + + ~DeathRecipient(); + + void OnRemoteDied(const wptr &object) override; + + private: + BackgroundTaskSubscriberImpl &subscriberImpl_; + }; + public: BackgroundTaskSubscriberImpl(BackgroundTaskSubscriber &subscriber); ~BackgroundTaskSubscriberImpl() {}; + void OnConnected() override; + void OnDisconnected() override; void OnTransientTaskStart(const std::shared_ptr& info) override; void OnTransientTaskEnd(const std::shared_ptr& info) override; + void OnContinuousTaskStart(const sptr &continuousTaskCallbackInfo) override; + void OnContinuousTaskStop(const sptr &continuousTaskCallbackInfo) override; + bool GetBackgroundTaskMgrProxy(); public: BackgroundTaskSubscriber &subscriber_; + sptr recipient_ {nullptr}; + sptr proxy_ {nullptr}; + std::mutex mutex_ {}; }; private: const sptr GetImpl() const; private: - sptr impl_ = nullptr; + sptr impl_ {nullptr}; friend class BackgroundTaskManager; }; diff --git a/interfaces/innerkits/include/continuous_task_callback_info.h b/interfaces/innerkits/include/continuous_task_callback_info.h new file mode 100644 index 00000000..da802a89 --- /dev/null +++ b/interfaces/innerkits/include/continuous_task_callback_info.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_LONGTIME_TASK_EVENT_DATA_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_LONGTIME_TASK_EVENT_DATA_H + +#include + +#include "parcel.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class ContinuousTaskCallbackInfo : public Parcelable { +public: + ContinuousTaskCallbackInfo(); + ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, pid_t creatorPid, std::string abilityName); + + int32_t GetTypeId(); + uid_t GetCreatorUid(); + pid_t GetCreatorPid(); + std::string GetAbilityName(); + bool Marshalling(Parcel &parcel) const; + static ContinuousTaskCallbackInfo *Unmarshalling(Parcel &parcel); + +private: + bool ReadFromParcel(Parcel &parcel); + +private: + int32_t typeId_ ; + uid_t creatorUid_ ; + pid_t creatorPid_ ; + std::string abilityName_ ; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/innerkits/include/continuous_task_param.h b/interfaces/innerkits/include/continuous_task_param.h new file mode 100644 index 00000000..7b68b9f2 --- /dev/null +++ b/interfaces/innerkits/include/continuous_task_param.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_CONTINUOUS_TASK_PARAMS_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_CONTINUOUS_TASK_PARAMS_H + +#include "iremote_object.h" +#include "parcel.h" +#include "want_agent.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +struct ContinuousTaskParam : public Parcelable { + bool isNewApi_ {false}; + uint32_t bgModeId_ {0}; + std::shared_ptr wantAgent_ {nullptr}; + std::string abilityName_ {""}; + sptr abilityToken_ {nullptr}; + + ContinuousTaskParam() = default; + ContinuousTaskParam(bool isNewApi, uint32_t bgModeId, + const std::shared_ptr wantAgent, const std::string abilityName, + const sptr abilityToken) + : isNewApi_(isNewApi), bgModeId_(bgModeId), wantAgent_(wantAgent), + abilityName_(abilityName), abilityToken_(abilityToken) {} + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static ContinuousTaskParam *Unmarshalling(Parcel &parcel); +}; +} +} + +#endif \ No newline at end of file diff --git a/interfaces/innerkits/src/background_task_mgr_helper.cpp b/interfaces/innerkits/src/background_task_mgr_helper.cpp index 5b57143d..0a98d27a 100644 --- a/interfaces/innerkits/src/background_task_mgr_helper.cpp +++ b/interfaces/innerkits/src/background_task_mgr_helper.cpp @@ -22,6 +22,17 @@ namespace OHOS { namespace BackgroundTaskMgr { +ErrCode BackgroundTaskMgrHelper::RequestStartBackgroundRunning(const ContinuousTaskParam &taskParam) +{ + return DelayedSingleton::GetInstance()->RequestStartBackgroundRunning(taskParam); +} + +ErrCode BackgroundTaskMgrHelper::RequestStopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + return DelayedSingleton::GetInstance()-> + RequestStopBackgroundRunning(abilityName, abilityToken); +} ErrCode BackgroundTaskMgrHelper::SubscribeBackgroundTask(const BackgroundTaskSubscriber &subscriber) { return DelayedSingleton::GetInstance()->SubscribeBackgroundTask(subscriber); diff --git a/interfaces/innerkits/src/background_task_subscriber.cpp b/interfaces/innerkits/src/background_task_subscriber.cpp index f982f16b..b0c2459f 100644 --- a/interfaces/innerkits/src/background_task_subscriber.cpp +++ b/interfaces/innerkits/src/background_task_subscriber.cpp @@ -15,6 +15,9 @@ #include "background_task_subscriber.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + namespace OHOS { namespace BackgroundTaskMgr { BackgroundTaskSubscriber::BackgroundTaskSubscriber() @@ -25,13 +28,55 @@ BackgroundTaskSubscriber::BackgroundTaskSubscriber() BackgroundTaskSubscriber::~BackgroundTaskSubscriber() {} +void BackgroundTaskSubscriber::OnConnected() +{} + +void BackgroundTaskSubscriber::OnDisconnected() +{} + +void BackgroundTaskSubscriber::OnTransientTaskStart(const std::shared_ptr& info) +{} + +void BackgroundTaskSubscriber::OnTransientTaskEnd(const std::shared_ptr& info) +{} + +void BackgroundTaskSubscriber::OnContinuousTaskStart( + const std::shared_ptr &continuousTaskCallbackInfo) +{} + +void BackgroundTaskSubscriber::OnContinuousTaskStop( + const std::shared_ptr &continuousTaskCallbackInfo) +{} + +void BackgroundTaskSubscriber::OnRemoteDied(const wptr &object) +{} + const sptr BackgroundTaskSubscriber::GetImpl() const { return impl_; } BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::BackgroundTaskSubscriberImpl( - BackgroundTaskSubscriber &subscriber) : subscriber_(subscriber) {} + BackgroundTaskSubscriber &subscriber) : subscriber_(subscriber) +{ + recipient_ = new (std::nothrow) DeathRecipient(*this); +} + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnConnected() +{ + if (GetBackgroundTaskMgrProxy()) { + proxy_->AsObject()->AddDeathRecipient(recipient_); + } + subscriber_.OnConnected(); +} + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnDisconnected() +{ + if (GetBackgroundTaskMgrProxy()) { + proxy_->AsObject()->RemoveDeathRecipient(recipient_); + } + subscriber_.OnDisconnected(); +} void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnTransientTaskStart( const std::shared_ptr& info) @@ -44,5 +89,54 @@ void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnTransientTaskEnd( { subscriber_.OnTransientTaskEnd(info); } + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnContinuousTaskStart( + const sptr &continuousTaskCallbackInfo) +{ + subscriber_.OnContinuousTaskStart(std::make_shared(*continuousTaskCallbackInfo)); +} + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnContinuousTaskStop( + const sptr &continuousTaskCallbackInfo) +{ + subscriber_.OnContinuousTaskStop(std::make_shared(*continuousTaskCallbackInfo)); +} + +bool BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::GetBackgroundTaskMgrProxy() +{ + if (proxy_) { + return true; + } + std::lock_guard lock(mutex_); + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + return false; + } + + sptr remoteObject = + systemAbilityManager->GetSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID); + if (!remoteObject) { + return false; + } + + proxy_ = iface_cast(remoteObject); + if ((!proxy_) || (proxy_->AsObject() == nullptr)) { + return false; + } + return true; +} + +BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::DeathRecipient::DeathRecipient( + BackgroundTaskSubscriberImpl &subscriberImpl) : subscriberImpl_(subscriberImpl) {} + +BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::DeathRecipient::~DeathRecipient() {} + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::DeathRecipient::OnRemoteDied( + const wptr &object) +{ + subscriberImpl_.proxy_ = nullptr; + subscriberImpl_.subscriber_.OnRemoteDied(object); +} } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/src/continuous_task_callback_info.cpp b/interfaces/innerkits/src/continuous_task_callback_info.cpp new file mode 100644 index 00000000..15efab7f --- /dev/null +++ b/interfaces/innerkits/src/continuous_task_callback_info.cpp @@ -0,0 +1,98 @@ +/* + * 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 "continuous_task_callback_info.h" +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo() +{} + +ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, + pid_t creatorPid, std::string abilityName) + : typeId_(typeId), creatorUid_(creatorUid), creatorPid_(creatorPid), abilityName_(abilityName) +{} + +int32_t ContinuousTaskCallbackInfo::GetTypeId() +{ + return typeId_; +} + +uid_t ContinuousTaskCallbackInfo::GetCreatorUid() +{ + return creatorUid_; +} + +pid_t ContinuousTaskCallbackInfo::GetCreatorPid() +{ + return creatorPid_; +} + +std::string ContinuousTaskCallbackInfo::GetAbilityName() +{ + return abilityName_; +} + +bool ContinuousTaskCallbackInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(typeId_)) { + BGTASK_LOGE("Failed to write typeId"); + return false; + } + + if (!parcel.WriteInt32(creatorUid_)) { + BGTASK_LOGE("Failed to write creator uid"); + return false; + } + + if (!parcel.WriteInt32(creatorPid_)) { + BGTASK_LOGE("Failed to write creator pid"); + return false; + } + + if (!parcel.WriteString(abilityName_)) { + BGTASK_LOGE("Failed to write ability name"); + return false; + } + return true; +} + +ContinuousTaskCallbackInfo *ContinuousTaskCallbackInfo::Unmarshalling(Parcel &parcel) +{ + auto object = new ContinuousTaskCallbackInfo(); + if ((object != nullptr) && !object->ReadFromParcel(parcel)) { + delete object; + object = nullptr; + } + + return object; +} + +bool ContinuousTaskCallbackInfo::ReadFromParcel(Parcel &parcel) +{ + typeId_ = parcel.ReadInt32(); + + creatorUid_ = static_cast(parcel.ReadInt32()); + creatorPid_ = static_cast(parcel.ReadInt32()); + + if (!parcel.ReadString(abilityName_)) { + BGTASK_LOGE("Failed to read creator ability name"); + return false; + } + return true; +} +} +} \ No newline at end of file diff --git a/interfaces/innerkits/src/continuous_task_param.cpp b/interfaces/innerkits/src/continuous_task_param.cpp new file mode 100644 index 00000000..3ca2ad7a --- /dev/null +++ b/interfaces/innerkits/src/continuous_task_param.cpp @@ -0,0 +1,113 @@ +/* + * 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 "continuous_task_param.h" +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +bool ContinuousTaskParam::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadBool(isNewApi_)) { + BGTASK_LOGE("Failed to read the flag which indicate whether is called from newApi"); + return false; + } + + if (!parcel.ReadUint32(bgModeId_)) { + BGTASK_LOGE("Failed to read request background mode info"); + return false; + } + bool valid = false; + valid = parcel.ReadBool(); + if (valid) { + wantAgent_ = std::shared_ptr( + parcel.ReadParcelable()); + if (!wantAgent_) { + BGTASK_LOGE("Failed to read wantAgent"); + return false; + } + } + + if (!parcel.ReadString(abilityName_)) { + BGTASK_LOGE("Failed to read ability name"); + return false; + } + valid = parcel.ReadBool(); + if (valid) { + abilityToken_ = parcel.ReadParcelable(); + if (!abilityToken_) { + BGTASK_LOGE("Failed to read ablityToken"); + return false; + } + } + + return true; +} + +ContinuousTaskParam *ContinuousTaskParam::Unmarshalling(Parcel &parcel) +{ + ContinuousTaskParam *param = new (std::nothrow) ContinuousTaskParam(); + if (param && !param->ReadFromParcel(parcel)) { + BGTASK_LOGE("read from parcel failed"); + delete param; + param = nullptr; + } + return param; +} + +bool ContinuousTaskParam::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteBool(isNewApi_)) { + BGTASK_LOGE("Failed to write the flag which indicate whether is called from newApi"); + return false; + } + + if (!parcel.WriteUint32(bgModeId_)) { + BGTASK_LOGE("Failed to write request background mode info"); + return false; + } + bool valid = false; + valid = wantAgent_ ? true : false; + if (!parcel.WriteBool(valid)) { + BGTASK_LOGE("Failed to write the flag which indicate whether wantAgent is null"); + return false; + } + if (valid) { + if (!parcel.WriteParcelable(wantAgent_.get())) { + BGTASK_LOGE("Failed to write wantAgent"); + return false; + } + } + + if (!parcel.WriteString(abilityName_)) { + BGTASK_LOGE("Failed to write abilityName"); + return false; + } + + valid = abilityToken_ ? true : false; + if (!parcel.WriteBool(valid)) { + BGTASK_LOGE("Failed to write the flag which indicate whether ability token is null"); + return false; + } + if (valid) { + if (!parcel.WriteParcelable(abilityToken_)) { + BGTASK_LOGE("parcel ability token failed"); + return false; + } + } + return true; +} +} +} \ No newline at end of file diff --git a/interfaces/kits/BUILD.gn b/interfaces/kits/BUILD.gn index 3ce19273..53fc2ef4 100644 --- a/interfaces/kits/BUILD.gn +++ b/interfaces/kits/BUILD.gn @@ -22,6 +22,7 @@ config("bgtaskmgr_public_config") { ohos_shared_library("backgroundtaskmanager") { sources = [ + "napi/src/bg_continuous_task_napi_module.cpp", "napi/src/cancel_suspend_delay.cpp", "napi/src/common.cpp", "napi/src/get_remaining_delay_time.cpp", @@ -34,9 +35,14 @@ ohos_shared_library("backgroundtaskmanager") { deps = [ "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", ] external_deps = [ + "ability_runtime:abilitykit_native", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", diff --git a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts index cbe6ae70..fd8692f5 100644 --- a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts +++ b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts @@ -14,6 +14,8 @@ */ import { AsyncCallback , Callback} from './basic'; +import { WantAgent } from "./@ohos.wantAgent"; +import { Context } from './app/context'; /** * Manages background tasks. @@ -70,6 +72,113 @@ declare namespace backgroundTaskManager { * @return Info of delay request */ function requestSuspendDelay(reason: string, callback: Callback): DelaySuspendInfo; + + /** + * Service ability uses this method to request start running in background. + * system will publish a notification related to the this service. + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + * @permission ohos.permission.KEEP_BACKGROUND_RUNNING + * @param context app running context. + * @param bgMode Indicates which background mode to request. + * @param wantAgent Indicates which ability to start when user click the notification bar. + */ + function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void; + function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise; + + /** + * Service ability uses this method to request stop running in background. + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + * @param context app running context. + */ + function stopBackgroundRunning(context: Context, callback: AsyncCallback): void; + function stopBackgroundRunning(context: Context): Promise; + + /** + * supported background mode. + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + export enum BackgroundMode { + /** + * data transfer mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + DATA_TRANSFER = 1, + + /** + * audio playback mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + AUDIO_PLAYBACK = 2, + + /** + * audio recording mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + AUDIO_RECORDING = 3, + + /** + * location mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + LOCATION = 4, + + /** + * bluetooth interaction mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + BLUETOOTH_INTERACTION = 5, + + /** + * multi-device connection mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + MULTI_DEVICE_CONNECTION = 6, + + /** + * wifi interaction mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + * @systemapi Hide this for inner system use. + */ + WIFI_INTERACTION = 7, + + /** + * Voice over Internet Phone mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + * @systemapi Hide this for inner system use. + */ + VOIP = 8, + + /** + * backgroud continuous calculate mode, for example 3d render. + * only supported in portable computer + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + TASK_KEEPING = 9, + } } export default backgroundTaskManager; diff --git a/interfaces/kits/napi/include/bg_continuous_task_napi_module.h b/interfaces/kits/napi/include/bg_continuous_task_napi_module.h new file mode 100644 index 00000000..a7d35047 --- /dev/null +++ b/interfaces/kits/napi/include/bg_continuous_task_napi_module.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_BG_CONTINUOUS_TASK_NAPI_MODULE_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_BG_CONTINUOUS_TASK_NAPI_MODULE_H + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace BackgroundTaskMgr { + napi_value StartBackgroundRunning(napi_env env, napi_callback_info info); + napi_value StopBackgroundRunning(napi_env env, napi_callback_info info); +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_CANCEL_SUSPEND_DELAY_H \ No newline at end of file diff --git a/interfaces/kits/napi/include/init.h b/interfaces/kits/napi/include/init.h index 435dccc6..876eddca 100644 --- a/interfaces/kits/napi/include/init.h +++ b/interfaces/kits/napi/include/init.h @@ -26,7 +26,9 @@ extern "C" { #endif __attribute__((constructor)) void RegisterModule(void); +void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const char *propName); napi_value BackgroundTaskMgrInit(napi_env env, napi_value exports); +napi_value BackgroundModeInit(napi_env env, napi_value exports); static napi_value Init(napi_env env, napi_value exports); #ifdef __cplusplus diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp new file mode 100644 index 00000000..630d32b5 --- /dev/null +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -0,0 +1,458 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bg_continuous_task_napi_module.h" +#include "bgtaskmgr_inner_errors.h" +#include "continuous_task_log.h" +#include "background_mode.h" +#include "continuous_task_param.h" +#include "ability.h" +#include "background_task_mgr_helper.h" +#include "fcntl.h" +#include "want_agent.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static constexpr uint32_t MAX_START_BG_RUNNING_PARAMS = 4; +static constexpr uint32_t MAX_STOP_BG_RUNNING_PARAMS = 2; +static constexpr uint32_t CALLBACK_RESULT_PARAMS_NUM = 2; +static constexpr int32_t BG_MODE_ID_BEGIN = 1; +static constexpr int32_t BG_MODE_ID_END = 9; +} + +struct AsyncCallbackInfo { + napi_env env {nullptr}; + napi_ref callback {nullptr}; + napi_async_work asyncWork {nullptr}; + napi_deferred deferred {nullptr}; + AppExecFwk::Ability *ability {nullptr}; + int32_t bgMode {0}; + Notification::WantAgent::WantAgent *wantAgent {nullptr}; + int errCode {0}; +}; + +napi_value WrapVoidToJS(napi_env env) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value WrapUndefinedToJS(napi_env env) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &result)); + return result; +} + +napi_value GetCallbackErrorValue(napi_env env, int errCode) +{ + napi_value jsObject = nullptr; + napi_value jsValue = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &jsValue)); + NAPI_CALL(env, napi_create_object(env, &jsObject)); + NAPI_CALL(env, napi_set_named_property(env, jsObject, "code", jsValue)); + return jsObject; +} + +AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env) +{ + BGTASK_LOGI("begin"); + if (env == nullptr) { + BGTASK_LOGE("env == nullptr."); + return nullptr; + } + + napi_status ret; + napi_value global = 0; + const napi_extended_error_info *errorInfo = nullptr; + ret = napi_get_global(env, &global); + if (ret != napi_ok) { + napi_get_last_error_info(env, &errorInfo); + BGTASK_LOGE("get_global=%{public}d err:%{public}s", ret, errorInfo->error_message); + } + + napi_value abilityObj = 0; + ret = napi_get_named_property(env, global, "ability", &abilityObj); + if (ret != napi_ok) { + napi_get_last_error_info(env, &errorInfo); + BGTASK_LOGE("get_named_property=%{public}d err:%{public}s", ret, errorInfo->error_message); + } + + OHOS::AppExecFwk::Ability *ability = nullptr; + ret = napi_get_value_external(env, abilityObj, (void **)&ability); + if (ret != napi_ok) { + napi_get_last_error_info(env, &errorInfo); + BGTASK_LOGE("get_value_external=%{public}d err:%{public}s", ret, errorInfo->error_message); + } + + AsyncCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo; + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullptr"); + return nullptr; + } + asyncCallbackInfo->env = env; + asyncCallbackInfo->asyncWork = nullptr; + asyncCallbackInfo->deferred = nullptr; + asyncCallbackInfo->ability = ability; + asyncCallbackInfo->errCode = ERR_OK; + + BGTASK_LOGI("end"); + return asyncCallbackInfo; +} + +void StartBackgroundRunningExecuteCB(napi_env env, void *data) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullptr"); + return; + } + if (asyncCallbackInfo->errCode != ERR_OK) { + BGTASK_LOGE("input params parse failed"); + return; + } + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + BGTASK_LOGE("ability == nullptr"); + return; + } + const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); + if (info == nullptr) { + BGTASK_LOGE("info == nullptr"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; + } + + if (asyncCallbackInfo->wantAgent == nullptr) { + BGTASK_LOGE("wantAgent param is nullptr"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; + } + + if (asyncCallbackInfo->bgMode < BG_MODE_ID_BEGIN || asyncCallbackInfo->bgMode > BG_MODE_ID_END) { + BGTASK_LOGE("request background mode id: %{public}d out of range", asyncCallbackInfo->bgMode); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; + } + + ContinuousTaskParam taskParam = ContinuousTaskParam(true, asyncCallbackInfo->bgMode, + std::make_shared(*asyncCallbackInfo->wantAgent), info->name, nullptr); + asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam); + + BGTASK_LOGI("end"); +} + +void CallbackCompletedCB(napi_env env, napi_status status, void *data) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + napi_value callback = 0; + napi_value undefined = 0; + napi_value result[CALLBACK_RESULT_PARAMS_NUM] = {0}; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + if (asyncCallbackInfo->errCode == ERR_OK) { + result[0] = WrapUndefinedToJS(env); + napi_create_int32(env, 0, &result[1]); + } else { + result[1] = WrapUndefinedToJS(env); + result[0] = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + } + + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_call_function(env, undefined, callback, CALLBACK_RESULT_PARAMS_NUM, result, &callResult); + + if (asyncCallbackInfo->callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + BGTASK_LOGI("end"); +} + +void PromiseCompletedCB(napi_env env, napi_status status, void *data) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + napi_value result = 0; + if (asyncCallbackInfo->errCode == ERR_OK) { + napi_create_int32(env, 0, &result); + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + } else { + result = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + napi_reject_deferred(env, asyncCallbackInfo->deferred, result); + } + + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + BGTASK_LOGI("end"); + delete asyncCallbackInfo; +} + +napi_value StartBackgroundRunningAsync( + napi_env env, napi_value *argv, const size_t argCallback, AsyncCallbackInfo *asyncCallbackInfo) +{ + BGTASK_LOGI("begin"); + if (argv == nullptr || asyncCallbackInfo == nullptr) { + BGTASK_LOGE("param == nullptr"); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[argCallback], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_CALL(env, napi_create_reference(env, argv[argCallback], 1, &asyncCallbackInfo->callback)); + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + StartBackgroundRunningExecuteCB, + CallbackCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + BGTASK_LOGI("end"); + return WrapVoidToJS(env); +} + +napi_value StartBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +{ + BGTASK_LOGI("begin"); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("param == nullptr"); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + StartBackgroundRunningExecuteCB, + PromiseCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + BGTASK_LOGI("end"); + return promise; +} + +napi_value GetBackgroundMode(const napi_env &env, const napi_value &value, int32_t &bgMode) +{ + BGTASK_LOGI("begin"); + + napi_valuetype valuetype = napi_undefined; + + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, value, &bgMode); + + BGTASK_LOGI("get bgmode info: %{public}d", bgMode); + + return WrapVoidToJS(env); +} + +napi_value GetWantAgent(const napi_env &env, const napi_value &value, Notification::WantAgent::WantAgent *&wantAgent) +{ + BGTASK_LOGI("begin"); + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + napi_unwrap(env, value, (void **)&wantAgent); + + BGTASK_LOGI("end"); + return WrapVoidToJS(env); +} + +napi_value StartBackgroundRunning(napi_env env, napi_callback_info info) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullpter"); + return WrapVoidToJS(env); + } + + size_t argc = MAX_START_BG_RUNNING_PARAMS; + napi_value argv[MAX_START_BG_RUNNING_PARAMS] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc > MAX_START_BG_RUNNING_PARAMS) { + BGTASK_LOGE("wrong param nums"); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return nullptr; + } + + // argv[1] : bgMode : BackgroundMode + if (GetBackgroundMode(env, argv[1], asyncCallbackInfo->bgMode) == nullptr) { + BGTASK_LOGE("input bgmode param not number"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + } + + // argv[2] : wantAgent: WantAgent + if (GetWantAgent(env, argv[2], asyncCallbackInfo->wantAgent) == nullptr) { + BGTASK_LOGE("input wantAgent param is not object"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + } + + napi_value ret = 0; + + if (argc == MAX_START_BG_RUNNING_PARAMS) { + ret = StartBackgroundRunningAsync(env, argv, MAX_START_BG_RUNNING_PARAMS - 1, asyncCallbackInfo); + } else { + ret = StartBackgroundRunningPromise(env, asyncCallbackInfo); + } + + if (ret == nullptr) { + BGTASK_LOGE("ret == nullpter"); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + ret = WrapVoidToJS(env); + } + BGTASK_LOGI("end"); + return ret; +} + +void StopBackgroundRunningExecuteCB(napi_env env, void *data) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullptr"); + return; + } + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + BGTASK_LOGE("ability == nullptr"); + return; + } + const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); + if (info == nullptr) { + BGTASK_LOGE("abilityInfo == nullptr"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; + } + asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStopBackgroundRunning(info->name, nullptr); +} + +napi_value StopBackgroundRunningAsync(napi_env env, napi_value *argv, + const size_t argCallback, AsyncCallbackInfo *asyncCallbackInfo) +{ + BGTASK_LOGI("begin"); + if (argv == nullptr || asyncCallbackInfo == nullptr) { + BGTASK_LOGE("param == nullptr"); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, argv[argCallback], 1, &asyncCallbackInfo->callback)); + } + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + StopBackgroundRunningExecuteCB, + CallbackCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + BGTASK_LOGI("end"); + return WrapVoidToJS(env); +} + +napi_value StopBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +{ + BGTASK_LOGI("begin"); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("param == nullptr"); + return nullptr; + } + napi_value resourceName = 0; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_deferred deferred; + napi_value promise = 0; + napi_create_promise(env, &deferred, &promise); + + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work( + env, + nullptr, + resourceName, + StopBackgroundRunningExecuteCB, + PromiseCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + BGTASK_LOGI("end"); + return promise; +} + +napi_value StopBackgroundRunning(napi_env env, napi_callback_info info) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullpter"); + return WrapVoidToJS(env); + } + + size_t argc = MAX_STOP_BG_RUNNING_PARAMS; + napi_value argv[MAX_STOP_BG_RUNNING_PARAMS] = {nullptr}; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc > MAX_STOP_BG_RUNNING_PARAMS) { + BGTASK_LOGE("wrong param nums"); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return nullptr; + } + + napi_value ret = 0; + if (argc == MAX_STOP_BG_RUNNING_PARAMS) { + ret = StopBackgroundRunningAsync(env, argv, MAX_STOP_BG_RUNNING_PARAMS - 1, asyncCallbackInfo); + } else { + ret = StopBackgroundRunningPromise(env, asyncCallbackInfo); + } + + if (ret == nullptr) { + BGTASK_LOGE("ret == nullpter"); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + ret = WrapVoidToJS(env); + } + BGTASK_LOGI("end"); + return ret; +} +} // namespace BackgroundTaskMgr +} \ No newline at end of file diff --git a/interfaces/kits/napi/src/init.cpp b/interfaces/kits/napi/src/init.cpp index 03918a74..5b7c832e 100644 --- a/interfaces/kits/napi/src/init.cpp +++ b/interfaces/kits/napi/src/init.cpp @@ -15,6 +15,8 @@ #include "init.h" +#include "background_mode.h" +#include "bg_continuous_task_napi_module.h" #include "cancel_suspend_delay.h" #include "get_remaining_delay_time.h" #include "request_suspend_delay.h" @@ -31,6 +33,8 @@ napi_value BackgroundTaskMgrInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("requestSuspendDelay", RequestSuspendDelay), DECLARE_NAPI_FUNCTION("cancelSuspendDelay", CancelSuspendDelay), DECLARE_NAPI_FUNCTION("getRemainingDelayTime", GetRemainingDelayTime), + DECLARE_NAPI_FUNCTION("startBackgroundRunning", StartBackgroundRunning), + DECLARE_NAPI_FUNCTION("stopBackgroundRunning", StopBackgroundRunning), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); @@ -38,6 +42,39 @@ napi_value BackgroundTaskMgrInit(napi_env env, napi_value exports) return exports; } +void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const char *propName) +{ + napi_value prop = nullptr; + if (napi_create_int32(env, objName, &prop) == napi_ok) { + napi_set_named_property(env, dstObj, propName, prop); + } +} + +napi_value BackgroundModeInit(napi_env env, napi_value exports) +{ + BGTASK_LOGI("begin"); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::DATA_TRANSFER, "DATA_TRANSFER"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::AUDIO_PLAYBACK, "AUDIO_PLAYBACK"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::AUDIO_RECORDING, "AUDIO_RECORDING"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::LOCATION, "LOCATION"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::BLUETOOTH_INTERACTION, "BLUETOOTH_INTERACTION"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::MULTI_DEVICE_CONNECTION, "MULTI_DEVICE_CONNECTION"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::WIFI_INTERACTION, "WIFI_INTERACTION"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::VOIP, "VOIP"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::TASK_KEEPING, "TASK_KEEPING"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("BackgroundMode", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + /* * Module export function */ @@ -47,6 +84,7 @@ static napi_value Init(napi_env env, napi_value exports) * Propertise define */ BackgroundTaskMgrInit(env, exports); + BackgroundModeInit(env, exports); return exports; } diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn index a130cd20..40c48381 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/BUILD.gn @@ -14,6 +14,12 @@ import("//build/test.gni") module_output_path = "background_task_mgr/interfaces" +ohos_js_unittest("ContinuousTaskJsTest") { + module_out_path = module_output_path + hap_profile = "./continuous_task_jsunittest/config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" +} + ohos_js_unittest("TransientTaskJsTest") { module_out_path = module_output_path hap_profile = "./transient_task_jsunittest/config.json" @@ -22,5 +28,8 @@ ohos_js_unittest("TransientTaskJsTest") { group("js_unittest") { testonly = true - deps = [ ":TransientTaskJsTest" ] + deps = [ + ":ContinuousTaskJsTest", + ":TransientTaskJsTest", + ] } diff --git a/interfaces/test/unittest/continuous_task_jsunittest/config.json b/interfaces/test/unittest/continuous_task_jsunittest/config.json new file mode 100644 index 00000000..b2980353 --- /dev/null +++ b/interfaces/test/unittest/continuous_task_jsunittest/config.json @@ -0,0 +1,74 @@ +{ + "app": { + "bundleName": "com.continuoustask.test", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 7, + "target": 7 + } + }, + "deviceConfig": {}, + "module": { + "package": "com.continuoustask.test", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [ + { + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "backgroundModes": [ + "dataTransfer" + ], + "name": "com.continuoustask.test.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ], + "defPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } + ] + } + } + \ No newline at end of file diff --git a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js new file mode 100644 index 00000000..c8851ad5 --- /dev/null +++ b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js @@ -0,0 +1,386 @@ +/* + * 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 notification from '@ohos.notification'; +import wantAgent from '@ohos.wantAgent'; +import particleAbility from '@ohos.ability.particleAbility' +import backgroundTaskManager from '@ohos.backgroundTaskManager' +import featureAbility from '@ohos.ability.featureAbility' + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +describe("ContinuousTaskJsTest", function () { + beforeAll(function() { + /* + * @tc.setup: setup invoked before all testcases + */ + console.info('beforeAll called') + }) + + afterAll(function() { + /* + * @tc.teardown: teardown invoked after all testcases + */ + console.info('afterAll called') + }) + + beforeEach(function() { + /* + * @tc.setup: setup invoked before each testcases + */ + console.info('beforeEach called') + }) + + afterEach(function() { + /* + * @tc.teardown: teardown invoked after each testcases + */ + console.info('afterEach called') + particleAbility.cancelBackgroundRunning(); + setTimeout(() => {}, 500); + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()); + setTimeout(() => {}, 500); + }) + + /* + * @tc.name:ContinuousTaskJsTest001 + * @tc.desc:verify new startBackgroundrunning interface promise mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO + */ + it("ContinuousTaskJsTest001", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then(() => { + console.log("ContinuousTaskJsTest001 startBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest001 startBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest002 + * @tc.desc:verify new startBackgroundrunning interface callback mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 + */ + it("ContinuousTaskJsTest002", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest002 startBackgroundRunning failed'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest002 startBackgroundRunning succeed'); + expect(true).assertTrue(); + } + setTimeout(()=>{ + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data, conTaskCallback); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest003 + * @tc.desc:verify old startBackgroundrunning interface promise mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH56K + */ + it("ContinuousTaskJsTest003", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + let basicContent = { + title: "title", + text: "text" + }; + + let notificationContent = { + contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: basicContent + }; + + let request = { + content: notificationContent, + wantAgent: data + } + + let id = 1; + + particleAbility.startBackgroundRunning(id, request).then((data) => { + console.log("ContinuousTaskJsTest003 startBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest003 startBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest004 + * @tc.desc:verify old startBackgroundrunning interface callback mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH6ET + */ + it("ContinuousTaskJsTest004", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest004 startBackgroundRunning failure'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest004 startBackgroundRunning success'); + expect(true).assertTrue(); + } + setTimeout(()=>{ + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + let basicContent = { + title: "title", + text: "text" + }; + + let notificationContent = { + contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: basicContent + }; + + let request = { + content: notificationContent, + wantAgent: data + } + + let id = 1; + + particleAbility.startBackgroundRunning(id, request, conTaskCallback); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest005 + * @tc.desc:verify new api stopBackgroundrunning interface promise mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EM AR000GH6EN AR000GH6EO + */ + it("ContinuousTaskJsTest005", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then((data) => { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then((data) => { + console.log("ContinuousTaskJsTest005 cancelBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest005 cancelBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); + }) + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest006 + * @tc.desc:verify new api stopBackgroundrunning interface callback mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EP AR000GJ9PR AR000GH6G8 + */ + it("ContinuousTaskJsTest006", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest006 startBackgroundRunning failure'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest006 startBackgroundRunning success'); + expect(true).assertTrue(); + } + setTimeout(()=>{ + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then((data) => { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), conTaskCallback); + }) + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest007 + * @tc.desc:verify old api cancelBackgroundrunning interface promise mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K + */ + it("ContinuousTaskJsTest007", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + await wantAgent.getWantAgent(wantAgentInfo).then((data) => { + particleAbility.startBackgroundRunning(data); + setTimeout(()=>{ + }, 500); + }); + + particleAbility.cancelBackgroundRunning().then(() => { + console.log("ContinuousTaskJsTest007 cancelBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch( (err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest007 cancelBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest008 + * @tc.desc:verify old cancelBackgroundrunning interface callback mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH6ET + */ + it("ContinuousTaskJsTest008", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest008 startBackgroundRunning failure'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest008 startBackgroundRunning success'); + expect(true).assertTrue(); + } + setTimeout(()=>{ + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + await wantAgent.getWantAgent(wantAgentInfo).then((data) => { + particleAbility.startBackgroundRunning(data); + setTimeout(()=>{ + }, 500); + }); + + particleAbility.cancelBackgroundRunning(conTaskCallback); + }) +}) \ No newline at end of file diff --git a/resources/BUILD.gn b/resources/BUILD.gn new file mode 100644 index 00000000..7cc33240 --- /dev/null +++ b/resources/BUILD.gn @@ -0,0 +1,33 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("bgtaskmgr_resources") { + deps = [ ":backgroundtaskresources_hap" ] +} + +ohos_resources("backgroundtask_res") { + sources = [ "main/resources" ] + hap_profile = "./main/config.json" +} + +ohos_hap("backgroundtaskresources_hap") { + deps = [ ":backgroundtask_res" ] + hap_profile = "./main/config.json" + hap_name = "BackgroundTaskResources" + module_install_dir = "app" + certificate_profile = "./BackgroundTaskResources.p7b" + subsystem_name = "resourceschedule" + part_name = "background_task_mgr" +} diff --git a/resources/BackgroundTaskResources.p7b b/resources/BackgroundTaskResources.p7b new file mode 100644 index 0000000000000000000000000000000000000000..4c50cd1fa2a5f3336d1b57d2d44182893b1aeba2 GIT binary patch literal 3401 zcmcgvYg7|w8YUN@2oV$&WmO<5STXobNC?ncJCo}GlaP=QLgV5jnOsPi3Ar#yTrG`T z>ZNLJ&nm5#qA2Qm>8{!$yIX6!TU~3tRoBzHqN^@vSJ&2dwXLhG-5KN{^yrU0J;(gW zocHF_j#Xh2E+x*q?8$Lnzru+oMdiCTu=hy0x_4vfzp8>DP>-phC}f9Tux#F zi1RN$OyzXM`KS4D{)zd*79tSzP^5^&n+RdK5Gn#iKsa*{wo?uUhGq(JzhC6=1VaIj zEgWJegra_S0u^lVkRieqz*&@;84i0K3@!y?nXRmh5J{cPpQJ?U5S2+msR%D408}h- zIti$heGcyPI6R@KuzbFdq(UMa;iLlW6H6qLVwo5!W**JrxHCiqSXd@41EmbSV5V?@ zL4fcPc#vRjW($)JA0hIPPKv#sgJ>aql%EKQ`WaDfDmVx+*~3<2Cjudl(__a&?4m^M z4^gU7ZLVBtFrq3{4jYyIsFlP}RIYB6%VAvZf@u_iT_{RG&1fhbDN!{6TJEx-l~g?% zYXnM|#%N1SS%tw~H4K@Qh#QkzNj;E6R0_BTacOH2m@>*i8C`FdqL#XfkWDO=Vg@g* zqAiMAy}n8rL8|TQ+Hj3p6}6em!bA;XvXb>?RS2uWXjI>yrBFuvKh8qz8YGCDwQh&n z*JAS^3cV2~R5XZUMkURx!f2v(Ml6ac5S&3{EQ%SiK@3xtM&w3V^MIqp2rHBo7;Nuf zg&e_P<_>xTxm#4m{bf0yE@{xh*bb*)`h9Ow34=H z26j#k>j!sH0qgAwy$e>V>trRevf_ZM3b#152x=usuLYv0I;lE{fm*T26spj~sFFx9 z(xi0Iphg@m4eF87Vys?mj%mX&*c6;)u6N3VDj2Q6ER|6!X(p>>v1V-zrh;h=yPF1} zLlBEnr4z^0GL248k*Z3+E@lh^HE=~~6t$ojEMfP-p`ewBm7GQEnL48ymjZUOyQQhY zlxhWRb|FTaJ7D*yLZ&Lp6fQ2Vsg;GDN|h5wLxvb!iMU+NZf~Q`N>=Oj3YgYXumbVH zjfmP2sjZTc9-X?en21Cog@p>t8?H8atF30q8C7~~D4!czzm%{0jk`jgADQS`zH1!6R!d>CBd)$Ry646^=jo0P2 zk`*O7g$6K6}fzr4fhqo79zyAbC+$UVn5l{LO#JSIcIOl^79+$)A@?~3_4uG_zrx=$!KAX?u zF;-}YQb9@*&%{s4+3A_oK0`k}) zUS{^tA=vNtvHrpE&y~Yqa+W|00WlCmV&*EX&k{(=AaOA?5CZ>CBmqFt0}=&~BT*fo zoE{&MYk1&~zydOplKZ!T%Nf`Y9w(WHB=F5Axc}(k%brIIZYwC8aC zxogIsUcGSs(qwF#>|5Sv-y9;jg~mBKAN;vPzba+iAK#E1=aI_}jeo1t0IER_Lub+y z{&+C1bF=W&x;!6Y^w$sflba}>Y& z{??fG%!yy^{pIze~svIC+!)%K7&?0 zcklY9_U_BbO2>KUx0klwy0kp0WZwN>uV(2xIIsBI z()?aS_Cbz(+tsOiJEa+s?e~KV`~IH3m(h=c(a(_q{iI(iT{fHxaR0>8O$Yf8N|*Dv z(itc!^dk{L5~y^Di2B1P$fN~iJQPo2;Y<7kAuv}t4&9$lePxH6 zD(ClzQrES-f6Zb!^}^as&&Th)ciO^NFT>RB{?*8qogKG&8txjq(nj{$7q9$WJ*x9% z!G-->Hr;I)dpAF4S)e!f=}G#a1zjjhR)5`zfagIvE0j!DIEjGAT!t%&lQcw0S>+iU zcTD(2UxIGusrG_B?e+A?W5cV*b0q)=7tr-|0d(wpdfRhr)}O80w{mwu*NEjO()O44 zOn$j_hBRi~vT>ql!2!DEBpML zTh_0;1=cj{Rz=Tl%{o)qbzD8ZEs@a?&giIbKu42_gR_S-d4km&Vn&d(SUglmZ1`jx z@i7w0+wj%l_3va!cP;&7bHhKb!qW=)SF+!}c{;R6zI$8Jce`#BWFI~IhTwPmWt$iJ z>y{i|_%r{Wmag|cH30Lzb8DuTRKMH(&PQvr*KN7EWJ$)&Q|)<6ZofEhUt!MeYez1v zxFa%k+5tYyoF1u>|3hPsG`C?V49}ea2rg(k|MSvCZ-#EX_?z41?uPA$OEz3Nka75I z=9LA`3|*hbba6@R1a~+3?=#oB$9{J0>?p>p4n0ND+sgwR4c+;oyYJTR{CM^1jE{WJ z^p1;9ytnv*c6p$01%AbE2`zVhB6<6nb45^`BWFZ5hk4}(-X~JVffIH3*F}d1j34~E zNZ~=LgF!L}OdJeS5}|bFSY!@GP}YAmLiJ$Q!%;pY(3)1%x+5+5bLm0fo7uPWE?)Vf zX&Z83bag&Y!Of+*Uh3TX+HcdR{b5YwK5+93{m7g &handler); + void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); + bool Subscribe(); + bool Unsubscribe(); + +private: + bool Connect(); + void Disconnect(); + void OnRemoteDied(const wptr &object); + +private: + std::mutex mutex_ {}; + std::weak_ptr handler_ {}; + std::weak_ptr bgContinuousTaskMgr_ {}; + sptr appMgrProxy_ {nullptr}; + sptr appMgrDeathRecipient_ {nullptr}; +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h new file mode 100644 index 00000000..562e24d6 --- /dev/null +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BG_CONTINUOUS_TASK_MGR_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BG_CONTINUOUS_TASK_MGR_H + +#include +#include + +#include "ipc_skeleton.h" +#include "iremote_object.h" +#include "resource_manager.h" +#include "singleton.h" + +#include "app_state_observer.h" +#include "bgtaskmgr_inner_errors.h" +#include "bundle_info.h" +#include "continuous_task_callback_info.h" +#include "task_notification_subscriber.h" +#include "continuous_task_param.h" +#include "continuous_task_record.h" +#include "ibackground_task_subscriber.h" +#include "remote_death_recipient.h" +#include "system_event_observer.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class BackgroundTaskMgrService; + +enum class ContinuousTaskEventTriggerType: uint32_t { + TASK_START, + TASK_CANCEL, +}; + +struct CachedBundleInfo { + std::unordered_map abilityBgMode_ {}; + std::string appName_ {""}; +}; + +class BgContinuousTaskMgr : public DelayedSingleton, + public std::enable_shared_from_this { +public: + ErrCode StartBackgroundRunning(const sptr taskParam); + + ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken); + + ErrCode AddSubscriber(const sptr &subscriber); + + ErrCode RemoveSubscriber(const sptr &subscriber); + + ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); + + bool StopContinuousTaskByUser(const std::string &mapKey); + + void OnBundleInfoChanged(const std::string &action, const std::string &bundleName, uid_t uid); + + void OnProcessDied(int32_t pid); + + void OnRemoteSubscriberDied(const wptr &object); + + bool Init(); + + void InitNecessaryState(); + + void Clear(); + +private: + ErrCode StartBackgroundRunningInner(std::shared_ptr &continuousTaskRecordPtr); + + ErrCode StopBackgroundRunningInner(uid_t uid, const std::string &abilityName, + const sptr &abilityToken); + + ErrCode AddSubscriberInner(const sptr &subscriber); + + ErrCode RemoveSubscriberInner(const sptr &subscriber); + + ErrCode ShellDumpInner(const std::vector &dumpOption, std::vector &dumpInfo); + + void DumpAllTaskInfo(std::vector &dumpInfo); + + void DumpCancelTask(const std::vector &dumpOption, bool cleanAll); + + ErrCode SendContinuousTaskNotification(std::shared_ptr &ContinuousTaskRecordPtr); + + bool RemoveContinuousTaskRecord(const std::string &mapKey); + + bool InitAllBundleBriefInfos(); + + bool AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); + + std::string CreateNotificationLabel(uid_t uid, const std::string &bundleName, + const std::string &abilityName, sptr abilityToken); + + uint32_t GetBackgroundModeInfo(uid_t uid, std::string &abilityName); + + bool AddAbilityBgModeInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); + + bool RegisterNotificationSubscriber(); + + bool RegisterSysCommEventListener(); + + bool RegisterAppStateObserver(); + + bool GetContinuousTaskText(); + + bool SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName); + + void OnRemoteSubscriberDiedInner(const wptr &object); + + std::string CreateNotificationText(int32_t typeId); + + void OnContinuousTaskChanged(const std::shared_ptr continuousTaskInfo, + ContinuousTaskEventTriggerType changeEventType); + +private: + std::atomic isSysReady_ {false}; + std::shared_ptr runner_ {nullptr}; + std::shared_ptr handler_ {nullptr}; + std::unordered_map> continuousTaskInfosMap_ {}; + std::shared_ptr subscriber_ {nullptr}; + std::shared_ptr systemEventListener_ {nullptr}; + std::shared_ptr appStateObserver_ {nullptr}; + std::list> bgTaskSubscribers_ {}; + std::map, sptr> subscriberRecipients_ {}; + std::unordered_map cachedBundleInfos_ {}; + std::vector continuousTaskText_ {}; + + DECLARE_DELAYED_SINGLETON(BgContinuousTaskMgr); +}; +} +} + +#endif \ No newline at end of file diff --git a/services/continuous_task/include/bundle_manager_helper.h b/services/continuous_task/include/bundle_manager_helper.h new file mode 100644 index 00000000..e18af8c1 --- /dev/null +++ b/services/continuous_task/include/bundle_manager_helper.h @@ -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 FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BUNDLE_MANAGER_HELPER_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BUNDLE_MANAGER_HELPER_H + +#include "bundle_mgr_interface.h" +#include "ipc_skeleton.h" +#include "iremote_object.h" +#include "resource_manager.h" +#include "singleton.h" + +#include "remote_death_recipient.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +using OHOS::AppExecFwk::Constants::UNSPECIFIED_USERID; +class BundleManagerHelper : public DelayedSingleton { +public: + std::string GetClientBundleName(uid_t uid); + bool CheckPermission(const std::string &bundleName, const std::string &permission); + bool IsSystemApp(uid_t uid); + bool GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, + AppExecFwk::BundleInfo &bundleInfo, int32_t userId = UNSPECIFIED_USERID); + +private: + bool Connect(); + void Disconnect(); + + void OnRemoteDied(const wptr &object); + +private: + sptr bundleMgr_ = nullptr; + std::mutex connectionMutex_; + sptr bundleMgrDeathRecipient_ = nullptr; + + DECLARE_DELAYED_SINGLETON(BundleManagerHelper) +}; +} +} + +#endif \ No newline at end of file diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h new file mode 100644 index 00000000..c20aa1cf --- /dev/null +++ b/services/continuous_task/include/continuous_task_record.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_CONTINUOUS_TASK_INFO_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_CONTINUOUS_TASK_INFO_H + +#include "iremote_object.h" +#include "parcel.h" +#include "want_agent.h" + +#include "task_notification_subscriber.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +extern const char *ContinuousTaskModeName[10]; + +class ContinuousTaskRecord { +public: + ContinuousTaskRecord() = default; + + ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, + const std::shared_ptr &wantAgent, const sptr &abilityToken, + int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi); + + std::string GetBundleName() const; + + std::string GetAbilityName() const; + + bool IsNewApi() const; + + uint32_t GetBgModeId() const; + + int32_t GetUserId() const; + + uid_t GetUid() const; + + pid_t GetPid() const; + + std::string GetNotificationLabel() const; + + std::shared_ptr GetWantAgent() const; + + sptr GetAbilityToken() const; + +private: + std::string bundleName_ {""}; + std::string abilityName_ {""}; + std::shared_ptr wantAgent_ {nullptr}; + sptr abilityToken_ {nullptr}; + int32_t userId_ {0}; + uid_t uid_ {0}; + pid_t pid_ {0}; + uint32_t bgModeId_ {0}; + bool isNewApi_ {false}; + std::string notificationLabel_ {""}; + + friend class BgContinuousTaskMgr; +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/include/remote_death_recipient.h b/services/continuous_task/include/remote_death_recipient.h new file mode 100644 index 00000000..f6938123 --- /dev/null +++ b/services/continuous_task/include/remote_death_recipient.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_REMOTE_DEATH_RECIPIENT_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_REMOTE_DEATH_RECIPIENT_H + +#include + +#include "iremote_object.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class RemoteDeathRecipient : public IRemoteObject::DeathRecipient { +public: + RemoteDeathRecipient(std::function &)> callback) + { + callback_ = callback; + } + ~RemoteDeathRecipient() + { + callback_ = nullptr; + } + + void OnRemoteDied(const wptr &object) + { + if (callback_ != nullptr) { + callback_(object); + } + } + +private: + std::function &)> callback_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/include/system_event_observer.h b/services/continuous_task/include/system_event_observer.h new file mode 100644 index 00000000..734e5150 --- /dev/null +++ b/services/continuous_task/include/system_event_observer.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_SYSTEM_EVENT_OBSERVER_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_SYSTEM_EVENT_OBSERVER_H + +#include "common_event_manager.h" +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.h" +#include "event_handler.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class BgContinuousTaskMgr; +class SystemEventObserver : public EventFwk::CommonEventSubscriber, + public std::enable_shared_from_this { +public: + SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo); + ~SystemEventObserver() = default; + + void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; + + void SetEventHandler(const std::shared_ptr &handler); + void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); + + bool Subscribe(); + + bool Unsubscribe(); + +private: + std::weak_ptr handler_; + std::weak_ptr bgContinuousTaskMgr_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/include/task_notification_subscriber.h b/services/continuous_task/include/task_notification_subscriber.h new file mode 100644 index 00000000..d16a06c5 --- /dev/null +++ b/services/continuous_task/include/task_notification_subscriber.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_NOTIFICATION_SUBSCRIBER_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_NOTIFICATION_SUBSCRIBER_H + +#include "notification_helper.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class BgContinuousTaskMgr; + +class TaskNotificationSubscriber : public Notification::NotificationSubscriber { +public: + TaskNotificationSubscriber(); + + virtual ~TaskNotificationSubscriber(); + + virtual void OnConnected() override; + + virtual void OnDisconnected() override; + + virtual void OnCanceled(const std::shared_ptr &request) override; + + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override; + + virtual void OnConsumed(const std::shared_ptr &request) override; + + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override; + + virtual void OnUpdate(const std::shared_ptr &sortingMap) override; + + virtual void OnDied() override; + + virtual void OnDoNotDisturbDateChange( + const std::shared_ptr &date) override; + +private: + std::vector StringSplit(const std::string &str, const char *delim); + +private: + static std::shared_ptr continuousTaskMgr_; +}; +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/continuous_task/src/app_state_observer.cpp b/services/continuous_task/src/app_state_observer.cpp new file mode 100644 index 00000000..8e5776dd --- /dev/null +++ b/services/continuous_task/src/app_state_observer.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_state_observer.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "bg_continuous_task_mgr.h" +#include "continuous_task_log.h" +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +const std::string TASK_ON_PROCESS_DIED = "OnProcessDiedTask"; +} + +AppStateObserver::AppStateObserver() +{ + appMgrDeathRecipient_ = new RemoteDeathRecipient(std::bind(&AppStateObserver::OnRemoteDied, + this, std::placeholders::_1)); +} + +AppStateObserver::~AppStateObserver() +{ + std::lock_guard lock(mutex_); + Disconnect(); +} + +void AppStateObserver::OnProcessDied(const AppExecFwk::ProcessData &processData) +{ + BGTASK_LOGI("process died, pid : %{public}d", processData.pid); + auto handler = handler_.lock(); + if (!handler) { + BGTASK_LOGE("handler is null"); + return; + } + auto bgContinuousTaskMgr = bgContinuousTaskMgr_.lock(); + if (!bgContinuousTaskMgr) { + BGTASK_LOGE("bgContinuousTaskMgr is null"); + return; + } + + auto task = [=]() { bgContinuousTaskMgr->OnProcessDied(processData.pid); }; + handler->PostTask(task, TASK_ON_PROCESS_DIED); +} + +void AppStateObserver::SetEventHandler(const std::shared_ptr &handler) +{ + handler_ = handler; +} + +void AppStateObserver::SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr) +{ + bgContinuousTaskMgr_ = bgContinuousTaskMgr; +} + +bool AppStateObserver::Subscribe() +{ + BGTASK_LOGI("Subscribe called"); + std::lock_guard lock(mutex_); + + if (!Connect()) { + return false; + } + appMgrProxy_->RegisterApplicationStateObserver(iface_cast(this)); + return true; +} + +bool AppStateObserver::Unsubscribe() +{ + BGTASK_LOGI("UnSubscribe called"); + std::lock_guard lock(mutex_); + if (!Connect()) { + return false; + } + appMgrProxy_->UnregisterApplicationStateObserver(iface_cast(this)); + return true; +} + +bool AppStateObserver::Connect() +{ + if (appMgrProxy_ != nullptr) { + return true; + } + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + BGTASK_LOGE("get SystemAbilityManager failed"); + return false; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + BGTASK_LOGE("get App Manager Service failed"); + return false; + } + + appMgrProxy_ = iface_cast(remoteObject); + if (!appMgrProxy_ || !appMgrProxy_->AsObject()) { + BGTASK_LOGE("get app mgr proxy failed!"); + return false; + } + appMgrProxy_->AsObject()->AddDeathRecipient(appMgrDeathRecipient_); + return true; +} + +void AppStateObserver::Disconnect() +{ + if (appMgrProxy_ != nullptr) { + appMgrProxy_->AsObject()->RemoveDeathRecipient(appMgrDeathRecipient_); + appMgrProxy_ = nullptr; + } +} + +void AppStateObserver::OnRemoteDied(const wptr &object) +{ + std::lock_guard lock(mutex_); + Disconnect(); +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp new file mode 100644 index 00000000..c94ba645 --- /dev/null +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -0,0 +1,854 @@ +/* + * 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 "bg_continuous_task_mgr.h" + +#include + +#include "bundle_constants.h" +#include "bundle_manager_helper.h" +#include "common_event_support.h" +#include "common_event_manager.h" +#include "errors.h" +#include "if_system_ability_manager.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "ohos/aafwk/base/string_wrapper.h" +#include "os_account_manager.h" +#include "system_ability_definition.h" + +#include "bgtaskmgr_inner_errors.h" +#include "continuous_task_record.h" +#include "continuous_task_log.h" +#include "system_event_observer.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static const char *CONTI_TASK_TEXT_RES_NAMES[] = { + "ohos_bgmode_prompt_data_transfer", + "ohos_bgmode_prompt_audio_playback", + "ohos_bgmode_prompt_audio_recording", + "ohos_bgmode_prompt_location", + "ohos_bgmode_prompt_bluetooth_interaction", + "ohos_bgmode_prompt_multidevice_connection", + "ohos_bgmode_prompt_wifi_interaction", + "ohos_bgmode_prompt_voip", + "ohos_bgmode_prompt_task_keeping", + "ohos_bgmode_prompt_default_value", +}; + +static constexpr char BG_CONTINUOUS_TASK_MGR_NAME[] = "BgContinuousTaskMgr"; +static constexpr char SEPARATOR[] = "_"; +static constexpr char DUMP_PARAM_LIST_ALL[] = "--all"; +static constexpr char DUMP_PARAM_CANCEL_ALL[] = "--cancel_all"; +static constexpr char DUMP_PARAM_CANCEL[] = "--cancel"; +static constexpr char NOTIFICATION_PREFIX[] = "bgmode"; +static constexpr char BGMODE_PERMISSION[] = "ohos.permission.KEEP_BACKGROUND_RUNNING"; +static constexpr char BG_TASK_RES_BUNDLE_NAME[] = "ohos.global.backgroundtaskres"; +static constexpr uint32_t SYSTEM_APP_BGMODE_WIFI_INTERACTION = 64; +static constexpr uint32_t SYSTEM_APP_BGMODE_VOIP = 128; +static constexpr unsigned int SYSTEM_UID = 1000; +static constexpr int32_t DEFAULT_NOTIFICATION_ID = 0; +static constexpr int DELAY_TIME = 2000; +static constexpr uint32_t INVALID_BGMODE = 0; +static constexpr uint32_t BG_MODE_INDEX_HEAD = 1; +static constexpr int BGMODE_NUMS = 10; +} + +BgContinuousTaskMgr::BgContinuousTaskMgr() +{} + +BgContinuousTaskMgr::~BgContinuousTaskMgr() +{} + +bool BgContinuousTaskMgr::Init() +{ + runner_ = AppExecFwk::EventRunner::Create(BG_CONTINUOUS_TASK_MGR_NAME); + if (runner_ == nullptr) { + BGTASK_LOGE("BgContinuousTaskMgr runner create failed!"); + return false; + } + handler_ = std::make_shared(runner_); + if (handler_ == nullptr) { + BGTASK_LOGE("BgContinuousTaskMgr handler create failed!"); + return false; + } + auto task = [this]() { this->InitNecessaryState(); }; + handler_->PostSyncTask(task); + return true; +} + +void BgContinuousTaskMgr::Clear() +{ + Notification::NotificationHelper::UnSubscribeNotification(*subscriber_); + if (systemEventListener_ != nullptr) { + systemEventListener_->Unsubscribe(); + } + if (appStateObserver_ != nullptr) { + appStateObserver_->Unsubscribe(); + } +} + +void BgContinuousTaskMgr::InitNecessaryState() +{ + sptr systemAbilityManager + = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr + || systemAbilityManager->CheckSystemAbility(APP_MGR_SERVICE_ID) == nullptr + || systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr + || systemAbilityManager->CheckSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID) == nullptr + || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr) { + BGTASK_LOGW("request system service is not ready yet!"); + auto task = [this]() { this->InitNecessaryState(); }; + handler_->PostTask(task, DELAY_TIME); + return; + } + + bool isInitSucceed = true; + if (!RegisterNotificationSubscriber()) { + BGTASK_LOGE("RegisterNotificationSubscriber failed"); + isInitSucceed = false; + } + if (!RegisterAppStateObserver()) { + BGTASK_LOGE("RegisterAppStateObserver failed"); + isInitSucceed = false; + } + if (!RegisterSysCommEventListener()) { + BGTASK_LOGE("RegisterSysCommEventListener failed"); + isInitSucceed = false; + } + if (!GetContinuousTaskText()) { + BGTASK_LOGE("GetContinuousTaskText failed"); + isInitSucceed = false; + } + isSysReady_.store(isInitSucceed); +} + +bool BgContinuousTaskMgr::RegisterNotificationSubscriber() +{ + BGTASK_LOGI("begin"); + bool res = true; + subscriber_ = std::make_shared(); + if (Notification::NotificationHelper::SubscribeNotification(*subscriber_) != ERR_OK) { + BGTASK_LOGE("SubscribeNotification failed!"); + res = false; + } + return res; +} + +bool BgContinuousTaskMgr::RegisterAppStateObserver() +{ + bool res = true; + appStateObserver_ = std::make_shared(); + if (appStateObserver_ != nullptr) { + appStateObserver_->SetEventHandler(handler_); + appStateObserver_->SetBgContinuousTaskMgr(shared_from_this()); + res = appStateObserver_->Subscribe(); + } + return res; +} + +bool BgContinuousTaskMgr::GetContinuousTaskText() +{ + AppExecFwk::BundleInfo bundleInfo; + if (!BundleManagerHelper::GetInstance()->GetBundleInfo(BG_TASK_RES_BUNDLE_NAME, + AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo)) { + BGTASK_LOGE("get background task res: %{public}s bundle info failed", BG_TASK_RES_BUNDLE_NAME); + return false; + } + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (!resourceManager) { + BGTASK_LOGE("create resourceManager failed"); + return false; + } + for (auto moduleResPath : bundleInfo.moduleResPaths) { + if (!moduleResPath.empty()) { + if (!resourceManager->AddResource(moduleResPath.c_str())) { + BGTASK_LOGE("AddResource failed"); + } + } + } + std::string taskText {""}; + for (std::string name : CONTI_TASK_TEXT_RES_NAMES) { + resourceManager->GetStringByName(name.c_str(), taskText); + if (taskText.empty()) { + BGTASK_LOGE("get continuous task notification text failed!"); + return false; + } + BGTASK_LOGI("get taskText: %{public}s", taskText.c_str()); + continuousTaskText_.push_back(taskText); + } + return true; +} + +bool BgContinuousTaskMgr::RegisterSysCommEventListener() +{ + bool res = true; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REPLACED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); + EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills); + systemEventListener_ = std::make_shared(commonEventSubscribeInfo); + if (systemEventListener_ != nullptr) { + systemEventListener_->SetEventHandler(handler_); + systemEventListener_->SetBgContinuousTaskMgr(shared_from_this()); + res = systemEventListener_->Subscribe(); + } + return res; +} + +bool BgContinuousTaskMgr::SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName) +{ + AppExecFwk::BundleInfo bundleInfo; + if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, + AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId)) { + BGTASK_LOGW("get bundle info: %{public}s failure!", bundleName.c_str()); + return false; + } + + CachedBundleInfo cachedBundleInfo = CachedBundleInfo(); + if (AddAbilityBgModeInfos(bundleInfo, cachedBundleInfo) + && AddAppNameInfos(bundleInfo, cachedBundleInfo)) { + cachedBundleInfos_.emplace(uid, cachedBundleInfo); + return true; + } + return false; +} + +bool BgContinuousTaskMgr::AddAbilityBgModeInfos(const AppExecFwk::BundleInfo &bundleInfo, + CachedBundleInfo &cachedBundleInfo) +{ + for (auto abilityInfo : bundleInfo.abilityInfos) { + if (abilityInfo.backgroundModes != INVALID_BGMODE) { + cachedBundleInfo.abilityBgMode_.emplace(abilityInfo.name, abilityInfo.backgroundModes); + BGTASK_LOGI("abilityName: %{public}s, abilityNameHash: %{public}s, Background Mode: %{public}d.", + abilityInfo.name.c_str(), std::to_string(std::hash()(abilityInfo.name)).c_str(), + abilityInfo.backgroundModes); + } + } + if (cachedBundleInfo.abilityBgMode_.empty()) { + return false; + } + return true; +} + +bool BgContinuousTaskMgr::AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo) +{ + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (resourceManager == nullptr) { + BGTASK_LOGE("resourceManager init failed!"); + return false; + } + int32_t labelId = bundleInfo.applicationInfo.labelId; + std::string bundleName = bundleInfo.name; + std::string appName {""}; + for (auto resPath = bundleInfo.moduleResPaths.begin(); resPath != bundleInfo.moduleResPaths.end(); resPath++) { + if (resPath->empty()) { + continue; + } + if (!resourceManager->AddResource(resPath->c_str())) { + BGTASK_LOGE("resourceManager add %{public}s resource path failed!", bundleInfo.name.c_str()); + } + } + resourceManager->GetStringById(labelId, appName); + appName = appName.empty() ? bundleInfo.applicationInfo.label : appName; + BGTASK_LOGI("get app display info, labelId: %{public}d, appname: %{public}s", labelId, appName.c_str()); + cachedBundleInfo.appName_ = appName; + return true; +} + +bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool isNewApi, uid_t uid) +{ + if (!isNewApi) { + if (configuredBgMode == INVALID_BGMODE) { + BGTASK_LOGE("ability without background mode config"); + return false; + } else { + return true; + } + } else { + uint32_t recordedBgMode = BG_MODE_INDEX_HEAD << (requestedBgModeId - 1); + if ((recordedBgMode == SYSTEM_APP_BGMODE_WIFI_INTERACTION || recordedBgMode == SYSTEM_APP_BGMODE_VOIP) + && !BundleManagerHelper::GetInstance()->IsSystemApp(uid)) { + BGTASK_LOGW("voip and wifiInteraction background mode only support for system app"); + return false; + } + if (requestedBgModeId == INVALID_BGMODE || (configuredBgMode + & (BG_MODE_INDEX_HEAD << (requestedBgModeId - 1))) == 0) { + BGTASK_LOGE("requested background mode is not declared in config file!"); + return false; + } + } + return true; +} + +uint32_t BgContinuousTaskMgr::GetBackgroundModeInfo(uid_t uid, std::string &abilityName) +{ + if (cachedBundleInfos_.find(uid) != cachedBundleInfos_.end()) { + auto cachedBundleInfo = cachedBundleInfos_.at(uid); + if (cachedBundleInfo.abilityBgMode_.find(abilityName) != + cachedBundleInfo.abilityBgMode_.end()) { + return cachedBundleInfo.abilityBgMode_.at(abilityName); + } + } + return INVALID_BGMODE; +} + +ErrCode BgContinuousTaskMgr::StartBackgroundRunning(const sptr taskParam) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + + if (!taskParam) { + BGTASK_LOGE("continuous task params is null!"); + return ERR_BGTASK_INVALID_PARAM; + } + + if (taskParam->isNewApi_) { + if (taskParam->wantAgent_ == nullptr || taskParam->abilityName_.empty()) { + BGTASK_LOGE("continuous task params invalid!"); + return ERR_BGTASK_INVALID_PARAM; + } + } else { + if (taskParam->abilityName_.empty()) { + BGTASK_LOGE("continuous task params invalid!"); + return ERR_BGTASK_INVALID_PARAM; + } + } + + ErrCode result = ERR_OK; + + uid_t callingUid = IPCSkeleton::GetCallingUid(); + pid_t callingPid = IPCSkeleton::GetCallingPid(); + std::string bundleName = BundleManagerHelper::GetInstance()->GetClientBundleName(callingUid); + int32_t userId = -1; + AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); + + std::shared_ptr continuousTaskRecord = std::make_shared(bundleName, + taskParam->abilityName_, taskParam->wantAgent_, taskParam->abilityToken_, userId, callingUid, callingPid, + taskParam->bgModeId_, taskParam->isNewApi_); + + handler_->PostSyncTask([this, continuousTaskRecord, &result]() mutable { + result = this->StartBackgroundRunningInner(continuousTaskRecord); + }, AppExecFwk::EventQueue::Priority::HIGH); + + BGTASK_LOGI("end"); + return result; +} + +ErrCode BgContinuousTaskMgr::StartBackgroundRunningInner(std::shared_ptr &continuousTaskRecord) +{ + BGTASK_LOGI("begin"); + + std::stringstream stream; + stream.clear(); + stream.str(""); + continuousTaskRecord->abilityToken_ ? stream << continuousTaskRecord->abilityToken_ : stream << 0; + std::string abilityTokeLabel = stream.str(); + std::string taskInfoMapKey = std::to_string(continuousTaskRecord->uid_) + SEPARATOR + + continuousTaskRecord->abilityName_ + SEPARATOR + abilityTokeLabel; + if (continuousTaskInfosMap_.find(taskInfoMapKey) != continuousTaskInfosMap_.end()) { + BGTASK_LOGI("continuous task is already exist: %{public}s", taskInfoMapKey.c_str()); + return ERR_BGTASK_OBJECT_EXISTS; + } + + if (!BundleManagerHelper::GetInstance()->CheckPermission(continuousTaskRecord->bundleName_, BGMODE_PERMISSION)) { + BGTASK_LOGE("background mode permission is not passed"); + return ERR_BGTASK_PERMISSION_DENIED; + } + + if (cachedBundleInfos_.find(continuousTaskRecord->uid_) == cachedBundleInfos_.end()) { + SetCachedBundleInfo(continuousTaskRecord->uid_, continuousTaskRecord->userId_, + continuousTaskRecord->bundleName_); + } + + uint32_t configuredBgMode = GetBackgroundModeInfo(continuousTaskRecord->uid_, + continuousTaskRecord->abilityName_); + if (!checkBgmodeType(configuredBgMode, continuousTaskRecord->bgModeId_, continuousTaskRecord->isNewApi_, + continuousTaskRecord->uid_)) { + BGTASK_LOGE("background mode invalid!"); + return ERR_BGTASK_INVALID_BGMODE; + } + + if (SendContinuousTaskNotification(continuousTaskRecord) != ERR_OK) { + BGTASK_LOGE("publish error"); + return ERR_BGTASK_NOTIFICATION_ERR; + } + continuousTaskInfosMap_.emplace(taskInfoMapKey, continuousTaskRecord); + OnContinuousTaskChanged(continuousTaskRecord, ContinuousTaskEventTriggerType::TASK_START); + return ERR_OK; +} + +int32_t GetBgModeNameIndex(uint32_t bgModeId, bool isNewApi) +{ + if (!isNewApi) { + return BGMODE_NUMS - 1; + } else { + return bgModeId - 1; + } +} + +ErrCode BgContinuousTaskMgr::SendContinuousTaskNotification( + std::shared_ptr &continuousTaskRecord) +{ + BGTASK_LOGI("begin"); + std::shared_ptr normalContent + = std::make_shared(); + + std::string notificationText {""}; + int32_t index = GetBgModeNameIndex(continuousTaskRecord->GetBgModeId(), continuousTaskRecord->isNewApi_); + if (index >= 0 && index < BGMODE_NUMS) { + notificationText = continuousTaskText_.at(index); + } + std::string appName {""}; + if (cachedBundleInfos_.find(continuousTaskRecord->uid_) != cachedBundleInfos_.end()) { + appName = cachedBundleInfos_.at(continuousTaskRecord->uid_).appName_; + } + if (appName.empty() || notificationText.empty()) { + BGTASK_LOGE("get notification prompt info failed"); + return ERR_BGTASK_INVALID_PARAM; + } + + normalContent->SetTitle(appName); + normalContent->SetText(notificationText); + + Notification::NotificationRequest notificationRequest = Notification::NotificationRequest(); + + std::shared_ptr extraInfo = std::make_shared(); + extraInfo->SetParam("abilityName", AAFwk::String::Box(continuousTaskRecord->abilityName_)); + + std::string notificationLabel = CreateNotificationLabel(continuousTaskRecord->uid_, + continuousTaskRecord->bundleName_, continuousTaskRecord->abilityName_, continuousTaskRecord->abilityToken_); + + // set extraInfo to save abilityname Info. + notificationRequest.SetAdditionalData(extraInfo); + + // set basic notification content + notificationRequest.SetContent(std::make_shared(normalContent)); + + // set wantagent param for click jump to target ability + notificationRequest.SetWantAgent(continuousTaskRecord->wantAgent_); + + // set notification label distinguish different notification + notificationRequest.SetLabel(notificationLabel); + + // set creator uid as system uid 1000 + notificationRequest.SetCreatorUid(SYSTEM_UID); + + // set creator user id to -2 means to get all user's notification event callback. + notificationRequest.SetCreatorUserId(-2); + + if (Notification::NotificationHelper::PublishContinuousTaskNotification(notificationRequest) != ERR_OK) { + BGTASK_LOGI("publish notification error"); + return ERR_BGTASK_NOTIFICATION_ERR; + } + continuousTaskRecord->notificationLabel_ = notificationLabel; + + BGTASK_LOGI("end"); + return ERR_OK; +} + +std::string BgContinuousTaskMgr::CreateNotificationLabel(uid_t uid, const std::string &bundleName, + const std::string &abilityName, const sptr abilityToken) +{ + std::stringstream stream; + stream.clear(); + stream.str(""); + stream << NOTIFICATION_PREFIX << SEPARATOR << uid << SEPARATOR << std::hash()(abilityName) + << SEPARATOR << (abilityToken ? (abilityToken) : 0); + std::string label = stream.str(); + BGTASK_LOGI("notification label: %{public}s", label.c_str()); + return label; +} + +ErrCode BgContinuousTaskMgr::StopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + if (abilityName.empty()) { + BGTASK_LOGE("abilityName is empty!"); + return ERR_BGTASK_INVALID_PARAM; + } + uid_t callingUid = IPCSkeleton::GetCallingUid(); + + ErrCode result = ERR_OK; + + handler_->PostSyncTask([this, callingUid, abilityName, abilityToken, &result]() { + result = this->StopBackgroundRunningInner(callingUid, abilityName, abilityToken); + }, AppExecFwk::EventQueue::Priority::HIGH); + + return result; +} + +ErrCode BgContinuousTaskMgr::StopBackgroundRunningInner(uid_t uid, const std::string &abilityName, + const sptr &abilityToken) +{ + BGTASK_LOGI("begin"); + std::stringstream stream; + stream.clear(); + stream.str(""); + abilityToken ? stream << abilityToken : stream << 0; + std::string abilityTokeLabel = stream.str(); + std::string mapKey = std::to_string(uid) + SEPARATOR + abilityName + SEPARATOR + abilityTokeLabel; + + auto iter = continuousTaskInfosMap_.find(mapKey); + if (iter == continuousTaskInfosMap_.end()) { + BGTASK_LOGW("%{public}s continuous task not exists", mapKey.c_str()); + return ERR_BGTASK_INVALID_PARAM; + } + ErrCode result = Notification::NotificationHelper::CancelContinuousTaskNotification( + iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); + RemoveContinuousTaskRecord(mapKey); + BGTASK_LOGI("end"); + return result; +} + +ErrCode BgContinuousTaskMgr::AddSubscriber(const sptr &subscriber) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + if (subscriber == nullptr) { + BGTASK_LOGI("subscriber is null."); + return ERR_BGTASK_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask([this, &subscriber, &result]() { + result = AddSubscriberInner(subscriber); + }, AppExecFwk::EventQueue::Priority::HIGH); + + return result; +} + +ErrCode BgContinuousTaskMgr::AddSubscriberInner(const sptr &subscriber) +{ + BGTASK_LOGI("begin"); + auto remoteObj = subscriber->AsObject(); + auto findSuscriber = [&remoteObj](const auto& target) { + return remoteObj == target->AsObject(); + }; + + auto subscriberIter = find_if(bgTaskSubscribers_.begin(), bgTaskSubscribers_.end(), findSuscriber); + if (subscriberIter != bgTaskSubscribers_.end()) { + BGTASK_LOGW("target subscriber already exist"); + return ERR_BGTASK_OBJECT_EXISTS; + } + + bgTaskSubscribers_.emplace_back(subscriber); + + if (subscriber->AsObject() == nullptr) { + return ERR_BGTASK_INVALID_PARAM; + } + if (subscriberRecipients_.find(subscriber->AsObject()) != subscriberRecipients_.end()) { + return ERR_BGTASK_OBJECT_EXISTS; + } + sptr deathRecipient = + new RemoteDeathRecipient([this](const wptr &remote) { this->OnRemoteSubscriberDied(remote); }); + subscriber->AsObject()->AddDeathRecipient(deathRecipient); + subscriberRecipients_.emplace(subscriber->AsObject(), deathRecipient); + subscriber->OnConnected(); + BGTASK_LOGI("end"); + return ERR_OK; +} + +ErrCode BgContinuousTaskMgr::RemoveSubscriber(const sptr &subscriber) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + if (subscriber == nullptr) { + BGTASK_LOGE("subscriber is null."); + return ERR_BGTASK_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask([this, &subscriber, &result]() { + result = this->RemoveSubscriberInner(subscriber); + }, AppExecFwk::EventQueue::Priority::HIGH); + + return result; +} + +ErrCode BgContinuousTaskMgr::RemoveSubscriberInner(const sptr &subscriber) +{ + BGTASK_LOGI("begin"); + auto subscriberIter = bgTaskSubscribers_.begin(); + while (subscriberIter != bgTaskSubscribers_.end()) { + if ((*subscriberIter)->AsObject() == subscriber->AsObject()) { + subscriberIter = bgTaskSubscribers_.erase(subscriberIter); + } else { + subscriberIter++; + } + } + if (subscriber->AsObject() == nullptr) { + return ERR_BGTASK_INVALID_PARAM; + } + auto iter = subscriberRecipients_.find(subscriber->AsObject()); + if (iter != subscriberRecipients_.end()) { + iter->first->RemoveDeathRecipient(iter->second); + subscriberRecipients_.erase(iter); + } + subscriber->OnDisconnected(); + BGTASK_LOGI("end"); + return ERR_OK; +} + +ErrCode BgContinuousTaskMgr::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + ErrCode result = ERR_OK; + handler_->PostSyncTask([&]() { + result = ShellDumpInner(dumpOption, dumpInfo); + }); + + return result; +} + +ErrCode BgContinuousTaskMgr::ShellDumpInner(const std::vector &dumpOption, + std::vector &dumpInfo) +{ + BGTASK_LOGI("begin"); + if (dumpOption[1] == DUMP_PARAM_LIST_ALL) { + DumpAllTaskInfo(dumpInfo); + } else if (dumpOption[1] == DUMP_PARAM_CANCEL_ALL) { + DumpCancelTask(dumpOption, true); + } else if (dumpOption[1] == DUMP_PARAM_CANCEL) { + DumpCancelTask(dumpOption, false); + } + return ERR_OK; +} + +void BgContinuousTaskMgr::DumpAllTaskInfo(std::vector &dumpInfo) +{ + BGTASK_LOGI("begin"); + std::stringstream stream; + if (continuousTaskInfosMap_.empty()) { + dumpInfo.emplace_back("No running continuous task\n"); + return; + } + std::unordered_map>::iterator iter; + uint32_t index = 1; + for (iter = continuousTaskInfosMap_.begin(); iter != continuousTaskInfosMap_.end(); iter++) { + stream.str(""); + stream.clear(); + stream << "No." << index; + stream << "\tcontinuousTaskKey: " << iter->first << "\n"; + stream << "\tcontinuousTaskValue:" << "\n"; + stream << "\t\tbundleName: " << iter->second->GetBundleName() << "\n"; + stream << "\t\tabilityName: " << iter->second->GetAbilityName() << "\n"; + stream << "\t\tisFromNewApi: " << (iter->second->IsNewApi() ? "true" : "false") << "\n"; + stream << "\t\tbackgroundMode: " << ContinuousTaskModeName[GetBgModeNameIndex( + iter->second->GetBgModeId(), iter->second->IsNewApi())] << "\n"; + stream << "\t\tuid: " << iter->second->GetUid() << "\n"; + stream << "\t\tuserId: " << iter->second->GetUserId() << "\n"; + stream << "\t\tpid: " << iter->second->GetPid() << "\n"; + stream << "\t\tnotificationLabel: " << iter->second->GetNotificationLabel() << "\n"; + auto wantAgent = iter->second->GetWantAgent(); + if (wantAgent != nullptr && wantAgent->GetPendingWant() != nullptr) { + auto want = wantAgent->GetPendingWant()->GetWant(wantAgent->GetPendingWant()->GetTarget()); + if (want != nullptr) { + stream << "\t\twantAgentBundleName: " << want->GetOperation().GetBundleName() << "\n"; + stream << "\t\twantAgentAbilityName: " << want->GetOperation().GetAbilityName() << "\n"; + } + } else { + stream << "\t\twantAgentBundleName: " << "NULL" << "\n"; + stream << "\t\twantAgentAbilityName: " << "NULL" << "\n"; + } + stream << "\n"; + dumpInfo.emplace_back(stream.str()); + index++; + } +} + +void BgContinuousTaskMgr::DumpCancelTask(const std::vector &dumpOption, bool cleanAll) +{ + BGTASK_LOGI("begin"); + if (cleanAll) { + for (auto item : continuousTaskInfosMap_) { + Notification::NotificationHelper::CancelContinuousTaskNotification(item.second->GetNotificationLabel(), + DEFAULT_NOTIFICATION_ID); + OnContinuousTaskChanged(item.second, ContinuousTaskEventTriggerType::TASK_CANCEL); + } + continuousTaskInfosMap_.clear(); + } else { + std::string taskKey = dumpOption[2]; + auto iter = continuousTaskInfosMap_.find(taskKey); + if (iter == continuousTaskInfosMap_.end()) { + return; + } + Notification::NotificationHelper::CancelContinuousTaskNotification(iter->second->GetNotificationLabel(), + DEFAULT_NOTIFICATION_ID); + RemoveContinuousTaskRecord(taskKey); + } +} + +bool BgContinuousTaskMgr::RemoveContinuousTaskRecord(const std::string &mapKey) +{ + BGTASK_LOGI("task info: %{public}s", mapKey.c_str()); + if (continuousTaskInfosMap_.find(mapKey) == continuousTaskInfosMap_.end()) { + BGTASK_LOGW("remove TaskInfo failure, no matched task: %{public}s", mapKey.c_str()); + return false; + } + OnContinuousTaskChanged(continuousTaskInfosMap_.at(mapKey), ContinuousTaskEventTriggerType::TASK_CANCEL); + continuousTaskInfosMap_.erase(mapKey); + BGTASK_LOGI("end"); + return true; +} + +bool BgContinuousTaskMgr::StopContinuousTaskByUser(const std::string &mapKey) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + bool result = true; + handler_->PostSyncTask([this, mapKey, &result]() { + result = RemoveContinuousTaskRecord(mapKey); + }); + return result; +} + +void BgContinuousTaskMgr::OnRemoteSubscriberDied(const wptr &object) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return; + } + if (object == nullptr) { + BGTASK_LOGI("remote object is null."); + return; + } + + handler_->PostSyncTask([this, &object]() { this->OnRemoteSubscriberDiedInner(object); }); +} + +void BgContinuousTaskMgr::OnRemoteSubscriberDiedInner(const wptr &object) +{ + BGTASK_LOGI("begin"); + sptr objectProxy = object.promote(); + if (!objectProxy) { + BGTASK_LOGE("get remote object failed"); + return; + } + auto iter = bgTaskSubscribers_.begin(); + while (iter != bgTaskSubscribers_.end()) { + if ((*iter)->AsObject() == objectProxy) { + iter = bgTaskSubscribers_.erase(iter); + } else { + iter++; + } + } + subscriberRecipients_.erase(objectProxy); +} + +void BgContinuousTaskMgr::OnProcessDied(int32_t pid) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return; + } + + auto iter = continuousTaskInfosMap_.begin(); + while (iter != continuousTaskInfosMap_.end()) { + if (iter->second->GetPid() == pid) { + OnContinuousTaskChanged(iter->second, ContinuousTaskEventTriggerType::TASK_CANCEL); + Notification::NotificationHelper::CancelContinuousTaskNotification( + iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); + iter = continuousTaskInfosMap_.erase(iter); + } else { + iter++; + } + } +} + +void BgContinuousTaskMgr::OnContinuousTaskChanged(const std::shared_ptr continuousTaskInfo, + ContinuousTaskEventTriggerType changeEventType) +{ + BGTASK_LOGI("begin"); + if (continuousTaskInfo == nullptr) { + BGTASK_LOGW("ContinuousTaskRecord is null"); + return; + } + + if (bgTaskSubscribers_.empty()) { + BGTASK_LOGI("Background Task Subscriber List is empty"); + return; + } + + sptr continuousTaskCallbackInfo = new ContinuousTaskCallbackInfo( + continuousTaskInfo->GetBgModeId(), continuousTaskInfo->GetUid(), + continuousTaskInfo->GetPid(), continuousTaskInfo->GetAbilityName()); + + switch (changeEventType) { + case ContinuousTaskEventTriggerType::TASK_START: + for (auto iter = bgTaskSubscribers_.begin(); iter != bgTaskSubscribers_.end(); iter++) { + BGTASK_LOGI("continuous task start callback trigger"); + (*iter)->OnContinuousTaskStart(continuousTaskCallbackInfo); + } + break; + case ContinuousTaskEventTriggerType::TASK_CANCEL: + for (auto iter = bgTaskSubscribers_.begin(); iter != bgTaskSubscribers_.end(); iter++) { + BGTASK_LOGI("continuous task stop callback trigger"); + (*iter)->OnContinuousTaskStop(continuousTaskCallbackInfo); + } + break; + } +} + +void BgContinuousTaskMgr::OnBundleInfoChanged(const std::string &action, const std::string &bundleName, uid_t uid) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return; + } + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REPLACED) { + cachedBundleInfos_.erase(uid); + } else { + BGTASK_LOGW("get unregister common event!"); + return; + } +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/bundle_manager_helper.cpp b/services/continuous_task/src/bundle_manager_helper.cpp new file mode 100644 index 00000000..b25de200 --- /dev/null +++ b/services/continuous_task/src/bundle_manager_helper.cpp @@ -0,0 +1,132 @@ +/* + * 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 "bundle_manager_helper.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED; + +BundleManagerHelper::BundleManagerHelper() +{ + bundleMgrDeathRecipient_ = new RemoteDeathRecipient( + [this](const wptr &object) { this->OnRemoteDied(object); }); +} + +BundleManagerHelper::~BundleManagerHelper() +{ + std::lock_guard lock(connectionMutex_); + Disconnect(); +} + +std::string BundleManagerHelper::GetClientBundleName(uid_t uid) +{ + std::string bundle {""}; + std::lock_guard lock(connectionMutex_); + Connect(); + if (bundleMgr_ != nullptr) { + bundleMgr_->GetBundleNameForUid(uid, bundle); + } + BGTASK_LOGI("get client Bundle Name: %{public}s", bundle.c_str()); + return bundle; +} + +bool BundleManagerHelper::CheckPermission(const std::string &bundleName, + const std::string &permission) +{ + std::lock_guard lock(connectionMutex_); + Connect(); + if (bundleMgr_ != nullptr) { + auto result = bundleMgr_->CheckPermission(bundleName, permission); + BGTASK_LOGI("permission check result: %{public}d", result); + if (result == PERMISSION_GRANTED) { + return true; + } + } + return false; +} + +bool BundleManagerHelper::IsSystemApp(uid_t uid) +{ + bool isSystemApp = false; + std::lock_guard lock(connectionMutex_); + Connect(); + if (bundleMgr_ != nullptr) { + isSystemApp = bundleMgr_->CheckIsSystemAppByUid(uid); + } + return isSystemApp; +} + +bool BundleManagerHelper::GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, + AppExecFwk::BundleInfo &bundleInfo, int32_t userId) +{ + std::lock_guard lock(connectionMutex_); + + Connect(); + + if (bundleMgr_ != nullptr && bundleMgr_->GetBundleInfo(bundleName, flag, bundleInfo, userId)) { + return true; + } + return false; +} + +bool BundleManagerHelper::Connect() +{ + if (bundleMgr_ != nullptr) { + return true; + } + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + BGTASK_LOGE("get SystemAbilityManager failed"); + return false; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + BGTASK_LOGE("get Bundle Manager failed"); + return false; + } + + bundleMgr_ = iface_cast(remoteObject); + if (bundleMgr_ != nullptr) { + bundleMgr_->AsObject()->AddDeathRecipient(bundleMgrDeathRecipient_); + return true; + } + BGTASK_LOGE("get bundleMgr failed"); + return false; +} + +void BundleManagerHelper::Disconnect() +{ + if (bundleMgr_ != nullptr) { + bundleMgr_->AsObject()->RemoveDeathRecipient(bundleMgrDeathRecipient_); + bundleMgr_ = nullptr; + } +} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{ + std::lock_guard lock(connectionMutex_); + Disconnect(); +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp new file mode 100644 index 00000000..a3bfa181 --- /dev/null +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -0,0 +1,92 @@ +/* + * 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 "continuous_task_record.h" + +#include "iremote_object.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +const char *ContinuousTaskModeName[10] = { + "dataTransfer", + "audioPlayback", + "audioRecording", + "location", + "bluetoothInteraction", + "multiDeviceConnection", + "wifiInteraction", + "voip", + "taskKeeping", + "default", +}; + +ContinuousTaskRecord::ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, + const std::shared_ptr &wantAgent, const sptr &abilityToken, + int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi) + : bundleName_(bundleName), abilityName_(abilityName), wantAgent_(wantAgent), abilityToken_(abilityToken), + userId_(userId), uid_(uid), pid_(pid), bgModeId_(bgModeId), isNewApi_(isNewApi) +{} + +std::string ContinuousTaskRecord::GetBundleName() const +{ + return bundleName_; +} + +std::string ContinuousTaskRecord::GetAbilityName() const +{ + return abilityName_; +} + +bool ContinuousTaskRecord::IsNewApi() const +{ + return isNewApi_; +} + +uint32_t ContinuousTaskRecord::GetBgModeId() const +{ + return bgModeId_; +} + +int32_t ContinuousTaskRecord::GetUserId() const +{ + return userId_; +} + +uid_t ContinuousTaskRecord::GetUid() const +{ + return uid_; +} + +pid_t ContinuousTaskRecord::GetPid() const +{ + return pid_; +} + +std::string ContinuousTaskRecord::GetNotificationLabel() const +{ + return notificationLabel_; +} + +std::shared_ptr ContinuousTaskRecord::GetWantAgent() const +{ + return wantAgent_; +} + +sptr ContinuousTaskRecord::GetAbilityToken() const +{ + return abilityToken_; +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp new file mode 100644 index 00000000..0f36f44f --- /dev/null +++ b/services/continuous_task/src/system_event_observer.cpp @@ -0,0 +1,90 @@ +/* + * 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 "system_event_observer.h" + +#include "bundle_constants.h" +#include "common_event_support.h" + +#include "bg_continuous_task_mgr.h" +#include "bgtaskmgr_inner_errors.h" +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +const std::string TASK_ON_BUNDLEINFO_CHANGED = "OnBundleInfoChanged"; +} + +SystemEventObserver::SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo) + : EventFwk::CommonEventSubscriber(subscribeInfo) +{} + +bool SystemEventObserver::Subscribe() +{ + BGTASK_LOGI("Subscribe called"); + + if (EventFwk::CommonEventManager::SubscribeCommonEvent(shared_from_this()) != true) { + BGTASK_LOGI("SubscribeCommonEvent occur exception."); + return false; + } + return true; +} + +bool SystemEventObserver::Unsubscribe() +{ + BGTASK_LOGI("UnSubscribe called"); + if (EventFwk::CommonEventManager::UnSubscribeCommonEvent(shared_from_this()) != true) { + BGTASK_LOGI("UnsubscribeCommonEvent occur exception."); + return false; + } + return true; +} + +void SystemEventObserver::SetEventHandler(const std::shared_ptr &handler) +{ + BGTASK_LOGI("set app state observer handler"); + handler_ = handler; +} + +void SystemEventObserver::SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr) +{ + BGTASK_LOGI("set app state oberver bgContinuousTaskMgr"); + bgContinuousTaskMgr_ = bgContinuousTaskMgr; +} + +void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + BGTASK_LOGI("OnReceiveEvent enter"); + auto handler = handler_.lock(); + if (!handler) { + BGTASK_LOGE("handler is null"); + return; + } + auto bgContinuousTaskMgr = bgContinuousTaskMgr_.lock(); + if (!bgContinuousTaskMgr) { + BGTASK_LOGE("bgContinuousTaskMgr is null"); + return; + } + AAFwk::Want want = eventData.GetWant(); + std::string action = want.GetAction(); + std::string bundleName = want.GetElement().GetBundleName(); + int uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); + BGTASK_LOGI("OnReceiveEvent action = %{public}s, bundle = %{public}s", action.c_str(), bundleName.c_str()); + auto task = [=]() { bgContinuousTaskMgr->OnBundleInfoChanged(action, bundleName, uid); }; + handler->PostTask(task, TASK_ON_BUNDLEINFO_CHANGED); +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp new file mode 100644 index 00000000..7c360c32 --- /dev/null +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -0,0 +1,134 @@ +/* + * 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 "task_notification_subscriber.h" + +#include +#include + +#include "ohos/aafwk/base/string_wrapper.h" + +#include "bg_continuous_task_mgr.h" +#include "continuous_task_log.h" + + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static constexpr char LABEL_SPLITER[] = "_"; +static constexpr char NOTIFICATION_PREFIX[] = "bgmode"; +static constexpr uint32_t SYSTEM_UID = 1000; +static constexpr uint32_t LABEL_BGMODE_PREFIX_POS = 0; +static constexpr uint32_t LABEL_APP_UID_POS = 1; +static constexpr uint32_t LABEL_ABILITY_TOKEN_POS = 3; +static constexpr uint32_t LABEL_SIZE = 4; +} + +std::shared_ptr TaskNotificationSubscriber::continuousTaskMgr_ + = BgContinuousTaskMgr::GetInstance(); + +TaskNotificationSubscriber::TaskNotificationSubscriber() +{} + +TaskNotificationSubscriber::~TaskNotificationSubscriber() +{} + +void TaskNotificationSubscriber::OnConnected() +{} + +void TaskNotificationSubscriber::OnDisconnected() +{} + +void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification) +{} + +void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification, + const std::shared_ptr &sortingMap, int deleteReason) +{ + BGTASK_LOGI("notification cancel event triggered"); + if (notification == nullptr) { + BGTASK_LOGW("notification param is null"); + return; + } + Notification::NotificationRequest request = notification->GetNotificationRequest(); + if (request.GetCreatorUid() != SYSTEM_UID) { + return; + } + + // continuous task notification label is consisted of bgmode prefix, app uid, abilityName hash code, ability token. + std::string notificationLabel = request.GetLabel(); + std::vector labelSplits = StringSplit(notificationLabel, LABEL_SPLITER); + + if (labelSplits.empty() || labelSplits[LABEL_BGMODE_PREFIX_POS] != NOTIFICATION_PREFIX + || labelSplits.size() != LABEL_SIZE) { + BGTASK_LOGW("notification callback label is invalid"); + return; + } + + if (deleteReason == Notification::NotificationConstant::APP_CANCEL_REASON_DELETE) { + BGTASK_LOGI("notification remove action is already tiggered by cancel method."); + return; + } + + BGTASK_LOGI("stop continuous task by user, the label is : %{public}s", notificationLabel.c_str()); + std::shared_ptr extraInfo = request.GetAdditionalData(); + + if (extraInfo == nullptr) { + BGTASK_LOGI("notification extraInfo is null"); + return; + } + + std::string abilityName = AAFwk::String::Unbox(AAFwk::IString::Query(extraInfo->GetParam("abilityName"))); + std::string taskInfoMapKey = labelSplits[LABEL_APP_UID_POS] + LABEL_SPLITER + abilityName + + LABEL_SPLITER + labelSplits[LABEL_ABILITY_TOKEN_POS]; + + if (continuousTaskMgr_->StopContinuousTaskByUser(taskInfoMapKey)) { + BGTASK_LOGI("remove continuous task record Key: %{public}s", taskInfoMapKey.c_str()); + } +} + +void TaskNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification) +{} + +void TaskNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification, + const std::shared_ptr &sortingMap) +{} + +void TaskNotificationSubscriber::OnUpdate( + const std::shared_ptr &sortingMap) +{} + +void TaskNotificationSubscriber::OnDied() +{} + +void TaskNotificationSubscriber::OnDoNotDisturbDateChange( + const std::shared_ptr &date) +{} + +std::vector TaskNotificationSubscriber::StringSplit(const std::string &str, const char *delim) +{ + std::vector strlist; + char *saveptr = NULL; + char *p = const_cast(str.c_str()); + char *input = strdup(p); + while ((input = strtok_r(input, delim, &saveptr)) != NULL) { + strlist.emplace_back(input); + input = NULL; + } + free(input); + return strlist; +} +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/core/include/background_task_mgr_service.h b/services/core/include/background_task_mgr_service.h index edcdf06b..92cb51e7 100644 --- a/services/core/include/background_task_mgr_service.h +++ b/services/core/include/background_task_mgr_service.h @@ -29,6 +29,7 @@ #include "system_ability_definition.h" #include "background_task_mgr_stub.h" +#include "bg_continuous_task_mgr.h" #include "bg_transient_task_mgr.h" #include "bgtaskmgr_inner_errors.h" @@ -53,6 +54,8 @@ public: const sptr& callback, std::shared_ptr &delayInfo) override; ErrCode CancelSuspendDelay(int32_t requestId) override; ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) override; + ErrCode StartBackgroundRunning(const sptr taskParam) override; + ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken) override; ErrCode SubscribeBackgroundTask(const sptr& subscriber) override; ErrCode UnsubscribeBackgroundTask(const sptr& subscriber) override; ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) override; diff --git a/services/core/src/background_task_mgr_service.cpp b/services/core/src/background_task_mgr_service.cpp index 7b1f9894..593ecb5f 100644 --- a/services/core/src/background_task_mgr_service.cpp +++ b/services/core/src/background_task_mgr_service.cpp @@ -18,6 +18,7 @@ #include #include "ability_manager_client.h" +#include "bgtaskmgr_inner_errors.h" #include "bundle_constants.h" #include "common_event_manager.h" #include "common_event_support.h" @@ -28,6 +29,7 @@ namespace OHOS { namespace BackgroundTaskMgr { namespace { +static const std::string CONTINUOUS_TASK_DUMP = "-C"; static const std::string TRANSIENT_TASK_DUMP = "-T"; const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility( DelayedSingleton::GetInstance().get()); @@ -60,10 +62,12 @@ void BackgroundTaskMgrService::OnStart() void BackgroundTaskMgrService::Init() { DelayedSingleton::GetInstance()->Init(); + BgContinuousTaskMgr::GetInstance()->Init(); } void BackgroundTaskMgrService::OnStop() { + BgContinuousTaskMgr::GetInstance()->Clear(); state_ = ServiceRunningState::STATE_NOT_START; BGTASK_LOGI("background task manager stop"); } @@ -89,14 +93,31 @@ void BackgroundTaskMgrService::ForceCancelSuspendDelay(int32_t requestId) DelayedSingleton::GetInstance()->ForceCancelSuspendDelay(requestId); } +ErrCode BackgroundTaskMgrService::StartBackgroundRunning(const sptr taskParam) +{ + return BgContinuousTaskMgr::GetInstance()->StartBackgroundRunning(taskParam); +} + +ErrCode BackgroundTaskMgrService::StopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + return BgContinuousTaskMgr::GetInstance()->StopBackgroundRunning(abilityName, abilityToken); +} + ErrCode BackgroundTaskMgrService::SubscribeBackgroundTask(const sptr& subscriber) { - return DelayedSingleton::GetInstance()->SubscribeBackgroundTask(subscriber); + ErrCode ret = ERR_OK; + ret = DelayedSingleton::GetInstance()->SubscribeBackgroundTask(subscriber); + ret = BgContinuousTaskMgr::GetInstance()->AddSubscriber(subscriber); + return ret; } ErrCode BackgroundTaskMgrService::UnsubscribeBackgroundTask(const sptr& subscriber) { - return DelayedSingleton::GetInstance()->UnsubscribeBackgroundTask(subscriber); + ErrCode ret = ERR_OK; + ret = DelayedSingleton::GetInstance()->UnsubscribeBackgroundTask(subscriber); + ret = BgContinuousTaskMgr::GetInstance()->RemoveSubscriber(subscriber); + return ret; } void BackgroundTaskMgrService::HandleRequestExpired(const int32_t requestId) @@ -120,6 +141,11 @@ ErrCode BackgroundTaskMgrService::ShellDump(const std::vector &dump ErrCode ret = ERR_OK; if (dumpOption[0] == TRANSIENT_TASK_DUMP) { ret = DelayedSingleton::GetInstance()->ShellDump(dumpOption, dumpInfo); + } else if (dumpOption[0] == CONTINUOUS_TASK_DUMP) { + ret = BgContinuousTaskMgr::GetInstance()->ShellDump(dumpOption, dumpInfo); + } else { + BGTASK_LOGI("invalid dump param"); + ret = ERR_BGTASK_INVALID_PARAM; } return ret; } diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 39eb7fef..dd24250d 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -23,13 +23,19 @@ ohos_unittest("bgtask_unit_test") { "${bgtaskmgr_services_path}/transient_task/inlcude", "${bgtaskmgr_services_path}/core/inlcude", "${bgtaskmgr_interfaces_path}/innerkits/transient_task/include", + "//base/global/resmgr_standard/frameworks/resmgr/include", + "//third_party/icu/icu4c/source/i18n", ] sources = [ "background_task_mgr_service_test.cpp", + "bg_continuous_task_mgr_test.cpp", "bg_transient_task_mgr_test.cpp", + "mock/mock_bundle_manager_helper.cpp", "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", + "mock/mock_notification_helper.cpp", + "mock/mock_resource_manager.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -38,6 +44,8 @@ ohos_unittest("bgtask_unit_test") { "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", "${bgtaskmgr_services_path}:bgtaskmgr_service", + "//base/notification/ans_standard/frameworks/ans/core:ans_core", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//third_party/googletest:gtest_main", ] diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp new file mode 100644 index 00000000..0484c3d2 --- /dev/null +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -0,0 +1,184 @@ +/* + * 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 +#include +#include + +#include "gtest/gtest.h" + +#define private public + +#include "bgtaskmgr_inner_errors.h" +#include "background_task_subscriber.h" +#include "bg_continuous_task_mgr.h" +#include "want_agent.h" + +using namespace testing::ext; + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static constexpr int32_t SLEEP_TIME = 500; +} +class BgContinuousTaskMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + inline void SleepForFC() + { + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); + } + + static std::shared_ptr bgContinuousTaskMgr_; +}; + +std::shared_ptr BgContinuousTaskMgrTest::bgContinuousTaskMgr_ = nullptr; + +void BgContinuousTaskMgrTest::SetUpTestCase() +{ + bgContinuousTaskMgr_ = BgContinuousTaskMgr::GetInstance(); + bgContinuousTaskMgr_->Init(); +} + +void BgContinuousTaskMgrTest::TearDownTestCase() +{ + bgContinuousTaskMgr_->Clear(); + bgContinuousTaskMgr_ = nullptr; +} + +void BgContinuousTaskMgrTest::SetUp() +{} + +void BgContinuousTaskMgrTest::TearDown() +{ + std::vector dumpOption; + dumpOption.emplace_back("-C"); + dumpOption.emplace_back("--cancel_all"); + std::vector dumpInfo; + bgContinuousTaskMgr_->ShellDump(dumpOption, dumpInfo); +} + +class TestBackgroundTaskSubscriber : public BackgroundTaskSubscriber { +public: + virtual void OnContinuousTaskStart(const std::shared_ptr + &continuousTaskCallbackInfo) override + {} + + virtual void OnContinuousTaskStop(const std::shared_ptr + &continuousTaskCallbackInfo) override + {} +}; + +/** + * @tc.name: StartBackgroundRunning_001 + * @tc.desc: start background runnging use new api test. + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO + */ +HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_001, TestSize.Level1) +{ + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(nullptr), (int)ERR_BGTASK_INVALID_PARAM); + sptr taskParam = new ContinuousTaskParam(); + taskParam->isNewApi_ = true; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); + taskParam->wantAgent_ = std::make_shared(); + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); + taskParam->abilityName_ = ""; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); + taskParam->abilityName_ = "ability1"; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_BGMODE); + taskParam->bgModeId_ = 9; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_BGMODE); + taskParam->bgModeId_ = 2; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_BGMODE); + taskParam->bgModeId_ = 1; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_OK); +} + +/** + * @tc.name: StartBackgroundRunning_002 + * @tc.desc: start background runnging use old api test. + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 + */ +HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) +{ + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(nullptr), (int)ERR_BGTASK_INVALID_PARAM); + sptr taskParam = new ContinuousTaskParam(); + taskParam->isNewApi_ = false; + taskParam->bgModeId_ = 0; + taskParam->abilityName_ = ""; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); + taskParam->abilityName_ = "ability1"; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_OK); +} + +/** + * @tc.name: StopBackgroundRunning_001 + * @tc.desc: start background runnging use new api test. + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K + */ +HWTEST_F(BgContinuousTaskMgrTest, StopBackgroundRunning_001, TestSize.Level1) +{ + sptr taskParam = new ContinuousTaskParam(); + taskParam->wantAgent_ = std::make_shared(); + taskParam->abilityName_ = "ability1"; + taskParam->bgModeId_ = 1; + EXPECT_EQ((int)bgContinuousTaskMgr_->StopBackgroundRunning("", nullptr), (int)ERR_BGTASK_INVALID_PARAM); + SleepForFC(); + EXPECT_EQ((int)bgContinuousTaskMgr_->StopBackgroundRunning("ability1", nullptr), (int)ERR_BGTASK_INVALID_PARAM); + SleepForFC(); + bgContinuousTaskMgr_->StartBackgroundRunning(taskParam); + SleepForFC(); + EXPECT_EQ((int)bgContinuousTaskMgr_->StopBackgroundRunning("ability1", nullptr), (int)ERR_OK); +} + +/** + * @tc.name: StartBackgroundRunning_001 + * @tc.desc: subscribe continuous task event callback test. + * @tc.type: FUNC + * @tc.require: AR000GH6EM AR000GH6G9 AR000GH6ET + */ +HWTEST_F(BgContinuousTaskMgrTest, SubscribeContinuousTask_001, TestSize.Level1) +{ + EXPECT_EQ((int)bgContinuousTaskMgr_->AddSubscriber(nullptr), (int)ERR_BGTASK_INVALID_PARAM); + SleepForFC(); + auto subscriber = new TestBackgroundTaskSubscriber(); + EXPECT_EQ((int)bgContinuousTaskMgr_->AddSubscriber(subscriber->GetImpl()), (int)ERR_OK); + SleepForFC(); + EXPECT_EQ((int)bgContinuousTaskMgr_->AddSubscriber(subscriber->GetImpl()), (int)ERR_BGTASK_OBJECT_EXISTS); +} + +/** + * @tc.name: UnsubscribeContinuousTask_001 + * @tc.desc: unsubscribe continuous task event callback test. + * @tc.type: FUNC + * @tc.require: AR000GH6EM AR000GH6G9 AR000GH6ET + */ +HWTEST_F(BgContinuousTaskMgrTest, UnsubscribeContinuousTask_001, TestSize.Level1) +{ + EXPECT_EQ((int)bgContinuousTaskMgr_->RemoveSubscriber(nullptr), (int)ERR_BGTASK_INVALID_PARAM); + SleepForFC(); + auto subscriber = new TestBackgroundTaskSubscriber(); + bgContinuousTaskMgr_->AddSubscriber(subscriber->GetImpl()); + SleepForFC(); + EXPECT_EQ((int)bgContinuousTaskMgr_->RemoveSubscriber(subscriber->GetImpl()), (int)ERR_OK); +} +} +} diff --git a/services/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/test/unittest/mock/mock_bundle_manager_helper.cpp new file mode 100644 index 00000000..032aa4aa --- /dev/null +++ b/services/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ability_info.h" +#include "bundle_info.h" +#include "bundle_manager_helper.h" + +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static constexpr char TEST_DEFAULT_BUNDLE[] = "bundleName"; +} + +BundleManagerHelper::BundleManagerHelper() +{} + +BundleManagerHelper::~BundleManagerHelper() +{} + +std::string BundleManagerHelper::GetClientBundleName(uid_t uid) +{ + return TEST_DEFAULT_BUNDLE; +} + +bool BundleManagerHelper::CheckPermission(const std::string &bundleName, + const std::string &permission) +{ + return true; +} + +bool BundleManagerHelper::IsSystemApp(uid_t uid) +{ + return true; +} + +bool BundleManagerHelper::GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, + AppExecFwk::BundleInfo &bundleInfo, int32_t userId) +{ + AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.name = "ability1"; + abilityInfo.backgroundModes = 1; + bundleInfo.abilityInfos.emplace_back(abilityInfo); + bundleInfo.name = TEST_DEFAULT_BUNDLE; + return true; +} + +bool BundleManagerHelper::Connect() +{ + return true; +} + +void BundleManagerHelper::Disconnect() +{} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{} +} +} \ No newline at end of file diff --git a/services/test/unittest/mock/mock_notification_helper.cpp b/services/test/unittest/mock/mock_notification_helper.cpp new file mode 100644 index 00000000..4611c313 --- /dev/null +++ b/services/test/unittest/mock/mock_notification_helper.cpp @@ -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. + */ + +#include "notification_helper.h" +#include "ans_notification.h" +#include "singleton.h" + +namespace OHOS { +namespace Notification { +ErrCode NotificationHelper::PublishContinuousTaskNotification(const NotificationRequest &request) +{ + return 0; +} + +ErrCode NotificationHelper::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) +{ + return 0; +} + +ErrCode NotificationHelper::SubscribeNotification(const NotificationSubscriber &subscriber) +{ + return 0; +} + +ErrCode NotificationHelper::SubscribeNotification( + const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo) +{ + return 0; +} + +ErrCode NotificationHelper::UnSubscribeNotification(NotificationSubscriber &subscriber) +{ + return 0; +} + +ErrCode NotificationHelper::UnSubscribeNotification( + NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo) +{ + return 0; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp new file mode 100644 index 00000000..68402953 --- /dev/null +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -0,0 +1,207 @@ +/* + * 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 "resource_manager_impl.h" + +namespace OHOS { +namespace Global { +namespace Resource { +ResourceManager *CreateResourceManager() +{ + ResourceManagerImpl *impl = new (std::nothrow) ResourceManagerImpl; + return impl; +} + +ResourceManager::~ResourceManager() +{} + +ResourceManagerImpl::ResourceManagerImpl() +{} + +ResourceManagerImpl::~ResourceManagerImpl() +{} + +bool ResourceManagerImpl::AddResource(const char *path) +{ + return true; +} + +RState ResourceManagerImpl::UpdateResConfig(ResConfig &resConfig) +{ + return SUCCESS; +} + +void ResourceManagerImpl::GetResConfig(ResConfig &resConfig) +{} + +RState ResourceManagerImpl::GetStringById(uint32_t id, std::string &outValue) +{ + outValue = "ENTRY"; + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringByName(const char *name, std::string &outValue) +{ + outValue = "bgmode_test"; + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringFormatById(std::string &outValue, uint32_t id, ...) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringFormatByName(std::string &outValue, const char *name, ...) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringArrayById(uint32_t id, std::vector &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringArrayByName(const char *name, std::vector &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPatternById(uint32_t id, std::map &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPatternByName(const char *name, std::map &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPluralStringById(uint32_t id, int quantity, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPluralStringByName(const char *name, int quantity, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPluralStringByIdFormat(std::string &outValue, uint32_t id, int quantity, ...) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPluralStringByNameFormat(std::string &outValue, const char *name, int quantity, ...) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetThemeById(uint32_t id, std::map &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetThemeByName(const char *name, std::map &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetBooleanById(uint32_t id, bool &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetBooleanByName(const char *name, bool &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetIntegerById(uint32_t id, int &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetIntegerByName(const char *name, int &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetFloatById(uint32_t id, float &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetFloatById(uint32_t id, float &outValue, std::string &unit) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetFloatByName(const char *name, float &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetFloatByName(const char *name, float &outValue, std::string &unit) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetIntArrayById(uint32_t id, std::vector &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetIntArrayByName(const char *name, std::vector &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetColorById(uint32_t id, uint32_t &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetColorByName(const char *name, uint32_t &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetProfileById(uint32_t id, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetProfileByName(const char *name, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetMediaById(uint32_t id, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetMediaByName(const char *name, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetRawFilePathByName(const std::string &name, std::string &outValue) +{ + return SUCCESS; +} +} +} +} \ No newline at end of file diff --git a/test/systemtest/bgtask_dump_test.cpp b/test/systemtest/bgtask_dump_test.cpp index 276fd0ac..b4fa831c 100644 --- a/test/systemtest/bgtask_dump_test.cpp +++ b/test/systemtest/bgtask_dump_test.cpp @@ -90,5 +90,23 @@ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_001, Function | MediumTest | L EXPECT_EQ(ret, 0); } } + +/* + * @tc.name: BgtaskDumpTest_ShellDump_002 + * @tc.desc: Shell dump + * @tc.type: FUNC + * @tc.require: AR000GH6EQ + */ +HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_002, Function | MediumTest | Level0) +{ + std::vector infos; + std::vector options; + options.push_back("-C"); + options.push_back("--all"); + if (bgtaskMgr_ != nullptr) { + auto ret = bgtaskMgr_->ShellDump(options, infos); + EXPECT_EQ(ret, 0); + } +} } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/utils/BUILD.gn b/utils/BUILD.gn index dd79d914..3218c9d5 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -16,4 +16,5 @@ import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") group("bgtaskmgr_dump") { deps = [ "dump:btm_target" ] + deps += [ "bgtask_observer:bgtask_observer_target" ] } diff --git a/utils/bgtask_observer/BUILD.gn b/utils/bgtask_observer/BUILD.gn new file mode 100644 index 00000000..7f7c33c2 --- /dev/null +++ b/utils/bgtask_observer/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") + +group("bgtask_observer_target") { + deps = [ ":bgtask_observer" ] +} + +ohos_executable("bgtask_observer") { + include_dirs = [ "include" ] + + sources = [ + "src/bgtask_observer.cpp", + "src/main.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", + "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + ] + + configs = [] + + external_deps = [ + "ability_runtime:want", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + "utils_base:utils", + ] + + install_enable = false + part_name = "background_task_mgr" +} diff --git a/utils/bgtask_observer/include/bgtask_observer.h b/utils/bgtask_observer/include/bgtask_observer.h new file mode 100644 index 00000000..79eccba1 --- /dev/null +++ b/utils/bgtask_observer/include/bgtask_observer.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_UTILS_BGTASK_OBSERVER_INCLUDE_BGTASK_OBSERVER_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_UTILS_BGTASK_OBSERVER_INCLUDE_BGTASK_OBSERVER_H + +#include "background_task_mgr_helper.h" +#include "background_task_subscriber.h" +#include "iremote_object.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class BgTaskObserver : public OHOS::BackgroundTaskMgr::BackgroundTaskSubscriber { +public: + virtual void OnContinuousTaskStart(const std::shared_ptr + &continuousTaskCallbackInfo) override; + + virtual void OnContinuousTaskStop(const std::shared_ptr + &continuousTaskCallbackInfo) override; + + virtual void OnRemoteDied(const wptr &object) override; + + std::atomic isRemoteDied_ {false}; +}; +} +} +#endif \ No newline at end of file diff --git a/utils/bgtask_observer/src/bgtask_observer.cpp b/utils/bgtask_observer/src/bgtask_observer.cpp new file mode 100644 index 00000000..a8e7d707 --- /dev/null +++ b/utils/bgtask_observer/src/bgtask_observer.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bgtask_observer.h" + +#include + +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +void BgTaskObserver::OnContinuousTaskStart(const std::shared_ptr &continuousTaskCallbackInfo) +{ + BGTASK_LOGI("Continuous Task Start"); + std::stringstream stream; + int32_t typeId = continuousTaskCallbackInfo->GetTypeId(); + uid_t uid = continuousTaskCallbackInfo->GetCreatorUid(); + pid_t pid = continuousTaskCallbackInfo->GetCreatorPid(); + std::string abiliytName = continuousTaskCallbackInfo->GetAbilityName(); + stream.str(""); + stream.clear(); + stream << "Continuous Task Start:" << "\n"; + stream << "\ttask typeId: " << typeId << "\n"; + stream << "\ttask uid: " << uid << "\n"; + stream << "\ttask pid: " << pid << "\n"; + stream << "\ttask abiliytName: " << abiliytName << "\n"; + + std::cout << stream.str() << std::endl; +} + +void BgTaskObserver::OnContinuousTaskStop(const std::shared_ptr &continuousTaskCallbackInfo) +{ + BGTASK_LOGI("Continuous Task Stop"); + std::stringstream stream; + int32_t typeId = continuousTaskCallbackInfo->GetTypeId(); + uid_t uid = continuousTaskCallbackInfo->GetCreatorUid(); + pid_t pid = continuousTaskCallbackInfo->GetCreatorPid(); + std::string abiliytName = continuousTaskCallbackInfo->GetAbilityName(); + stream.str(""); + stream.clear(); + stream << "Continuous Task Stop:" << "\n"; + stream << "\ttask typeId: " << typeId << "\n"; + stream << "\ttask uid: " << uid << "\n"; + stream << "\ttask pid: " << pid << "\n"; + stream << "\ttask abiliytName: " << abiliytName << "\n"; + + std::cout << stream.str() << std::endl; +} + +void BgTaskObserver::OnRemoteDied(const wptr &object) +{ + BGTASK_LOGI("remote service died"); + isRemoteDied_.store(true); +} +} +} \ No newline at end of file diff --git a/utils/bgtask_observer/src/main.cpp b/utils/bgtask_observer/src/main.cpp new file mode 100644 index 00000000..6291bc13 --- /dev/null +++ b/utils/bgtask_observer/src/main.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "background_task_mgr_helper.h" +#include "background_task_subscriber.h" +#include "bgtask_observer.h" + +namespace { +static constexpr int32_t DELAY_TIME = 1000; +static constexpr int32_t MAX_CHAR_NUMS = 100; + +void CycleTest() +{ + auto bgtaskObserver = std::make_shared(); + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver) + == OHOS::ERR_OK) { + std::cout << "register succeed in cycletest" << std::endl; + } + while (true) { + if (bgtaskObserver->isRemoteDied_.load()) { + std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_TIME)); + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver) + == OHOS::ERR_OK) { + std::cout << "try to subscribe again succeed" << std::endl; + bgtaskObserver->isRemoteDied_.store(false); + } + } + } +} + +void PatchTest(int nums) +{ + std::list> observerList; + for (int i = 0; i < nums; i++) { + auto bgtaskObserver = std::make_shared(); + observerList.emplace_back(bgtaskObserver); + } + + int index = 1; + for (auto observer : observerList) { + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*observer) + == OHOS::ERR_OK) { + std::cout << "register succeed No." << index << std::endl; + } + index++; + } + std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_TIME)); + index = 1; + for (auto observer : observerList) { + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*observer) + == OHOS::ERR_OK) { + std::cout << "unregister succeed No." << index << std::endl; + } + index++; + } +} +} + +int main(int argc, char *argv[]) +{ + auto bgtaskObserver = std::make_shared(); + char command[MAX_CHAR_NUMS]; + int nums; + while (std::cin >> command >> nums) { + std::string commandStr = command; + if (commandStr == "register") { + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver) + == OHOS::ERR_OK) { + std::cout << "register once succeed" << std::endl; + } + } + if (commandStr == "unregister") { + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*bgtaskObserver) + == OHOS::ERR_OK) { + std::cout << "unregister once succeed" << std::endl; + } + } + if (commandStr == "patchtest") { + PatchTest(nums); + } + if (commandStr == "cycletest") { + CycleTest(); + } + } + return 0; +} \ No newline at end of file diff --git a/utils/dump/src/bgtaskmgr_shell_command.cpp b/utils/dump/src/bgtaskmgr_shell_command.cpp index 3e6a44dd..2845c1f5 100644 --- a/utils/dump/src/bgtaskmgr_shell_command.cpp +++ b/utils/dump/src/bgtaskmgr_shell_command.cpp @@ -28,9 +28,11 @@ namespace OHOS { namespace BackgroundTaskMgr { namespace { +static constexpr int32_t MIN_CONTINUOUS_TASK_DUMP_PARAMS_NUM = 4; static const struct option OPTIONS[] = { {"help", no_argument, nullptr, 'h'}, {"transient", no_argument, nullptr, 'T'}, + {"continuous", no_argument, nullptr, 'C'}, }; static const std::string HELP_MSG = "usage: bgtask []\n" @@ -47,7 +49,10 @@ static const std::string DUMP_HELP_MSG = " SCREEN_ON sreen on mode\n" " SCREEN_OFF sreen off mode\n" " DUMP_CANCEL cancel dump mode\n" - " All list all request\n"; + " All list all request\n" + " -C, --all list all running continuous task infos\n" + " --cancel_all cancel all running continuous task\n" + " --cancel cancel one task by specifying task key\n"; } // namespace BgtaskmgrShellCommand::BgtaskmgrShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "bgtask") @@ -95,7 +100,7 @@ ErrCode BgtaskmgrShellCommand::RunAsHelpCommand() ErrCode BgtaskmgrShellCommand::RunAsDumpCommand() { int ind = 0; - int option = getopt_long(argc_, argv_, "hT", OPTIONS, &ind); + int option = getopt_long(argc_, argv_, "hTC", OPTIONS, &ind); ErrCode ret = ERR_OK; if (btm_ == nullptr) { @@ -112,6 +117,14 @@ ErrCode BgtaskmgrShellCommand::RunAsDumpCommand() ret = btm_->ShellDump(argList_, infos); } break; + case 'C': + if (argc_ < MIN_CONTINUOUS_TASK_DUMP_PARAMS_NUM || btm_ == nullptr) { + resultReceiver_.append(DUMP_HELP_MSG); + ret = ERR_BGTASK_SERVICE_NOT_CONNECTED; + break; + } + ret = btm_->ShellDump(argList_, infos); + break; default: resultReceiver_.append("Please input correct command!\n"); resultReceiver_.append(DUMP_HELP_MSG); -- Gitee From 636534db797dc1a409c1a06fb9188ec7f4785b50 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 08:49:19 +0800 Subject: [PATCH 19/77] bugfix for notification prompt init failed Signed-off-by: zhangxin_T --- .../include/bg_continuous_task_mgr.h | 2 ++ .../src/bg_continuous_task_mgr.cpp | 20 ++++++++++++++----- services/test/unittest/BUILD.gn | 1 + 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index 562e24d6..30d11de1 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -74,6 +74,8 @@ public: void InitNecessaryState(); + void InitNotificationPrompt(); + void Clear(); private: diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index c94ba645..1214b5b0 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -86,8 +86,8 @@ bool BgContinuousTaskMgr::Init() BGTASK_LOGE("BgContinuousTaskMgr handler create failed!"); return false; } - auto task = [this]() { this->InitNecessaryState(); }; - handler_->PostSyncTask(task); + auto registerTask = [this]() { this->InitNecessaryState(); }; + handler_->PostSyncTask(registerTask); return true; } @@ -130,11 +130,21 @@ void BgContinuousTaskMgr::InitNecessaryState() BGTASK_LOGE("RegisterSysCommEventListener failed"); isInitSucceed = false; } + if (isInitSucceed) { + auto getPromptTask = [this]() { this->InitNotificationPrompt(); }; + handler_->PostTask(getPromptTask, DELAY_TIME); + } +} + +void BgContinuousTaskMgr::InitNotificationPrompt() { if (!GetContinuousTaskText()) { - BGTASK_LOGE("GetContinuousTaskText failed"); - isInitSucceed = false; + BGTASK_LOGW("init continuous task notification prompt failed. will try again"); + isSysReady_.store(false); + auto task = [this]() { this->InitNotificationPrompt(); }; + handler_->PostTask(task, DELAY_TIME); + return; } - isSysReady_.store(isInitSucceed); + isSysReady_.store(true); } bool BgContinuousTaskMgr::RegisterNotificationSubscriber() diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index dd24250d..a010cd73 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("bgtask_unit_test") { "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_image_standard:image_native", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "utils_base:utils", -- Gitee From 52171ffbfadfba2a5e468ef4689eaceb1a55a9e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Fri, 11 Feb 2022 10:37:57 +0800 Subject: [PATCH 20/77] add test SR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- .../transient_task_jsunit.test.js | 8 ++++---- .../background_task_mgr_service_test.cpp | 2 +- .../test/unittest/bg_transient_task_mgr_test.cpp | 16 ++++++++-------- test/systemtest/bgtask_dump_test.cpp | 4 ++-- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js b/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js index 22997910..bb5e8d71 100644 --- a/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js +++ b/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js @@ -49,7 +49,7 @@ describe("TransientTaskJsTest", function () { * @tc.name: TransientTaskJsTest001 * @tc.desc: test request a suspend delay * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86N AR000GH86L + * @tc.require: SR000GGTES AR000GH86K AR000GH86N AR000GH86L */ it("TransientTaskJsTest001", 0, async function (done) { console.info('----------------------TransientTaskJsTest001---------------------------'); @@ -69,7 +69,7 @@ describe("TransientTaskJsTest", function () { * @tc.name: TransientTaskJsTest002 * @tc.desc: test transient task more than three * @tc.type: FUNC - * @tc.require: AR000GH86K AR000GH86L AR000GH86N + * @tc.require: SR000GGTES AR000GH86K AR000GH86L AR000GH86N */ it("TransientTaskJsTest002", 0, async function (done) { console.info('----------------------TransientTaskJsTest002---------------------------'); @@ -94,7 +94,7 @@ describe("TransientTaskJsTest", function () { * @tc.name: TransientTaskJsTest003 * @tc.desc: test getRemainingDelayTime Promise * @tc.type: FUNC - * @tc.require: AR000GH86M AR000GH860 AR000GH86L + * @tc.require: SR000GGTJV AR000GH86M AR000GH860 AR000GH86L */ it("TransientTaskJsTest003", 0, async function (done) { function callback() {} @@ -126,7 +126,7 @@ describe("TransientTaskJsTest", function () { * @tc.name: TransientTaskJsTest004 * @tc.desc: test getRemainingDelayTime Callback * @tc.type: FUNC - * @tc.require: AR000GH86M AR000GH860 AR000GH86L + * @tc.require: SR000GGTJV AR000GH86M AR000GH860 AR000GH86L */ it("TransientTaskJsTest004", 0, async function (done) { function callback() {} diff --git a/services/test/unittest/background_task_mgr_service_test.cpp b/services/test/unittest/background_task_mgr_service_test.cpp index 45f36042..6fa37b66 100644 --- a/services/test/unittest/background_task_mgr_service_test.cpp +++ b/services/test/unittest/background_task_mgr_service_test.cpp @@ -37,7 +37,7 @@ public: * @tc.name: BackgroundTaskMgrServiceTest_001 * @tc.desc: Test BackgroundTaskMgrService service ready. * @tc.type: FUNC - * @tc.require: AR000GH86O AR000GH86Q + * @tc.require: SR000GGTET AR000GH86O AR000GH86Q */ HWTEST_F(BackgroundTaskMgrServiceTest, BackgroundTaskMgrServiceTest_001, TestSize.Level1) { diff --git a/services/test/unittest/bg_transient_task_mgr_test.cpp b/services/test/unittest/bg_transient_task_mgr_test.cpp index cc10fb3a..ada0fe80 100644 --- a/services/test/unittest/bg_transient_task_mgr_test.cpp +++ b/services/test/unittest/bg_transient_task_mgr_test.cpp @@ -45,7 +45,7 @@ public: * @tc.name: SubscribeTransientTask_001 * @tc.desc: subscribe transient task event. * @tc.type: FUNC - * @tc.require: AR000GH86P AR000GH86O + * @tc.require: SR000GGTET AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_001, TestSize.Level1) { @@ -58,7 +58,7 @@ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_001, TestSize.Level1) * @tc.name: SubscribeTransientTask_002 * @tc.desc: subscribe transient task event. * @tc.type: FUNC - * @tc.require: AR000GH86P AR000GH86O + * @tc.require: SR000GGTET AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_002, TestSize.Level1) { @@ -70,7 +70,7 @@ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_002, TestSize.Level1) * @tc.name: SubscribeTransientTask_003 * @tc.desc: subscribe transient task event. * @tc.type: FUNC - * @tc.require: AR000GH86P AR000GH86O + * @tc.require: SR000GGTET AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_003, TestSize.Level1) { @@ -86,7 +86,7 @@ HWTEST_F(BgTransientTaskMgrTest, SubscribeTransientTask_003, TestSize.Level1) * @tc.name: UnsubscribeTransientTask_001 * @tc.desc: unsubscribe transient task event. * @tc.type: FUNC - * @tc.require: AR000GH86P AR000GH86O + * @tc.require: SR000GGTET AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_001, TestSize.Level1) { @@ -104,7 +104,7 @@ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_001, TestSize.Level1) * @tc.name: UnsubscribeTransientTask_002 * @tc.desc: unsubscribe transient task event. * @tc.type: FUNC - * @tc.require: AR000GH86P AR000GH86O + * @tc.require: SR000GGTET AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_002, TestSize.Level1) { @@ -117,7 +117,7 @@ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_002, TestSize.Level1) * @tc.name: UnsubscribeTransientTask_003 * @tc.desc: unsubscribe transient task event. * @tc.type: FUNC - * @tc.require: AR000GH86P AR000GH86O + * @tc.require: SR000GGTET AR000GH86P AR000GH86O */ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_003, TestSize.Level1) { @@ -129,7 +129,7 @@ HWTEST_F(BgTransientTaskMgrTest, UnsubscribeTransientTask_003, TestSize.Level1) * @tc.name: Marshalling_001 * @tc.desc: marshalling transient task app info. * @tc.type: FUNC - * @tc.require: AR000GH86Q + * @tc.require: SR000GGTET AR000GH86Q */ HWTEST_F(BgTransientTaskMgrTest, Marshalling_001, TestSize.Level1) { @@ -144,7 +144,7 @@ HWTEST_F(BgTransientTaskMgrTest, Marshalling_001, TestSize.Level1) * @tc.name: Unmarshalling_001 * @tc.desc: unmarshalling transient task app info. * @tc.type: FUNC - * @tc.require: AR000GH86Q + * @tc.require: SR000GGTET AR000GH86Q */ HWTEST_F(BgTransientTaskMgrTest, Unmarshalling_001, TestSize.Level1) { diff --git a/test/systemtest/bgtask_dump_test.cpp b/test/systemtest/bgtask_dump_test.cpp index 276fd0ac..8c12dc03 100644 --- a/test/systemtest/bgtask_dump_test.cpp +++ b/test/systemtest/bgtask_dump_test.cpp @@ -60,7 +60,7 @@ void BgtaskDumpTest::TearDown() * @tc.name: BgtaskDumpTest_GetServiceObject_001 * @tc.desc: Get Service Object * @tc.type: FUNC - * @tc.require: AR000GH86Q + * @tc.require: SR000GGTET AR000GH86Q */ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_GetServiceObject_001, Function | MediumTest | Level0) { @@ -77,7 +77,7 @@ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_GetServiceObject_001, Function | MediumT * @tc.name: BgtaskDumpTest_ShellDump_001 * @tc.desc: Shell dump * @tc.type: FUNC - * @tc.require: AR000GH85V + * @tc.require: SR000GGTJU AR000GH85V */ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_001, Function | MediumTest | Level0) { -- Gitee From 36d53f3c26318cd84fd9ab9efe10650fcffa0f7a Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 11:57:54 +0800 Subject: [PATCH 21/77] add new api ability token and codeCheck bugfix Signed-off-by: zhangxin_T --- frameworks/include/ibackground_task_mgr.h | 8 ++--- .../include/continuous_task_callback_info.h | 8 ++--- .../src/background_task_subscriber.cpp | 24 +++++-------- .../src/continuous_task_callback_info.cpp | 14 ++++---- interfaces/innerkits/src/expired_callback.cpp | 3 +- .../src/bg_continuous_task_napi_module.cpp | 18 ++++++++-- .../kits/napi/src/request_suspend_delay.cpp | 3 +- .../src/bg_continuous_task_mgr.cpp | 9 +++-- .../src/continuous_task_record.cpp | 3 +- .../src/system_event_observer.cpp | 3 +- .../src/task_notification_subscriber.cpp | 30 ++++++---------- .../core/src/background_task_mgr_service.cpp | 6 ++-- .../unittest/bg_continuous_task_mgr_test.cpp | 9 ++--- .../unittest/bg_transient_task_mgr_test.cpp | 6 ++-- .../mock/mock_bundle_manager_helper.cpp | 12 +++---- .../test/unittest/mock/mock_event_handler.cpp | 36 +++++++------------ .../unittest/mock/mock_resource_manager.cpp | 12 +++---- test/systemtest/bgtask_dump_test.cpp | 9 ++--- utils/dump/src/bgtaskmgr_shell_command.cpp | 3 +- utils/dump/src/shell_command.cpp | 3 +- 20 files changed, 88 insertions(+), 131 deletions(-) diff --git a/frameworks/include/ibackground_task_mgr.h b/frameworks/include/ibackground_task_mgr.h index 256f9cf9..79d974d6 100644 --- a/frameworks/include/ibackground_task_mgr.h +++ b/frameworks/include/ibackground_task_mgr.h @@ -39,13 +39,13 @@ public: virtual ErrCode RequestSuspendDelay(const std::u16string& reason, const sptr& callback, std::shared_ptr &delayInfo) = 0; - virtual ErrCode CancelSuspendDelay(int32_t requestId) = 0; + virtual ErrCode CancelSuspendDelay(int32_t requestId) = 0; virtual ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) = 0; virtual ErrCode StartBackgroundRunning(const sptr taskParam) = 0; virtual ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken) = 0; - virtual ErrCode SubscribeBackgroundTask(const sptr& subscriber) = 0; - virtual ErrCode UnsubscribeBackgroundTask(const sptr& subscriber) = 0; - virtual ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) = 0; + virtual ErrCode SubscribeBackgroundTask(const sptr &subscriber) = 0; + virtual ErrCode UnsubscribeBackgroundTask(const sptr &subscriber) = 0; + virtual ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) = 0; public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.resourceschedule.IBackgroundTaskMgr"); diff --git a/interfaces/innerkits/include/continuous_task_callback_info.h b/interfaces/innerkits/include/continuous_task_callback_info.h index da802a89..cae9910e 100644 --- a/interfaces/innerkits/include/continuous_task_callback_info.h +++ b/interfaces/innerkits/include/continuous_task_callback_info.h @@ -27,10 +27,10 @@ public: ContinuousTaskCallbackInfo(); ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, pid_t creatorPid, std::string abilityName); - int32_t GetTypeId(); - uid_t GetCreatorUid(); - pid_t GetCreatorPid(); - std::string GetAbilityName(); + int32_t GetTypeId() const; + uid_t GetCreatorUid() const; + pid_t GetCreatorPid() const; + std::string GetAbilityName() const; bool Marshalling(Parcel &parcel) const; static ContinuousTaskCallbackInfo *Unmarshalling(Parcel &parcel); diff --git a/interfaces/innerkits/src/background_task_subscriber.cpp b/interfaces/innerkits/src/background_task_subscriber.cpp index b0c2459f..ad56a6f9 100644 --- a/interfaces/innerkits/src/background_task_subscriber.cpp +++ b/interfaces/innerkits/src/background_task_subscriber.cpp @@ -25,31 +25,23 @@ BackgroundTaskSubscriber::BackgroundTaskSubscriber() impl_ = new BackgroundTaskSubscriberImpl(*this); }; -BackgroundTaskSubscriber::~BackgroundTaskSubscriber() -{} +BackgroundTaskSubscriber::~BackgroundTaskSubscriber() {} -void BackgroundTaskSubscriber::OnConnected() -{} +void BackgroundTaskSubscriber::OnConnected() {} -void BackgroundTaskSubscriber::OnDisconnected() -{} +void BackgroundTaskSubscriber::OnDisconnected() {} -void BackgroundTaskSubscriber::OnTransientTaskStart(const std::shared_ptr& info) -{} +void BackgroundTaskSubscriber::OnTransientTaskStart(const std::shared_ptr& info) {} -void BackgroundTaskSubscriber::OnTransientTaskEnd(const std::shared_ptr& info) -{} +void BackgroundTaskSubscriber::OnTransientTaskEnd(const std::shared_ptr& info) {} void BackgroundTaskSubscriber::OnContinuousTaskStart( - const std::shared_ptr &continuousTaskCallbackInfo) -{} + const std::shared_ptr &continuousTaskCallbackInfo) {} void BackgroundTaskSubscriber::OnContinuousTaskStop( - const std::shared_ptr &continuousTaskCallbackInfo) -{} + const std::shared_ptr &continuousTaskCallbackInfo) {} -void BackgroundTaskSubscriber::OnRemoteDied(const wptr &object) -{} +void BackgroundTaskSubscriber::OnRemoteDied(const wptr &object) {} const sptr BackgroundTaskSubscriber::GetImpl() const { diff --git a/interfaces/innerkits/src/continuous_task_callback_info.cpp b/interfaces/innerkits/src/continuous_task_callback_info.cpp index 15efab7f..c70d99dd 100644 --- a/interfaces/innerkits/src/continuous_task_callback_info.cpp +++ b/interfaces/innerkits/src/continuous_task_callback_info.cpp @@ -18,30 +18,28 @@ namespace OHOS { namespace BackgroundTaskMgr { -ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo() -{} +ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo() {} ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, pid_t creatorPid, std::string abilityName) - : typeId_(typeId), creatorUid_(creatorUid), creatorPid_(creatorPid), abilityName_(abilityName) -{} + : typeId_(typeId), creatorUid_(creatorUid), creatorPid_(creatorPid), abilityName_(abilityName) {} -int32_t ContinuousTaskCallbackInfo::GetTypeId() +int32_t ContinuousTaskCallbackInfo::GetTypeId() const { return typeId_; } -uid_t ContinuousTaskCallbackInfo::GetCreatorUid() +uid_t ContinuousTaskCallbackInfo::GetCreatorUid() const { return creatorUid_; } -pid_t ContinuousTaskCallbackInfo::GetCreatorPid() +pid_t ContinuousTaskCallbackInfo::GetCreatorPid() const { return creatorPid_; } -std::string ContinuousTaskCallbackInfo::GetAbilityName() +std::string ContinuousTaskCallbackInfo::GetAbilityName() const { return abilityName_; } diff --git a/interfaces/innerkits/src/expired_callback.cpp b/interfaces/innerkits/src/expired_callback.cpp index a7a43225..239f158d 100644 --- a/interfaces/innerkits/src/expired_callback.cpp +++ b/interfaces/innerkits/src/expired_callback.cpp @@ -22,8 +22,7 @@ ExpiredCallback::ExpiredCallback() impl_ = new ExpiredCallbackImpl(*this); }; -ExpiredCallback::~ExpiredCallback() -{} +ExpiredCallback::~ExpiredCallback() {} const sptr ExpiredCallback::GetImpl() const { diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp index 630d32b5..ff0b4e4d 100644 --- a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -144,6 +144,13 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) return; } + sptr token {nullptr}; + auto abilityContext = asyncCallbackInfo->ability->GetAbilityContext(); + if (abilityContext) { + BGTASK_LOGI("get ability context succeed"); + token = abilityContext->GetToken(); + } + if (asyncCallbackInfo->bgMode < BG_MODE_ID_BEGIN || asyncCallbackInfo->bgMode > BG_MODE_ID_END) { BGTASK_LOGE("request background mode id: %{public}d out of range", asyncCallbackInfo->bgMode); asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; @@ -151,7 +158,7 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) } ContinuousTaskParam taskParam = ContinuousTaskParam(true, asyncCallbackInfo->bgMode, - std::make_shared(*asyncCallbackInfo->wantAgent), info->name, nullptr); + std::make_shared(*asyncCallbackInfo->wantAgent), info->name, token); asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam); BGTASK_LOGI("end"); @@ -356,7 +363,14 @@ void StopBackgroundRunningExecuteCB(napi_env env, void *data) asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; return; } - asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStopBackgroundRunning(info->name, nullptr); + + sptr token {nullptr}; + auto abilityContext = asyncCallbackInfo->ability->GetAbilityContext(); + if (abilityContext) { + BGTASK_LOGI("get ability context succeed"); + token = abilityContext->GetToken(); + } + asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStopBackgroundRunning(info->name, token); } napi_value StopBackgroundRunningAsync(napi_env env, napi_value *argv, diff --git a/interfaces/kits/napi/src/request_suspend_delay.cpp b/interfaces/kits/napi/src/request_suspend_delay.cpp index 3d5bed19..865a97e2 100644 --- a/interfaces/kits/napi/src/request_suspend_delay.cpp +++ b/interfaces/kits/napi/src/request_suspend_delay.cpp @@ -24,8 +24,7 @@ namespace OHOS { namespace BackgroundTaskMgr { static const int32_t REQUEST_SUSPEND_DELAY_PARAMS = 2; -CallbackInstance::CallbackInstance() -{} +CallbackInstance::CallbackInstance() {} CallbackInstance::~CallbackInstance() { diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 1214b5b0..cd27e6e5 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -68,11 +68,9 @@ static constexpr uint32_t BG_MODE_INDEX_HEAD = 1; static constexpr int BGMODE_NUMS = 10; } -BgContinuousTaskMgr::BgContinuousTaskMgr() -{} +BgContinuousTaskMgr::BgContinuousTaskMgr() {} -BgContinuousTaskMgr::~BgContinuousTaskMgr() -{} +BgContinuousTaskMgr::~BgContinuousTaskMgr() {} bool BgContinuousTaskMgr::Init() { @@ -136,7 +134,8 @@ void BgContinuousTaskMgr::InitNecessaryState() } } -void BgContinuousTaskMgr::InitNotificationPrompt() { +void BgContinuousTaskMgr::InitNotificationPrompt() +{ if (!GetContinuousTaskText()) { BGTASK_LOGW("init continuous task notification prompt failed. will try again"); isSysReady_.store(false); diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index a3bfa181..1f66de05 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -36,8 +36,7 @@ ContinuousTaskRecord::ContinuousTaskRecord(const std::string &bundleName, const const std::shared_ptr &wantAgent, const sptr &abilityToken, int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi) : bundleName_(bundleName), abilityName_(abilityName), wantAgent_(wantAgent), abilityToken_(abilityToken), - userId_(userId), uid_(uid), pid_(pid), bgModeId_(bgModeId), isNewApi_(isNewApi) -{} + userId_(userId), uid_(uid), pid_(pid), bgModeId_(bgModeId), isNewApi_(isNewApi) {} std::string ContinuousTaskRecord::GetBundleName() const { diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp index 0f36f44f..92d4987d 100644 --- a/services/continuous_task/src/system_event_observer.cpp +++ b/services/continuous_task/src/system_event_observer.cpp @@ -29,8 +29,7 @@ const std::string TASK_ON_BUNDLEINFO_CHANGED = "OnBundleInfoChanged"; } SystemEventObserver::SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo) - : EventFwk::CommonEventSubscriber(subscribeInfo) -{} + : EventFwk::CommonEventSubscriber(subscribeInfo) {} bool SystemEventObserver::Subscribe() { diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index 7c360c32..d8ee070b 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -39,20 +39,15 @@ static constexpr uint32_t LABEL_SIZE = 4; std::shared_ptr TaskNotificationSubscriber::continuousTaskMgr_ = BgContinuousTaskMgr::GetInstance(); -TaskNotificationSubscriber::TaskNotificationSubscriber() -{} +TaskNotificationSubscriber::TaskNotificationSubscriber() {} -TaskNotificationSubscriber::~TaskNotificationSubscriber() -{} +TaskNotificationSubscriber::~TaskNotificationSubscriber() {} -void TaskNotificationSubscriber::OnConnected() -{} +void TaskNotificationSubscriber::OnConnected() {} -void TaskNotificationSubscriber::OnDisconnected() -{} +void TaskNotificationSubscriber::OnDisconnected() {} -void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification) -{} +void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification) {} void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification, const std::shared_ptr &sortingMap, int deleteReason) @@ -99,23 +94,18 @@ void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification) -{} +void TaskNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification) {} void TaskNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification, - const std::shared_ptr &sortingMap) -{} + const std::shared_ptr &sortingMap) {} void TaskNotificationSubscriber::OnUpdate( - const std::shared_ptr &sortingMap) -{} + const std::shared_ptr &sortingMap) {} -void TaskNotificationSubscriber::OnDied() -{} +void TaskNotificationSubscriber::OnDied() {} void TaskNotificationSubscriber::OnDoNotDisturbDateChange( - const std::shared_ptr &date) -{} + const std::shared_ptr &date) {} std::vector TaskNotificationSubscriber::StringSplit(const std::string &str, const char *delim) { diff --git a/services/core/src/background_task_mgr_service.cpp b/services/core/src/background_task_mgr_service.cpp index 593ecb5f..85386396 100644 --- a/services/core/src/background_task_mgr_service.cpp +++ b/services/core/src/background_task_mgr_service.cpp @@ -36,11 +36,9 @@ const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility( } BackgroundTaskMgrService::BackgroundTaskMgrService() - : SystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID, true) -{} + : SystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID, true) {} -BackgroundTaskMgrService::~BackgroundTaskMgrService() -{} +BackgroundTaskMgrService::~BackgroundTaskMgrService() {} void BackgroundTaskMgrService::OnStart() { diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp index 0484c3d2..0e8f106e 100644 --- a/services/test/unittest/bg_continuous_task_mgr_test.cpp +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -61,8 +61,7 @@ void BgContinuousTaskMgrTest::TearDownTestCase() bgContinuousTaskMgr_ = nullptr; } -void BgContinuousTaskMgrTest::SetUp() -{} +void BgContinuousTaskMgrTest::SetUp() {} void BgContinuousTaskMgrTest::TearDown() { @@ -76,12 +75,10 @@ void BgContinuousTaskMgrTest::TearDown() class TestBackgroundTaskSubscriber : public BackgroundTaskSubscriber { public: virtual void OnContinuousTaskStart(const std::shared_ptr - &continuousTaskCallbackInfo) override - {} + &continuousTaskCallbackInfo) override {} virtual void OnContinuousTaskStop(const std::shared_ptr - &continuousTaskCallbackInfo) override - {} + &continuousTaskCallbackInfo) override {} }; /** diff --git a/services/test/unittest/bg_transient_task_mgr_test.cpp b/services/test/unittest/bg_transient_task_mgr_test.cpp index cc10fb3a..9faa9d1f 100644 --- a/services/test/unittest/bg_transient_task_mgr_test.cpp +++ b/services/test/unittest/bg_transient_task_mgr_test.cpp @@ -27,10 +27,8 @@ namespace OHOS { namespace BackgroundTaskMgr { class TestBackgroundTaskSubscriber : public BackgroundTaskSubscriber { public: - void OnTransientTaskStart(const std::shared_ptr& info) override - {} - void OnTransientTaskEnd(const std::shared_ptr& info) override - {} + void OnTransientTaskStart(const std::shared_ptr& info) override {} + void OnTransientTaskEnd(const std::shared_ptr& info) override {} }; class BgTransientTaskMgrTest : public testing::Test { diff --git a/services/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/test/unittest/mock/mock_bundle_manager_helper.cpp index 032aa4aa..00cfa133 100644 --- a/services/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -25,11 +25,9 @@ namespace { static constexpr char TEST_DEFAULT_BUNDLE[] = "bundleName"; } -BundleManagerHelper::BundleManagerHelper() -{} +BundleManagerHelper::BundleManagerHelper() {} -BundleManagerHelper::~BundleManagerHelper() -{} +BundleManagerHelper::~BundleManagerHelper() {} std::string BundleManagerHelper::GetClientBundleName(uid_t uid) { @@ -63,10 +61,8 @@ bool BundleManagerHelper::Connect() return true; } -void BundleManagerHelper::Disconnect() -{} +void BundleManagerHelper::Disconnect() {} -void BundleManagerHelper::OnRemoteDied(const wptr &object) -{} +void BundleManagerHelper::OnRemoteDied(const wptr &object) {} } } \ No newline at end of file diff --git a/services/test/unittest/mock/mock_event_handler.cpp b/services/test/unittest/mock/mock_event_handler.cpp index e317c0c5..94d094c7 100644 --- a/services/test/unittest/mock/mock_event_handler.cpp +++ b/services/test/unittest/mock/mock_event_handler.cpp @@ -23,11 +23,9 @@ std::shared_ptr EventHandler::Current() return wp.lock(); } -EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) -{} +EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) {} -EventHandler::~EventHandler() -{} +EventHandler::~EventHandler() {} bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Priority priority) { @@ -48,17 +46,13 @@ bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) return true; } -void EventHandler::RemoveAllEvents() -{} +void EventHandler::RemoveAllEvents() {} -void EventHandler::RemoveEvent(uint32_t innerEventId) -{} +void EventHandler::RemoveEvent(uint32_t innerEventId) {} -void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) -{} +void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) {} -void EventHandler::RemoveTask(const std::string &name) -{} +void EventHandler::RemoveTask(const std::string &name) {} ErrCode EventHandler::AddFileDescriptorListener( int32_t fileDescriptor, uint32_t events, const std::shared_ptr &listener) @@ -66,20 +60,15 @@ ErrCode EventHandler::AddFileDescriptorListener( return EVENT_HANDLER_ERR_INVALID_PARAM; } -void EventHandler::RemoveAllFileDescriptorListeners() -{} +void EventHandler::RemoveAllFileDescriptorListeners() {} -void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) -{} +void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) {} -void EventHandler::SetEventRunner(const std::shared_ptr &runner) -{} +void EventHandler::SetEventRunner(const std::shared_ptr &runner) {} -void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) -{} +void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) {} -void EventHandler::Dump(Dumper &dumper) -{} +void EventHandler::Dump(Dumper &dumper) {} bool EventHandler::HasInnerEvent(uint32_t innerEventId) { @@ -101,7 +90,6 @@ bool EventHandler::IsIdle() return true; } -void EventHandler::ProcessEvent(const InnerEvent::Pointer &) -{} +void EventHandler::ProcessEvent(const InnerEvent::Pointer &) {} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp index 68402953..eb3fb0a2 100644 --- a/services/test/unittest/mock/mock_resource_manager.cpp +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -24,14 +24,11 @@ ResourceManager *CreateResourceManager() return impl; } -ResourceManager::~ResourceManager() -{} +ResourceManager::~ResourceManager() {} -ResourceManagerImpl::ResourceManagerImpl() -{} +ResourceManagerImpl::ResourceManagerImpl() {} -ResourceManagerImpl::~ResourceManagerImpl() -{} +ResourceManagerImpl::~ResourceManagerImpl() {} bool ResourceManagerImpl::AddResource(const char *path) { @@ -43,8 +40,7 @@ RState ResourceManagerImpl::UpdateResConfig(ResConfig &resConfig) return SUCCESS; } -void ResourceManagerImpl::GetResConfig(ResConfig &resConfig) -{} +void ResourceManagerImpl::GetResConfig(ResConfig &resConfig) {} RState ResourceManagerImpl::GetStringById(uint32_t id, std::string &outValue) { diff --git a/test/systemtest/bgtask_dump_test.cpp b/test/systemtest/bgtask_dump_test.cpp index b4fa831c..f69c78d5 100644 --- a/test/systemtest/bgtask_dump_test.cpp +++ b/test/systemtest/bgtask_dump_test.cpp @@ -40,11 +40,9 @@ public: std::shared_ptr bgtaskMgr_; }; -void BgtaskDumpTest::SetUpTestCase() -{} +void BgtaskDumpTest::SetUpTestCase() {} -void BgtaskDumpTest::TearDownTestCase() -{} +void BgtaskDumpTest::TearDownTestCase() {} void BgtaskDumpTest::SetUp() { @@ -53,8 +51,7 @@ void BgtaskDumpTest::SetUp() } } -void BgtaskDumpTest::TearDown() -{} +void BgtaskDumpTest::TearDown() {} /* * @tc.name: BgtaskDumpTest_GetServiceObject_001 diff --git a/utils/dump/src/bgtaskmgr_shell_command.cpp b/utils/dump/src/bgtaskmgr_shell_command.cpp index 2845c1f5..ea908c7c 100644 --- a/utils/dump/src/bgtaskmgr_shell_command.cpp +++ b/utils/dump/src/bgtaskmgr_shell_command.cpp @@ -55,8 +55,7 @@ static const std::string DUMP_HELP_MSG = " --cancel cancel one task by specifying task key\n"; } // namespace -BgtaskmgrShellCommand::BgtaskmgrShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "bgtask") -{} +BgtaskmgrShellCommand::BgtaskmgrShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "bgtask") {} ErrCode BgtaskmgrShellCommand::CreateCommandMap() { diff --git a/utils/dump/src/shell_command.cpp b/utils/dump/src/shell_command.cpp index afb6ab4e..2a9c4d93 100644 --- a/utils/dump/src/shell_command.cpp +++ b/utils/dump/src/shell_command.cpp @@ -37,8 +37,7 @@ ShellCommand::ShellCommand(int argc, char *argv[], std::string name) } } -ShellCommand::~ShellCommand() -{} +ShellCommand::~ShellCommand() {} ErrCode ShellCommand::OnCommand() { -- Gitee From 7827cb114008fdb6dbc31bef17368b195734d64f Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 15:07:54 +0800 Subject: [PATCH 22/77] test case related SR number Signed-off-by: zhangxin_T --- .../continuous_task_jsunit.test.js | 16 ++++++++-------- .../unittest/bg_continuous_task_mgr_test.cpp | 10 +++++----- test/systemtest/bgtask_dump_test.cpp | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js index c8851ad5..daf02b6d 100644 --- a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js +++ b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js @@ -58,7 +58,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest001 * @tc.desc:verify new startBackgroundrunning interface promise mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO + * @tc.require: SR000GGT7U AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO */ it("ContinuousTaskJsTest001", 0, async function (done) { let wantAgentInfo = { @@ -94,7 +94,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest002 * @tc.desc:verify new startBackgroundrunning interface callback mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 + * @tc.require: SR000GGT7T AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 */ it("ContinuousTaskJsTest002", 0, async function (done) { function conTaskCallback(err, data) { @@ -130,7 +130,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest003 * @tc.desc:verify old startBackgroundrunning interface promise mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH56K + * @tc.require: SR000GGT7V AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH56K */ it("ContinuousTaskJsTest003", 0, async function (done) { let wantAgentInfo = { @@ -182,7 +182,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest004 * @tc.desc:verify old startBackgroundrunning interface callback mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH6ET + * @tc.require: SR000GGT81 AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH6ET */ it("ContinuousTaskJsTest004", 0, async function (done) { function conTaskCallback(err, data) { @@ -234,7 +234,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest005 * @tc.desc:verify new api stopBackgroundrunning interface promise mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EM AR000GH6EN AR000GH6EO + * @tc.require: SR000GGT7U AR000GH6ES AR000GH6EM AR000GH6EN AR000GH6EO */ it("ContinuousTaskJsTest005", 0, async function (done) { let wantAgentInfo = { @@ -272,7 +272,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest006 * @tc.desc:verify new api stopBackgroundrunning interface callback mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EP AR000GJ9PR AR000GH6G8 + * @tc.require: SR000GGT7T AR000GH6ES AR000GH6EP AR000GJ9PR AR000GH6G8 */ it("ContinuousTaskJsTest006", 0, async function (done) { function conTaskCallback(err, data) { @@ -310,7 +310,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest007 * @tc.desc:verify old api cancelBackgroundrunning interface promise mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K + * @tc.require: SR000GGT7V AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K */ it("ContinuousTaskJsTest007", 0, async function (done) { let wantAgentInfo = { @@ -349,7 +349,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest008 * @tc.desc:verify old cancelBackgroundrunning interface callback mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH6ET + * @tc.require: SR000GGT81 AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH6ET */ it("ContinuousTaskJsTest008", 0, async function (done) { function conTaskCallback(err, data) { diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp index 0e8f106e..b4bfbff5 100644 --- a/services/test/unittest/bg_continuous_task_mgr_test.cpp +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -85,7 +85,7 @@ public: * @tc.name: StartBackgroundRunning_001 * @tc.desc: start background runnging use new api test. * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO + * @tc.require: SR000GGT7U AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO */ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_001, TestSize.Level1) { @@ -111,7 +111,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_001, TestSize.Level1) * @tc.name: StartBackgroundRunning_002 * @tc.desc: start background runnging use old api test. * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 + * @tc.require: SR000GGT7T AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 */ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) { @@ -129,7 +129,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) * @tc.name: StopBackgroundRunning_001 * @tc.desc: start background runnging use new api test. * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K + * @tc.require: SR000GGT7V AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K */ HWTEST_F(BgContinuousTaskMgrTest, StopBackgroundRunning_001, TestSize.Level1) { @@ -150,7 +150,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StopBackgroundRunning_001, TestSize.Level1) * @tc.name: StartBackgroundRunning_001 * @tc.desc: subscribe continuous task event callback test. * @tc.type: FUNC - * @tc.require: AR000GH6EM AR000GH6G9 AR000GH6ET + * @tc.require: SR000GGT81 AR000GH6EM AR000GH6G9 AR000GH6ET */ HWTEST_F(BgContinuousTaskMgrTest, SubscribeContinuousTask_001, TestSize.Level1) { @@ -166,7 +166,7 @@ HWTEST_F(BgContinuousTaskMgrTest, SubscribeContinuousTask_001, TestSize.Level1) * @tc.name: UnsubscribeContinuousTask_001 * @tc.desc: unsubscribe continuous task event callback test. * @tc.type: FUNC - * @tc.require: AR000GH6EM AR000GH6G9 AR000GH6ET + * @tc.require: SR000GGT7U AR000GH6EM AR000GH6G9 AR000GH6ET */ HWTEST_F(BgContinuousTaskMgrTest, UnsubscribeContinuousTask_001, TestSize.Level1) { diff --git a/test/systemtest/bgtask_dump_test.cpp b/test/systemtest/bgtask_dump_test.cpp index f69c78d5..3d63ce27 100644 --- a/test/systemtest/bgtask_dump_test.cpp +++ b/test/systemtest/bgtask_dump_test.cpp @@ -92,7 +92,7 @@ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_001, Function | MediumTest | L * @tc.name: BgtaskDumpTest_ShellDump_002 * @tc.desc: Shell dump * @tc.type: FUNC - * @tc.require: AR000GH6EQ + * @tc.require: SR000GGT80 AR000GH6EQ */ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_002, Function | MediumTest | Level0) { -- Gitee From 749ebf6f0a2a65764543c5f4aeb13f97f33872b7 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 16:57:07 +0800 Subject: [PATCH 23/77] change License info Signed-off-by: zhangxin_T --- frameworks/common/include/continuous_task_log.h | 2 +- interfaces/innerkits/include/continuous_task_callback_info.h | 2 +- interfaces/innerkits/include/continuous_task_param.h | 2 +- interfaces/innerkits/src/continuous_task_callback_info.cpp | 2 +- interfaces/innerkits/src/continuous_task_param.cpp | 2 +- .../continuous_task_jsunittest/continuous_task_jsunit.test.js | 2 +- services/continuous_task/include/app_state_observer.h | 2 +- services/continuous_task/include/bg_continuous_task_mgr.h | 2 +- services/continuous_task/include/bundle_manager_helper.h | 2 +- services/continuous_task/include/continuous_task_record.h | 2 +- services/continuous_task/include/remote_death_recipient.h | 2 +- services/continuous_task/include/system_event_observer.h | 2 +- services/continuous_task/include/task_notification_subscriber.h | 2 +- services/continuous_task/src/app_state_observer.cpp | 2 +- services/continuous_task/src/bg_continuous_task_mgr.cpp | 2 +- services/continuous_task/src/bundle_manager_helper.cpp | 2 +- services/continuous_task/src/continuous_task_record.cpp | 2 +- services/continuous_task/src/system_event_observer.cpp | 2 +- services/continuous_task/src/task_notification_subscriber.cpp | 2 +- services/test/unittest/bg_continuous_task_mgr_test.cpp | 2 +- services/test/unittest/mock/mock_bundle_manager_helper.cpp | 2 +- services/test/unittest/mock/mock_notification_helper.cpp | 2 +- services/test/unittest/mock/mock_resource_manager.cpp | 2 +- 23 files changed, 23 insertions(+), 23 deletions(-) diff --git a/frameworks/common/include/continuous_task_log.h b/frameworks/common/include/continuous_task_log.h index db3f7e91..282ef60d 100644 --- a/frameworks/common/include/continuous_task_log.h +++ b/frameworks/common/include/continuous_task_log.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/innerkits/include/continuous_task_callback_info.h b/interfaces/innerkits/include/continuous_task_callback_info.h index cae9910e..1aa13997 100644 --- a/interfaces/innerkits/include/continuous_task_callback_info.h +++ b/interfaces/innerkits/include/continuous_task_callback_info.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/innerkits/include/continuous_task_param.h b/interfaces/innerkits/include/continuous_task_param.h index 7b68b9f2..d5aa92f0 100644 --- a/interfaces/innerkits/include/continuous_task_param.h +++ b/interfaces/innerkits/include/continuous_task_param.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/innerkits/src/continuous_task_callback_info.cpp b/interfaces/innerkits/src/continuous_task_callback_info.cpp index c70d99dd..72379b23 100644 --- a/interfaces/innerkits/src/continuous_task_callback_info.cpp +++ b/interfaces/innerkits/src/continuous_task_callback_info.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/innerkits/src/continuous_task_param.cpp b/interfaces/innerkits/src/continuous_task_param.cpp index 3ca2ad7a..973cfa1b 100644 --- a/interfaces/innerkits/src/continuous_task_param.cpp +++ b/interfaces/innerkits/src/continuous_task_param.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js index daf02b6d..15cc39a4 100644 --- a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js +++ b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/app_state_observer.h b/services/continuous_task/include/app_state_observer.h index 85e48696..3f118aed 100644 --- a/services/continuous_task/include/app_state_observer.h +++ b/services/continuous_task/include/app_state_observer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index 30d11de1..9ef40bbd 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/bundle_manager_helper.h b/services/continuous_task/include/bundle_manager_helper.h index e18af8c1..21b5af19 100644 --- a/services/continuous_task/include/bundle_manager_helper.h +++ b/services/continuous_task/include/bundle_manager_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h index c20aa1cf..83722030 100644 --- a/services/continuous_task/include/continuous_task_record.h +++ b/services/continuous_task/include/continuous_task_record.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/remote_death_recipient.h b/services/continuous_task/include/remote_death_recipient.h index f6938123..d43ff79f 100644 --- a/services/continuous_task/include/remote_death_recipient.h +++ b/services/continuous_task/include/remote_death_recipient.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/system_event_observer.h b/services/continuous_task/include/system_event_observer.h index 734e5150..0225c3de 100644 --- a/services/continuous_task/include/system_event_observer.h +++ b/services/continuous_task/include/system_event_observer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/task_notification_subscriber.h b/services/continuous_task/include/task_notification_subscriber.h index d16a06c5..6e4c0e41 100644 --- a/services/continuous_task/include/task_notification_subscriber.h +++ b/services/continuous_task/include/task_notification_subscriber.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/app_state_observer.cpp b/services/continuous_task/src/app_state_observer.cpp index 8e5776dd..b9d050c5 100644 --- a/services/continuous_task/src/app_state_observer.cpp +++ b/services/continuous_task/src/app_state_observer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index cd27e6e5..4935dab6 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/bundle_manager_helper.cpp b/services/continuous_task/src/bundle_manager_helper.cpp index b25de200..a2b838f9 100644 --- a/services/continuous_task/src/bundle_manager_helper.cpp +++ b/services/continuous_task/src/bundle_manager_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index 1f66de05..dae7312d 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp index 92d4987d..87aafde6 100644 --- a/services/continuous_task/src/system_event_observer.cpp +++ b/services/continuous_task/src/system_event_observer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index d8ee070b..9cc29b8f 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp index b4bfbff5..8cb18d16 100644 --- a/services/test/unittest/bg_continuous_task_mgr_test.cpp +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/test/unittest/mock/mock_bundle_manager_helper.cpp index 00cfa133..77f444bd 100644 --- a/services/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/test/unittest/mock/mock_notification_helper.cpp b/services/test/unittest/mock/mock_notification_helper.cpp index 4611c313..b78edb36 100644 --- a/services/test/unittest/mock/mock_notification_helper.cpp +++ b/services/test/unittest/mock/mock_notification_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp index eb3fb0a2..383cdc0e 100644 --- a/services/test/unittest/mock/mock_resource_manager.cpp +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -- Gitee From afc4abf8ac7156fcc7db91460fc9cd97edea1105 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 21:21:57 +0800 Subject: [PATCH 24/77] code format modify Signed-off-by: zhangxin_T --- frameworks/src/background_task_mgr_proxy.cpp | 73 ++++++++++--------- .../src/background_task_subscriber_proxy.cpp | 24 +++--- .../src/background_task_subscriber_stub.cpp | 2 - frameworks/src/expired_callback_proxy.cpp | 4 +- frameworks/src/expired_callback_stub.cpp | 2 +- .../src/bg_continuous_task_napi_module.cpp | 32 ++++---- .../kits/napi/src/request_suspend_delay.cpp | 4 +- .../include/app_state_observer.h | 1 - .../include/bg_continuous_task_mgr.h | 37 +--------- .../include/bundle_manager_helper.h | 1 - .../include/continuous_task_record.h | 11 --- .../include/remote_death_recipient.h | 1 + .../include/system_event_observer.h | 4 - .../include/task_notification_subscriber.h | 10 --- .../src/bg_continuous_task_mgr.cpp | 6 +- .../src/task_notification_subscriber.cpp | 7 +- .../core/src/background_task_mgr_service.cpp | 8 +- utils/bgtask_observer/src/bgtask_observer.cpp | 2 +- utils/dump/src/shell_command.cpp | 1 - 19 files changed, 80 insertions(+), 150 deletions(-) diff --git a/frameworks/src/background_task_mgr_proxy.cpp b/frameworks/src/background_task_mgr_proxy.cpp index deead535..a5d88bf4 100644 --- a/frameworks/src/background_task_mgr_proxy.cpp +++ b/frameworks/src/background_task_mgr_proxy.cpp @@ -32,7 +32,7 @@ ErrCode BackgroundTaskMgrProxy::RequestSuspendDelay(const std::u16string& reason const sptr& callback, std::shared_ptr &delayInfo) { if (callback == nullptr) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s callback is null", __func__); + BGTASK_LOGE("callback is null"); return ERR_BGTASK_INVALID_PARAM; } @@ -40,30 +40,30 @@ ErrCode BackgroundTaskMgrProxy::RequestSuspendDelay(const std::u16string& reason MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write descriptor failed", __func__); + BGTASK_LOGE("write descriptor failed"); return ERR_BGTASK_PARCELABLE_FAILED; } if (!data.WriteString16(reason)) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write reason failed", __func__); + BGTASK_LOGE("write reason failed"); return ERR_BGTASK_PARCELABLE_FAILED; } if (!data.WriteRemoteObject(callback->AsObject())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write callback failed", __func__); + BGTASK_LOGE("write callback failed"); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(REQUEST_SUSPEND_DELAY, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } delayInfo = DelaySuspendInfo::Unmarshalling(reply); if (delayInfo == nullptr) { - BGTASK_LOGE("BackgroundTaskMgrProxy::%{public}s, read result failed", __func__); + BGTASK_LOGE("read result failed"); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -75,21 +75,21 @@ ErrCode BackgroundTaskMgrProxy::CancelSuspendDelay(int32_t requestId) MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write descriptor failed", __func__); + BGTASK_LOGE("write descriptor failed"); return ERR_BGTASK_PARCELABLE_FAILED; } if (!data.WriteInt32(requestId)) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write requestId failed", __func__); + BGTASK_LOGE("write requestId failed"); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(CANCEL_SUSPEND_DELAY, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -111,15 +111,15 @@ ErrCode BackgroundTaskMgrProxy::GetRemainingDelayTime(int32_t requestId, int32_t ErrCode result = InnerTransact(GET_REMAINING_DELAY_TIME, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } if (!reply.ReadInt32(delayTime)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -146,11 +146,11 @@ ErrCode BackgroundTaskMgrProxy::StartBackgroundRunning(const sptr& subscriber) { if (subscriber == nullptr) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s subscriber is null", __func__); + BGTASK_LOGE("subscriber is null"); return ERR_BGTASK_PARCELABLE_FAILED; } @@ -202,21 +203,21 @@ ErrCode BackgroundTaskMgrProxy::SubscribeBackgroundTask(const sptrAsObject())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write subscriber failed", __func__); + BGTASK_LOGE("write subscriber failed"); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(SUBSCRIBE_BACKGROUND_TASK, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -225,7 +226,7 @@ ErrCode BackgroundTaskMgrProxy::SubscribeBackgroundTask(const sptr& subscriber) { if (subscriber == nullptr) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s subscriber is null", __func__); + BGTASK_LOGE("subscriber is null"); return ERR_BGTASK_PARCELABLE_FAILED; } @@ -233,21 +234,21 @@ ErrCode BackgroundTaskMgrProxy::UnsubscribeBackgroundTask(const sptrAsObject())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write subscriber failed", __func__); + BGTASK_LOGE("write subscriber failed"); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(UNSUBSCRIBE_BACKGROUND_TASK, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -260,26 +261,26 @@ ErrCode BackgroundTaskMgrProxy::ShellDump(const std::vector &dumpOp MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { - BGTASK_LOGE("[ShellDump] fail: write interface token failed."); + BGTASK_LOGE("write interface token failed."); return ERR_BGTASK_PARCELABLE_FAILED; } if (!data.WriteStringVector(dumpOption)) { - BGTASK_LOGE("[ShellDump] fail: write option failed."); + BGTASK_LOGE("write option failed."); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(SHELL_DUMP, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } if (!reply.ReadStringVector(&dumpInfo)) { - BGTASK_LOGI("[ShellDump] fail: read dumpInfo failed."); + BGTASK_LOGE("read dumpInfo failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -290,7 +291,7 @@ ErrCode BackgroundTaskMgrProxy::InnerTransact(uint32_t code, MessageOption &flag { auto remote = Remote(); if (remote == nullptr) { - BGTASK_LOGI("[InnerTransact] fail: get Remote fail code %{public}d", code); + BGTASK_LOGE("get Remote fail code %{public}d", code); return ERR_DEAD_OBJECT; } int err = remote->SendRequest(code, data, reply, flags); @@ -299,11 +300,11 @@ ErrCode BackgroundTaskMgrProxy::InnerTransact(uint32_t code, MessageOption &flag return ERR_OK; } case DEAD_OBJECT: { - BGTASK_LOGI("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); + BGTASK_LOGE("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); return ERR_DEAD_OBJECT; } default: { - BGTASK_LOGI("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); + BGTASK_LOGE("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); return ERR_BGTASK_TRANSACT_FAILED; } } diff --git a/frameworks/src/background_task_subscriber_proxy.cpp b/frameworks/src/background_task_subscriber_proxy.cpp index 1e2d253f..acc38797 100644 --- a/frameworks/src/background_task_subscriber_proxy.cpp +++ b/frameworks/src/background_task_subscriber_proxy.cpp @@ -34,7 +34,7 @@ void BackgroundTaskSubscriberProxy::OnConnected() } MessageParcel data; if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { - BGTASK_LOGE("[OnConnected] fail: write interface token failed."); + BGTASK_LOGE("write interface token failed."); return; } @@ -56,7 +56,7 @@ void BackgroundTaskSubscriberProxy::OnDisconnected() } MessageParcel data; if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { - BGTASK_LOGE("[OnDisconnected] fail: write interface token failed."); + BGTASK_LOGE("write interface token failed."); return; } @@ -73,25 +73,25 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskStart(const std::shared_ptr remote = Remote(); if (remote == nullptr) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s remote is dead.", __func__); + BGTASK_LOGE("remote is dead."); return; } MessageParcel data; bool res = data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor()); if (!res) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, write descriptor failed.", __func__); + BGTASK_LOGE("write descriptor failed."); return; } if (!info->Marshalling(data)) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, write parcel failed.", __func__); + BGTASK_LOGE("write parcel failed."); return; } MessageParcel reply; MessageOption option; int ret = remote->SendRequest(ON_TRANSIENT_TASK_START, data, reply, option); if (ret != ERR_NONE) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, SendRequest failed, error code: %d", __func__, ret); + BGTASK_LOGE("SendRequest failed, error code: %d", ret); return; } } @@ -100,25 +100,25 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskEnd(const std::shared_ptr remote = Remote(); if (remote == nullptr) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s remote is dead.", __func__); + BGTASK_LOGE("remote is dead."); return; } MessageParcel data; bool res = data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor()); if (!res) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, write descriptor failed.", __func__); + BGTASK_LOGE("write descriptor failed."); return; } if (!info->Marshalling(data)) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, write parcel failed.", __func__); + BGTASK_LOGE("write parcel failed."); return; } MessageParcel reply; MessageOption option; int ret = remote->SendRequest(ON_TRANSIENT_TASK_END, data, reply, option); if (ret != ERR_NONE) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, SendRequest failed, error code: %d", __func__, ret); + BGTASK_LOGE("SendRequest failed, error code: %d", ret); return; } } @@ -144,7 +144,7 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStart( } if (!data.WriteParcelable(continuousTaskCallbackInfo)) { - BGTASK_LOGI("write continuousTaskCallbackInfo failed."); + BGTASK_LOGE("write continuousTaskCallbackInfo failed."); return; } @@ -155,7 +155,6 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStart( BGTASK_LOGE("SendRequest error"); return; } - BGTASK_LOGI("end"); } void BackgroundTaskSubscriberProxy::OnContinuousTaskStop( @@ -190,7 +189,6 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStop( BGTASK_LOGE("SendRequest error"); return; } - BGTASK_LOGI("end"); } } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/frameworks/src/background_task_subscriber_stub.cpp b/frameworks/src/background_task_subscriber_stub.cpp index 13aa9c45..c3328bf6 100644 --- a/frameworks/src/background_task_subscriber_stub.cpp +++ b/frameworks/src/background_task_subscriber_stub.cpp @@ -114,7 +114,6 @@ ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskStart(MessageParcel } OnContinuousTaskStart(continuousTaskCallbackInfo); - BGTASK_LOGI("end"); return ERR_OK; } @@ -128,7 +127,6 @@ ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskCancel(MessageParcel } OnContinuousTaskStop(continuousTaskCallbackInfo); - BGTASK_LOGI("end"); return ERR_OK; } } // namespace BackgroundTaskMgr diff --git a/frameworks/src/expired_callback_proxy.cpp b/frameworks/src/expired_callback_proxy.cpp index 9e93f1d8..b474f015 100644 --- a/frameworks/src/expired_callback_proxy.cpp +++ b/frameworks/src/expired_callback_proxy.cpp @@ -29,7 +29,7 @@ void ExpiredCallbackProxy::OnExpired() { sptr remote = Remote(); if (remote == nullptr) { - BGTASK_LOGE("ExpiredCallbackProxy::%{public}s remote is dead.", __func__); + BGTASK_LOGE("remote is dead."); return; } @@ -38,7 +38,7 @@ void ExpiredCallbackProxy::OnExpired() MessageOption option(MessageOption::TF_ASYNC); bool res = data.WriteInterfaceToken(ExpiredCallbackProxy::GetDescriptor()); if (!res) { - BGTASK_LOGE("ExpiredCallbackProxy::%{public}s, write descriptor failed.", __func__); + BGTASK_LOGE("write descriptor failed."); return; } remote->SendRequest(ON_EXPIRED, data, reply, option); diff --git a/frameworks/src/expired_callback_stub.cpp b/frameworks/src/expired_callback_stub.cpp index 3582ee00..9d5d6814 100644 --- a/frameworks/src/expired_callback_stub.cpp +++ b/frameworks/src/expired_callback_stub.cpp @@ -30,7 +30,7 @@ int ExpiredCallbackStub::OnRemoteRequest(uint32_t code, std::u16string descriptor = ExpiredCallbackStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { - BGTASK_LOGE("ExpiredCallbackStub::%{public}s, local descriptor not match remote.", __func__); + BGTASK_LOGE("local descriptor not match remote."); return ERR_TRANSACTION_FAILED; } switch (code) { diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp index ff0b4e4d..b9687efc 100644 --- a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -72,7 +72,7 @@ AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env) { BGTASK_LOGI("begin"); if (env == nullptr) { - BGTASK_LOGE("env == nullptr."); + BGTASK_LOGE("env is nullptr."); return nullptr; } @@ -101,7 +101,7 @@ AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env) AsyncCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo; if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("asyncCallbackInfo == nullptr"); + BGTASK_LOGE("asyncCallbackInfo is nullptr"); return nullptr; } asyncCallbackInfo->env = env; @@ -119,7 +119,7 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) BGTASK_LOGI("begin"); AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("asyncCallbackInfo == nullptr"); + BGTASK_LOGE("asyncCallbackInfo is nullptr"); return; } if (asyncCallbackInfo->errCode != ERR_OK) { @@ -128,12 +128,12 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) } if (asyncCallbackInfo->ability == nullptr) { asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; - BGTASK_LOGE("ability == nullptr"); + BGTASK_LOGE("ability is nullptr"); return; } const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); if (info == nullptr) { - BGTASK_LOGE("info == nullptr"); + BGTASK_LOGE("info is nullptr"); asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; return; } @@ -216,7 +216,7 @@ napi_value StartBackgroundRunningAsync( { BGTASK_LOGI("begin"); if (argv == nullptr || asyncCallbackInfo == nullptr) { - BGTASK_LOGE("param == nullptr"); + BGTASK_LOGE("param is nullptr"); return nullptr; } napi_value resourceName = 0; @@ -244,7 +244,7 @@ napi_value StartBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncC { BGTASK_LOGI("begin"); if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("param == nullptr"); + BGTASK_LOGE("param is nullptr"); return nullptr; } napi_value resourceName; @@ -271,13 +271,11 @@ napi_value GetBackgroundMode(const napi_env &env, const napi_value &value, int32 BGTASK_LOGI("begin"); napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, value, &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, value, &bgMode); BGTASK_LOGI("get bgmode info: %{public}d", bgMode); - return WrapVoidToJS(env); } @@ -333,7 +331,7 @@ napi_value StartBackgroundRunning(napi_env env, napi_callback_info info) } if (ret == nullptr) { - BGTASK_LOGE("ret == nullpter"); + BGTASK_LOGE("ret is nullpter"); if (asyncCallbackInfo != nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; @@ -349,17 +347,17 @@ void StopBackgroundRunningExecuteCB(napi_env env, void *data) BGTASK_LOGI("begin"); AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("asyncCallbackInfo == nullptr"); + BGTASK_LOGE("asyncCallbackInfo is nullptr"); return; } if (asyncCallbackInfo->ability == nullptr) { asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; - BGTASK_LOGE("ability == nullptr"); + BGTASK_LOGE("ability is nullptr"); return; } const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); if (info == nullptr) { - BGTASK_LOGE("abilityInfo == nullptr"); + BGTASK_LOGE("abilityInfo is nullptr"); asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; return; } @@ -378,7 +376,7 @@ napi_value StopBackgroundRunningAsync(napi_env env, napi_value *argv, { BGTASK_LOGI("begin"); if (argv == nullptr || asyncCallbackInfo == nullptr) { - BGTASK_LOGE("param == nullptr"); + BGTASK_LOGE("param is nullptr"); return nullptr; } napi_value resourceName = 0; @@ -406,7 +404,7 @@ napi_value StopBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCa { BGTASK_LOGI("begin"); if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("param == nullptr"); + BGTASK_LOGE("param is nullptr"); return nullptr; } napi_value resourceName = 0; @@ -435,7 +433,7 @@ napi_value StopBackgroundRunning(napi_env env, napi_callback_info info) BGTASK_LOGI("begin"); AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("asyncCallbackInfo == nullpter"); + BGTASK_LOGE("asyncCallbackInfo is nullpter"); return WrapVoidToJS(env); } @@ -458,7 +456,7 @@ napi_value StopBackgroundRunning(napi_env env, napi_callback_info info) } if (ret == nullptr) { - BGTASK_LOGE("ret == nullpter"); + BGTASK_LOGE("ret is nullpter"); if (asyncCallbackInfo != nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; diff --git a/interfaces/kits/napi/src/request_suspend_delay.cpp b/interfaces/kits/napi/src/request_suspend_delay.cpp index 865a97e2..ab7ae7dd 100644 --- a/interfaces/kits/napi/src/request_suspend_delay.cpp +++ b/interfaces/kits/napi/src/request_suspend_delay.cpp @@ -38,7 +38,7 @@ void CallbackInstance::OnExpired() BGTASK_LOGI("enter"); if (expiredCallbackInfo_.ref == nullptr) { - BGTASK_LOGI("expired callback unset"); + BGTASK_LOGE("expired callback unset"); return; } @@ -116,7 +116,7 @@ napi_value RequestSuspendDelay(napi_env env, napi_callback_info info) napi_value result = nullptr; napi_create_object(env, &result); if (!Common::SetDelaySuspendInfo(env, delaySuspendInfo, result)) { - BGTASK_LOGI("Set DelaySuspendInfo object failed"); + BGTASK_LOGW("Set DelaySuspendInfo object failed"); } return result; } diff --git a/services/continuous_task/include/app_state_observer.h b/services/continuous_task/include/app_state_observer.h index 3f118aed..672ef69b 100644 --- a/services/continuous_task/include/app_state_observer.h +++ b/services/continuous_task/include/app_state_observer.h @@ -32,7 +32,6 @@ public: AppStateObserver(); ~AppStateObserver(); void OnProcessDied(const AppExecFwk::ProcessData &processData) override; - void SetEventHandler(const std::shared_ptr &handler); void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); bool Subscribe(); diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index 9ef40bbd..915834b7 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -53,76 +53,41 @@ class BgContinuousTaskMgr : public DelayedSingleton, public std::enable_shared_from_this { public: ErrCode StartBackgroundRunning(const sptr taskParam); - ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken); - ErrCode AddSubscriber(const sptr &subscriber); - ErrCode RemoveSubscriber(const sptr &subscriber); - ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); - bool StopContinuousTaskByUser(const std::string &mapKey); - void OnBundleInfoChanged(const std::string &action, const std::string &bundleName, uid_t uid); - void OnProcessDied(int32_t pid); - void OnRemoteSubscriberDied(const wptr &object); - bool Init(); - void InitNecessaryState(); - void InitNotificationPrompt(); - void Clear(); private: ErrCode StartBackgroundRunningInner(std::shared_ptr &continuousTaskRecordPtr); - ErrCode StopBackgroundRunningInner(uid_t uid, const std::string &abilityName, const sptr &abilityToken); - ErrCode AddSubscriberInner(const sptr &subscriber); - ErrCode RemoveSubscriberInner(const sptr &subscriber); - ErrCode ShellDumpInner(const std::vector &dumpOption, std::vector &dumpInfo); - + ErrCode SendContinuousTaskNotification(std::shared_ptr &ContinuousTaskRecordPtr); void DumpAllTaskInfo(std::vector &dumpInfo); - void DumpCancelTask(const std::vector &dumpOption, bool cleanAll); - - ErrCode SendContinuousTaskNotification(std::shared_ptr &ContinuousTaskRecordPtr); - bool RemoveContinuousTaskRecord(const std::string &mapKey); - - bool InitAllBundleBriefInfos(); - bool AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); - std::string CreateNotificationLabel(uid_t uid, const std::string &bundleName, const std::string &abilityName, sptr abilityToken); - uint32_t GetBackgroundModeInfo(uid_t uid, std::string &abilityName); - bool AddAbilityBgModeInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); - bool RegisterNotificationSubscriber(); - bool RegisterSysCommEventListener(); - bool RegisterAppStateObserver(); - bool GetContinuousTaskText(); - bool SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName); - void OnRemoteSubscriberDiedInner(const wptr &object); - - std::string CreateNotificationText(int32_t typeId); - void OnContinuousTaskChanged(const std::shared_ptr continuousTaskInfo, ContinuousTaskEventTriggerType changeEventType); diff --git a/services/continuous_task/include/bundle_manager_helper.h b/services/continuous_task/include/bundle_manager_helper.h index 21b5af19..1c17c875 100644 --- a/services/continuous_task/include/bundle_manager_helper.h +++ b/services/continuous_task/include/bundle_manager_helper.h @@ -38,7 +38,6 @@ public: private: bool Connect(); void Disconnect(); - void OnRemoteDied(const wptr &object); private: diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h index 83722030..90f87d15 100644 --- a/services/continuous_task/include/continuous_task_record.h +++ b/services/continuous_task/include/continuous_task_record.h @@ -29,29 +29,18 @@ extern const char *ContinuousTaskModeName[10]; class ContinuousTaskRecord { public: ContinuousTaskRecord() = default; - ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, const std::shared_ptr &wantAgent, const sptr &abilityToken, int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi); - std::string GetBundleName() const; - std::string GetAbilityName() const; - bool IsNewApi() const; - uint32_t GetBgModeId() const; - int32_t GetUserId() const; - uid_t GetUid() const; - pid_t GetPid() const; - std::string GetNotificationLabel() const; - std::shared_ptr GetWantAgent() const; - sptr GetAbilityToken() const; private: diff --git a/services/continuous_task/include/remote_death_recipient.h b/services/continuous_task/include/remote_death_recipient.h index d43ff79f..d1587747 100644 --- a/services/continuous_task/include/remote_death_recipient.h +++ b/services/continuous_task/include/remote_death_recipient.h @@ -28,6 +28,7 @@ public: { callback_ = callback; } + ~RemoteDeathRecipient() { callback_ = nullptr; diff --git a/services/continuous_task/include/system_event_observer.h b/services/continuous_task/include/system_event_observer.h index 0225c3de..c46e20a9 100644 --- a/services/continuous_task/include/system_event_observer.h +++ b/services/continuous_task/include/system_event_observer.h @@ -29,14 +29,10 @@ class SystemEventObserver : public EventFwk::CommonEventSubscriber, public: SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo); ~SystemEventObserver() = default; - void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; - void SetEventHandler(const std::shared_ptr &handler); void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); - bool Subscribe(); - bool Unsubscribe(); private: diff --git a/services/continuous_task/include/task_notification_subscriber.h b/services/continuous_task/include/task_notification_subscriber.h index 6e4c0e41..fc9ff891 100644 --- a/services/continuous_task/include/task_notification_subscriber.h +++ b/services/continuous_task/include/task_notification_subscriber.h @@ -25,27 +25,17 @@ class BgContinuousTaskMgr; class TaskNotificationSubscriber : public Notification::NotificationSubscriber { public: TaskNotificationSubscriber(); - virtual ~TaskNotificationSubscriber(); - virtual void OnConnected() override; - virtual void OnDisconnected() override; - virtual void OnCanceled(const std::shared_ptr &request) override; - virtual void OnCanceled(const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) override; - virtual void OnConsumed(const std::shared_ptr &request) override; - virtual void OnConsumed(const std::shared_ptr &request, const std::shared_ptr &sortingMap) override; - virtual void OnUpdate(const std::shared_ptr &sortingMap) override; - virtual void OnDied() override; - virtual void OnDoNotDisturbDateChange( const std::shared_ptr &date) override; diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 4935dab6..6692982d 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -228,7 +228,7 @@ bool BgContinuousTaskMgr::SetCachedBundleInfo(uid_t uid, int32_t userId, std::st AppExecFwk::BundleInfo bundleInfo; if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId)) { - BGTASK_LOGW("get bundle info: %{public}s failure!", bundleName.c_str()); + BGTASK_LOGE("get bundle info: %{public}s failure!", bundleName.c_str()); return false; } @@ -296,7 +296,7 @@ bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool uint32_t recordedBgMode = BG_MODE_INDEX_HEAD << (requestedBgModeId - 1); if ((recordedBgMode == SYSTEM_APP_BGMODE_WIFI_INTERACTION || recordedBgMode == SYSTEM_APP_BGMODE_VOIP) && !BundleManagerHelper::GetInstance()->IsSystemApp(uid)) { - BGTASK_LOGW("voip and wifiInteraction background mode only support for system app"); + BGTASK_LOGE("voip and wifiInteraction background mode only support for system app"); return false; } if (requestedBgModeId == INVALID_BGMODE || (configuredBgMode @@ -468,7 +468,7 @@ ErrCode BgContinuousTaskMgr::SendContinuousTaskNotification( notificationRequest.SetCreatorUserId(-2); if (Notification::NotificationHelper::PublishContinuousTaskNotification(notificationRequest) != ERR_OK) { - BGTASK_LOGI("publish notification error"); + BGTASK_LOGE("publish notification error"); return ERR_BGTASK_NOTIFICATION_ERR; } continuousTaskRecord->notificationLabel_ = notificationLabel; diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index 9cc29b8f..7a09b1bb 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -68,7 +68,7 @@ void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr extraInfo = request.GetAdditionalData(); - if (extraInfo == nullptr) { - BGTASK_LOGI("notification extraInfo is null"); + BGTASK_LOGE("notification extraInfo is null"); return; } + BGTASK_LOGI("stop continuous task by user, the label is : %{public}s", notificationLabel.c_str()); std::string abilityName = AAFwk::String::Unbox(AAFwk::IString::Query(extraInfo->GetParam("abilityName"))); std::string taskInfoMapKey = labelSplits[LABEL_APP_UID_POS] + LABEL_SPLITER + abilityName diff --git a/services/core/src/background_task_mgr_service.cpp b/services/core/src/background_task_mgr_service.cpp index 85386396..5f5b985a 100644 --- a/services/core/src/background_task_mgr_service.cpp +++ b/services/core/src/background_task_mgr_service.cpp @@ -43,14 +43,12 @@ BackgroundTaskMgrService::~BackgroundTaskMgrService() {} void BackgroundTaskMgrService::OnStart() { if (state_ == ServiceRunningState::STATE_RUNNING) { - BGTASK_LOGI("Service has already started."); + BGTASK_LOGW("Service has already started."); return; } - Init(); - if (!Publish(DelayedSingleton::GetInstance().get())) { - BGTASK_LOGI("Service start failed!"); + BGTASK_LOGE("Service start failed!"); return; } state_ = ServiceRunningState::STATE_RUNNING; @@ -142,7 +140,7 @@ ErrCode BackgroundTaskMgrService::ShellDump(const std::vector &dump } else if (dumpOption[0] == CONTINUOUS_TASK_DUMP) { ret = BgContinuousTaskMgr::GetInstance()->ShellDump(dumpOption, dumpInfo); } else { - BGTASK_LOGI("invalid dump param"); + BGTASK_LOGW("invalid dump param"); ret = ERR_BGTASK_INVALID_PARAM; } return ret; diff --git a/utils/bgtask_observer/src/bgtask_observer.cpp b/utils/bgtask_observer/src/bgtask_observer.cpp index a8e7d707..8e0d594d 100644 --- a/utils/bgtask_observer/src/bgtask_observer.cpp +++ b/utils/bgtask_observer/src/bgtask_observer.cpp @@ -63,7 +63,7 @@ void BgTaskObserver::OnContinuousTaskStop(const std::shared_ptr &object) { - BGTASK_LOGI("remote service died"); + BGTASK_LOGW("remote service died"); isRemoteDied_.store(true); } } diff --git a/utils/dump/src/shell_command.cpp b/utils/dump/src/shell_command.cpp index 2a9c4d93..d4c97289 100644 --- a/utils/dump/src/shell_command.cpp +++ b/utils/dump/src/shell_command.cpp @@ -104,7 +104,6 @@ std::string ShellCommand::GetUnknownOptionMsg(std::string &unknownOption) const std::string ShellCommand::GetMessageFromCode(const int32_t code) const { - BGTASK_LOGI("[%{public}s(%{public}s)] enter", __FILE__, __FUNCTION__); BGTASK_LOGI("code = %{public}d", code); std::string result = ""; -- Gitee From 29eddcdf712c10a5aaada5d9069287ac063005d4 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Thu, 10 Feb 2022 23:52:57 +0800 Subject: [PATCH 25/77] add continuous task feature Signed-off-by: zhangxin_T --- bundle.json | 8 +- frameworks/BUILD.gn | 8 + .../common/include/bgtaskmgr_inner_errors.h | 8 + .../common/include/continuous_task_log.h | 25 + frameworks/include/background_task_manager.h | 5 + .../include/background_task_mgr_proxy.h | 2 + frameworks/include/background_task_mgr_stub.h | 2 + .../background_task_subscriber_proxy.h | 4 + .../include/background_task_subscriber_stub.h | 9 +- frameworks/include/ibackground_task_mgr.h | 6 + .../include/ibackground_task_subscriber.h | 13 +- frameworks/src/background_task_manager.cpp | 29 + frameworks/src/background_task_mgr_proxy.cpp | 66 ++ frameworks/src/background_task_mgr_stub.cpp | 36 + .../src/background_task_subscriber_proxy.cpp | 114 +++ .../src/background_task_subscriber_stub.cpp | 56 +- interfaces/innerkits/BUILD.gn | 16 +- .../innerkits/include/background_mode.h | 38 + .../include/background_task_mgr_helper.h | 18 + .../include/background_task_subscriber.h | 56 +- .../include/continuous_task_callback_info.h | 48 + .../innerkits/include/continuous_task_param.h | 46 + .../src/background_task_mgr_helper.cpp | 11 + .../src/background_task_subscriber.cpp | 96 +- .../src/continuous_task_callback_info.cpp | 98 ++ .../innerkits/src/continuous_task_param.cpp | 113 +++ interfaces/kits/BUILD.gn | 6 + .../kits/js/@ohos.backgroundTaskManager.d.ts | 109 +++ .../include/bg_continuous_task_napi_module.h | 28 + interfaces/kits/napi/include/init.h | 2 + .../src/bg_continuous_task_napi_module.cpp | 458 ++++++++++ interfaces/kits/napi/src/init.cpp | 38 + interfaces/test/unittest/BUILD.gn | 11 +- .../continuous_task_jsunittest/config.json | 74 ++ .../continuous_task_jsunit.test.js | 386 ++++++++ resources/BUILD.gn | 33 + resources/BackgroundTaskResources.p7b | Bin 0 -> 3401 bytes resources/main/config.json | 33 + .../main/resources/base/element/string.json | 44 + .../main/resources/zh_CN/element/string.json | 44 + services/BUILD.gn | 15 + .../include/app_state_observer.h | 55 ++ .../include/bg_continuous_task_mgr.h | 145 +++ .../include/bundle_manager_helper.h | 54 ++ .../include/continuous_task_record.h | 73 ++ .../include/remote_death_recipient.h | 48 + .../include/system_event_observer.h | 48 + .../include/task_notification_subscriber.h | 60 ++ .../src/app_state_observer.cpp | 134 +++ .../src/bg_continuous_task_mgr.cpp | 854 ++++++++++++++++++ .../src/bundle_manager_helper.cpp | 132 +++ .../src/continuous_task_record.cpp | 92 ++ .../src/system_event_observer.cpp | 90 ++ .../src/task_notification_subscriber.cpp | 134 +++ .../include/background_task_mgr_service.h | 3 + .../core/src/background_task_mgr_service.cpp | 30 +- services/test/unittest/BUILD.gn | 8 + .../unittest/bg_continuous_task_mgr_test.cpp | 184 ++++ .../mock/mock_bundle_manager_helper.cpp | 72 ++ .../mock/mock_notification_helper.cpp | 54 ++ .../unittest/mock/mock_resource_manager.cpp | 207 +++++ test/systemtest/bgtask_dump_test.cpp | 18 + utils/BUILD.gn | 1 + utils/bgtask_observer/BUILD.gn | 52 ++ .../bgtask_observer/include/bgtask_observer.h | 39 + utils/bgtask_observer/src/bgtask_observer.cpp | 70 ++ utils/bgtask_observer/src/main.cpp | 102 +++ utils/dump/src/bgtaskmgr_shell_command.cpp | 17 +- 68 files changed, 4968 insertions(+), 20 deletions(-) create mode 100644 frameworks/common/include/continuous_task_log.h create mode 100644 interfaces/innerkits/include/background_mode.h create mode 100644 interfaces/innerkits/include/continuous_task_callback_info.h create mode 100644 interfaces/innerkits/include/continuous_task_param.h create mode 100644 interfaces/innerkits/src/continuous_task_callback_info.cpp create mode 100644 interfaces/innerkits/src/continuous_task_param.cpp create mode 100644 interfaces/kits/napi/include/bg_continuous_task_napi_module.h create mode 100644 interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp create mode 100644 interfaces/test/unittest/continuous_task_jsunittest/config.json create mode 100644 interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js create mode 100644 resources/BUILD.gn create mode 100644 resources/BackgroundTaskResources.p7b create mode 100644 resources/main/config.json create mode 100644 resources/main/resources/base/element/string.json create mode 100644 resources/main/resources/zh_CN/element/string.json create mode 100644 services/continuous_task/include/app_state_observer.h create mode 100644 services/continuous_task/include/bg_continuous_task_mgr.h create mode 100644 services/continuous_task/include/bundle_manager_helper.h create mode 100644 services/continuous_task/include/continuous_task_record.h create mode 100644 services/continuous_task/include/remote_death_recipient.h create mode 100644 services/continuous_task/include/system_event_observer.h create mode 100644 services/continuous_task/include/task_notification_subscriber.h create mode 100644 services/continuous_task/src/app_state_observer.cpp create mode 100644 services/continuous_task/src/bg_continuous_task_mgr.cpp create mode 100644 services/continuous_task/src/bundle_manager_helper.cpp create mode 100644 services/continuous_task/src/continuous_task_record.cpp create mode 100644 services/continuous_task/src/system_event_observer.cpp create mode 100644 services/continuous_task/src/task_notification_subscriber.cpp create mode 100644 services/test/unittest/bg_continuous_task_mgr_test.cpp create mode 100644 services/test/unittest/mock/mock_bundle_manager_helper.cpp create mode 100644 services/test/unittest/mock/mock_notification_helper.cpp create mode 100644 services/test/unittest/mock/mock_resource_manager.cpp create mode 100644 utils/bgtask_observer/BUILD.gn create mode 100644 utils/bgtask_observer/include/bgtask_observer.h create mode 100644 utils/bgtask_observer/src/bgtask_observer.cpp create mode 100644 utils/bgtask_observer/src/main.cpp diff --git a/bundle.json b/bundle.json index 1c3d60dd..2a8e1896 100644 --- a/bundle.json +++ b/bundle.json @@ -12,7 +12,10 @@ "component": { "name": "background_task_mgr", "subsystem": "resourceschedule", - "syscap": [ "SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask" ], + "syscap": [ + "SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask", + "SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask" + ], "features": [], "adapted_system_type": [ "mini", @@ -43,7 +46,8 @@ "//foundation/resourceschedule/background_task_mgr/services:bgtaskmgr_service", "//foundation/resourceschedule/background_task_mgr/sa_profile:bgtaskmgr_sa_profile", "//foundation/resourceschedule/background_task_mgr/sa_profile:bgtaskmgr_service_init", - "//foundation/resourceschedule/background_task_mgr/utils:bgtaskmgr_dump" + "//foundation/resourceschedule/background_task_mgr/utils:bgtaskmgr_dump", + "//foundation/resourceschedule/background_task_mgr/resources:bgtaskmgr_resources" ], "inner_kits": [ { diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn index 9795b083..656ea94e 100644 --- a/frameworks/BUILD.gn +++ b/frameworks/BUILD.gn @@ -25,6 +25,8 @@ config("bgtaskmgr_public_config") { ohos_shared_library("bgtaskmgr_fwk") { sources = [ "${bgtaskmgr_interfaces_path}/innerkits/src/background_task_subscriber.cpp", + "${bgtaskmgr_interfaces_path}/innerkits/src/continuous_task_callback_info.cpp", + "${bgtaskmgr_interfaces_path}/innerkits/src/continuous_task_param.cpp", "${bgtaskmgr_interfaces_path}/innerkits/src/delay_suspend_info.cpp", "${bgtaskmgr_interfaces_path}/innerkits/src/expired_callback.cpp", "${bgtaskmgr_interfaces_path}/innerkits/src/transient_task_app_info.cpp", @@ -38,9 +40,15 @@ ohos_shared_library("bgtaskmgr_fwk") { "src/expired_callback_stub.cpp", ] + deps = [ + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + ] + public_configs = [ ":bgtaskmgr_public_config" ] external_deps = [ + "ability_runtime:want", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/frameworks/common/include/bgtaskmgr_inner_errors.h b/frameworks/common/include/bgtaskmgr_inner_errors.h index 0551efeb..7ebc4b8d 100644 --- a/frameworks/common/include/bgtaskmgr_inner_errors.h +++ b/frameworks/common/include/bgtaskmgr_inner_errors.h @@ -47,6 +47,14 @@ enum : int { ERR_BGTASK_INVALID_PARAM, ERR_BGTASK_NOT_ALLOWED, ERR_BGTASK_OBJECT_EXISTS, + ERR_BGTASK_METHOD_CALLED_FAILED, + ERR_BGTASK_NON_SYSTEM_APP, + ERR_BGTASK_SYS_NOT_READY, + ERR_BGTASK_TASK_ERR, + ERR_BGTASK_PERMISSION_DENIED, + ERR_BGTASK_NOTIFICATION_ERR, + ERR_BGTASK_INVALID_BGMODE, + ERR_BGTASK_NO_MEMORY, }; } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/frameworks/common/include/continuous_task_log.h b/frameworks/common/include/continuous_task_log.h new file mode 100644 index 00000000..db3f7e91 --- /dev/null +++ b/frameworks/common/include/continuous_task_log.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_COMMON_INCLUDE_CONTINUOUS_TASK_LOG_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_COMMON_INCLUDE_CONTINUOUS_TASK_LOG_H + +#ifndef BGTASK_MGR_LOG_TAG +#define BGTASK_MGR_LOG_TAG "CONTINUOUS_TASK" +#endif + +#include "bgtaskmgr_log_wrapper.h" + +#endif \ No newline at end of file diff --git a/frameworks/include/background_task_manager.h b/frameworks/include/background_task_manager.h index 4e747596..ff8bdf18 100644 --- a/frameworks/include/background_task_manager.h +++ b/frameworks/include/background_task_manager.h @@ -20,6 +20,7 @@ #include "expired_callback.h" #include "ibackground_task_mgr.h" #include "iremote_object.h" +#include "want_agent.h" namespace OHOS { namespace BackgroundTaskMgr { @@ -36,6 +37,10 @@ public: ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime); + ErrCode RequestStartBackgroundRunning(const ContinuousTaskParam &taskParam); + + ErrCode RequestStopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken); + void ResetBackgroundTaskManagerProxy(); ErrCode SubscribeBackgroundTask(const BackgroundTaskSubscriber &subscriber); diff --git a/frameworks/include/background_task_mgr_proxy.h b/frameworks/include/background_task_mgr_proxy.h index 77187965..aa602586 100644 --- a/frameworks/include/background_task_mgr_proxy.h +++ b/frameworks/include/background_task_mgr_proxy.h @@ -33,6 +33,8 @@ public: const sptr& callback, std::shared_ptr &delayInfo) override; ErrCode CancelSuspendDelay(int32_t requestId) override; ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) override; + ErrCode StartBackgroundRunning(const sptr taskParam) override; + ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken) override; ErrCode SubscribeBackgroundTask(const sptr& subscriber) override; ErrCode UnsubscribeBackgroundTask(const sptr& subscriber) override; ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) override; diff --git a/frameworks/include/background_task_mgr_stub.h b/frameworks/include/background_task_mgr_stub.h index 94750b40..98aaa398 100644 --- a/frameworks/include/background_task_mgr_stub.h +++ b/frameworks/include/background_task_mgr_stub.h @@ -38,6 +38,8 @@ private: ErrCode HandleRequestSuspendDelay(MessageParcel& data, MessageParcel& reply); ErrCode HandleCancelSuspendDelay(MessageParcel& data, MessageParcel& reply); ErrCode HandleGetRemainingDelayTime(MessageParcel& data, MessageParcel& reply); + ErrCode HandleStartBackgroundRunning(MessageParcel &data, MessageParcel &reply); + ErrCode HandleStopBackgroundRunning(MessageParcel &data, MessageParcel &reply); ErrCode HandleSubscribeBackgroundTask(MessageParcel& data, MessageParcel& reply); ErrCode HandleUnsubscribeBackgroundTask(MessageParcel& data, MessageParcel& reply); ErrCode HandleShellDump(MessageParcel& data, MessageParcel& reply); diff --git a/frameworks/include/background_task_subscriber_proxy.h b/frameworks/include/background_task_subscriber_proxy.h index fc4101af..0f5ffd04 100644 --- a/frameworks/include/background_task_subscriber_proxy.h +++ b/frameworks/include/background_task_subscriber_proxy.h @@ -29,8 +29,12 @@ public: ~BackgroundTaskSubscriberProxy() override; DISALLOW_COPY_AND_MOVE(BackgroundTaskSubscriberProxy); + void OnConnected() override; + void OnDisconnected() override; void OnTransientTaskStart(const std::shared_ptr& info) override; void OnTransientTaskEnd(const std::shared_ptr& info) override; + void OnContinuousTaskStart(const sptr &continuousTaskCallbackInfo) override; + void OnContinuousTaskStop(const sptr &continuousTaskCallbackInfo) override; private: static inline BrokerDelegator delegator_; diff --git a/frameworks/include/background_task_subscriber_stub.h b/frameworks/include/background_task_subscriber_stub.h index dac0d283..a72025c9 100644 --- a/frameworks/include/background_task_subscriber_stub.h +++ b/frameworks/include/background_task_subscriber_stub.h @@ -18,6 +18,7 @@ #include +#include "bgtaskmgr_inner_errors.h" #include "ibackground_task_subscriber.h" namespace OHOS { @@ -30,8 +31,12 @@ public: int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; private: - int32_t HandleOnTransientTaskStart(MessageParcel& data); - int32_t HandleOnTransientTaskEnd(MessageParcel& data); + ErrCode HandleOnConnected(MessageParcel &data); + ErrCode HandleOnDisconnected(MessageParcel &data); + ErrCode HandleOnTransientTaskStart(MessageParcel& data); + ErrCode HandleOnTransientTaskEnd(MessageParcel& data); + ErrCode HandleOnContinuousTaskStart(MessageParcel &data); + ErrCode HandleOnContinuousTaskCancel(MessageParcel &data); }; } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/frameworks/include/ibackground_task_mgr.h b/frameworks/include/ibackground_task_mgr.h index d1ef00a8..256f9cf9 100644 --- a/frameworks/include/ibackground_task_mgr.h +++ b/frameworks/include/ibackground_task_mgr.h @@ -23,9 +23,11 @@ #include #include "bgtaskmgr_inner_errors.h" +#include "continuous_task_param.h" #include "delay_suspend_info.h" #include "iexpired_callback.h" #include "ibackground_task_subscriber.h" +#include "want_agent.h" namespace OHOS { namespace BackgroundTaskMgr { @@ -39,6 +41,8 @@ public: const sptr& callback, std::shared_ptr &delayInfo) = 0; virtual ErrCode CancelSuspendDelay(int32_t requestId) = 0; virtual ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) = 0; + virtual ErrCode StartBackgroundRunning(const sptr taskParam) = 0; + virtual ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken) = 0; virtual ErrCode SubscribeBackgroundTask(const sptr& subscriber) = 0; virtual ErrCode UnsubscribeBackgroundTask(const sptr& subscriber) = 0; virtual ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) = 0; @@ -51,6 +55,8 @@ protected: REQUEST_SUSPEND_DELAY = MIN_TRANSACTION_ID, CANCEL_SUSPEND_DELAY, GET_REMAINING_DELAY_TIME, + START_BACKGROUND_RUNNING, + STOP_BACKGROUND_RUNNING, SUBSCRIBE_BACKGROUND_TASK, UNSUBSCRIBE_BACKGROUND_TASK, SHELL_DUMP, diff --git a/frameworks/include/ibackground_task_subscriber.h b/frameworks/include/ibackground_task_subscriber.h index 60348ab6..265e376b 100644 --- a/frameworks/include/ibackground_task_subscriber.h +++ b/frameworks/include/ibackground_task_subscriber.h @@ -20,6 +20,7 @@ #include #include +#include "continuous_task_callback_info.h" #include "transient_task_app_info.h" namespace OHOS { @@ -30,15 +31,23 @@ public: ~IBackgroundTaskSubscriber() override = default; DISALLOW_COPY_AND_MOVE(IBackgroundTaskSubscriber); + virtual void OnConnected() = 0; + virtual void OnDisconnected() = 0; virtual void OnTransientTaskStart(const std::shared_ptr& info) = 0; virtual void OnTransientTaskEnd(const std::shared_ptr& info) = 0; + virtual void OnContinuousTaskStart(const sptr &continuousTaskCallbackInfo) = 0; + virtual void OnContinuousTaskStop(const sptr &continuousTaskCallbackInfo) = 0; public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.resourceschedule.IBackgroundTaskSubscriber"); protected: enum InterfaceId : uint32_t { - ON_TRANSIENT_TASK_START = FIRST_CALL_TRANSACTION, - ON_TRANSIENT_TASK_END + ON_CONNECTED = FIRST_CALL_TRANSACTION, + ON_DISCONNECTED, + ON_TRANSIENT_TASK_START, + ON_TRANSIENT_TASK_END, + ON_CONTINUOUS_TASK_START, + ON_CONTINUOUS_TASK_STOP, }; }; } // namespace BackgroundTaskMgr diff --git a/frameworks/src/background_task_manager.cpp b/frameworks/src/background_task_manager.cpp index 5066e3a0..ded9427f 100644 --- a/frameworks/src/background_task_manager.cpp +++ b/frameworks/src/background_task_manager.cpp @@ -62,6 +62,35 @@ ErrCode BackgroundTaskManager::GetRemainingDelayTime(int32_t requestId, int32_t return backgroundTaskMgrProxy_->GetRemainingDelayTime(requestId, delayTime); } +ErrCode BackgroundTaskManager::RequestStartBackgroundRunning(const ContinuousTaskParam &taskParam) +{ + BGTASK_LOGI("begin"); + if (!GetBackgroundTaskManagerProxy()) { + BGTASK_LOGE("GetBackgroundTaskManagerProxy failed."); + return ERR_BGTASK_SERVICE_NOT_CONNECTED; + } + + sptr taskParamPtr = new (std::nothrow) ContinuousTaskParam(taskParam); + if (taskParamPtr == nullptr) { + BGTASK_LOGE("Failed to create continuous task param"); + return ERR_BGTASK_NO_MEMORY; + } + BGTASK_LOGI("end"); + return backgroundTaskMgrProxy_->StartBackgroundRunning(taskParamPtr); +} + +ErrCode BackgroundTaskManager::RequestStopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + BGTASK_LOGI("begin"); + if (!GetBackgroundTaskManagerProxy()) { + BGTASK_LOGE("GetBackgroundTaskManagerProxy failed."); + return ERR_BGTASK_SERVICE_NOT_CONNECTED; + } + BGTASK_LOGI("end"); + return backgroundTaskMgrProxy_->StopBackgroundRunning(abilityName, abilityToken); +} + ErrCode BackgroundTaskManager::SubscribeBackgroundTask(const BackgroundTaskSubscriber &subscriber) { if (!GetBackgroundTaskManagerProxy()) { diff --git a/frameworks/src/background_task_mgr_proxy.cpp b/frameworks/src/background_task_mgr_proxy.cpp index 5c7ef321..deead535 100644 --- a/frameworks/src/background_task_mgr_proxy.cpp +++ b/frameworks/src/background_task_mgr_proxy.cpp @@ -125,6 +125,72 @@ ErrCode BackgroundTaskMgrProxy::GetRemainingDelayTime(int32_t requestId, int32_t return result; } +ErrCode BackgroundTaskMgrProxy::StartBackgroundRunning(const sptr taskParam) +{ + BGTASK_LOGI("begin"); + if (taskParam == nullptr) { + return ERR_BGTASK_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(taskParam)) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + + ErrCode result = InnerTransact(START_BACKGROUND_RUNNING, option, data, reply); + if (result != ERR_OK) { + BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + return ERR_BGTASK_TRANSACT_FAILED; + } + if (!reply.ReadInt32(result)) { + BGTASK_LOGI("fail: read result failed."); + return ERR_BGTASK_PARCELABLE_FAILED; + } + BGTASK_LOGI("end"); + return result; +} + +ErrCode BackgroundTaskMgrProxy::StopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + BGTASK_LOGI("begin"); + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + + if (!data.WriteString(abilityName)) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(abilityToken)) { + BGTASK_LOGE("parcel ability token failed"); + return ERR_BGTASK_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + + ErrCode result = InnerTransact(STOP_BACKGROUND_RUNNING, option, data, reply); + if (result != ERR_OK) { + BGTASK_LOGE("[StopBackgroundRunning] fail: transact ErrCode=%{public}d", result); + return ERR_BGTASK_TRANSACT_FAILED; + } + if (!reply.ReadInt32(result)) { + BGTASK_LOGE("[StopBackgroundRunning] fail: read result failed."); + return ERR_BGTASK_PARCELABLE_FAILED; + } + BGTASK_LOGI("end"); + return result; +} + ErrCode BackgroundTaskMgrProxy::SubscribeBackgroundTask(const sptr& subscriber) { if (subscriber == nullptr) { diff --git a/frameworks/src/background_task_mgr_stub.cpp b/frameworks/src/background_task_mgr_stub.cpp index b48904f9..1b4bef13 100644 --- a/frameworks/src/background_task_mgr_stub.cpp +++ b/frameworks/src/background_task_mgr_stub.cpp @@ -37,6 +37,12 @@ const std::map taskParam = data.ReadParcelable(); + if (taskParam == nullptr) { + BGTASK_LOGE("ContinuousTaskParam ReadParcelable failed"); + return ERR_BGTASK_PARCELABLE_FAILED; + } + ErrCode result = StartBackgroundRunning(taskParam); + if (!reply.WriteInt32(result)) { + BGTASK_LOGE("write result failed, ErrCode=%{public}d", result); + return ERR_BGTASK_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode BackgroundTaskMgrStub::HandleStopBackgroundRunning(MessageParcel &data, MessageParcel &reply) +{ + std::string abilityName; + if (!data.ReadString(abilityName)) { + return ERR_BGTASK_PARCELABLE_FAILED; + } + sptr abilityToken = data.ReadParcelable(); + ErrCode result = StopBackgroundRunning(abilityName, abilityToken); + if (!reply.WriteInt32(result)) { + BGTASK_LOGE("write result failed, ErrCode=%{public}d", result); + return ERR_BGTASK_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode BackgroundTaskMgrStub::HandleSubscribeBackgroundTask(MessageParcel& data, MessageParcel& reply) { sptr subscriber = data.ReadRemoteObject(); diff --git a/frameworks/src/background_task_subscriber_proxy.cpp b/frameworks/src/background_task_subscriber_proxy.cpp index cdd0a363..1e2d253f 100644 --- a/frameworks/src/background_task_subscriber_proxy.cpp +++ b/frameworks/src/background_task_subscriber_proxy.cpp @@ -25,6 +25,50 @@ BackgroundTaskSubscriberProxy::BackgroundTaskSubscriberProxy(const sptr(impl) {} BackgroundTaskSubscriberProxy::~BackgroundTaskSubscriberProxy() {} +void BackgroundTaskSubscriberProxy::OnConnected() +{ + sptr remote = Remote(); + if (remote == nullptr) { + BGTASK_LOGE("remote is dead."); + return; + } + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { + BGTASK_LOGE("[OnConnected] fail: write interface token failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode ret = remote->SendRequest(ON_CONNECTED, data, reply, option); + if (ret!= ERR_OK) { + BGTASK_LOGE("SendRequest failed, error code: %d", ret); + return; + } +} + +void BackgroundTaskSubscriberProxy::OnDisconnected() +{ + sptr remote = Remote(); + if (remote == nullptr) { + BGTASK_LOGE("remote is dead."); + return; + } + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { + BGTASK_LOGE("[OnDisconnected] fail: write interface token failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode ret = remote->SendRequest(ON_DISCONNECTED, data, reply, option); + if (ret != ERR_OK) { + BGTASK_LOGE("SendRequest failed, error code: %d", ret); + return; + } +} + void BackgroundTaskSubscriberProxy::OnTransientTaskStart(const std::shared_ptr& info) { sptr remote = Remote(); @@ -78,5 +122,75 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskEnd(const std::shared_ptr &continuousTaskCallbackInfo) +{ + BGTASK_LOGI("begin"); + sptr remote = Remote(); + if (remote == nullptr) { + BGTASK_LOGE("remote is dead."); + return; + } + if (continuousTaskCallbackInfo == nullptr) { + BGTASK_LOGE("continuousTaskCallbackInfo is nullptr."); + return; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { + BGTASK_LOGE("write interface token failed."); + return; + } + + if (!data.WriteParcelable(continuousTaskCallbackInfo)) { + BGTASK_LOGI("write continuousTaskCallbackInfo failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = remote->SendRequest(ON_CONTINUOUS_TASK_START, data, reply, option); + if (result != ERR_OK) { + BGTASK_LOGE("SendRequest error"); + return; + } + BGTASK_LOGI("end"); +} + +void BackgroundTaskSubscriberProxy::OnContinuousTaskStop( + const sptr &continuousTaskCallbackInfo) +{ + BGTASK_LOGI("begin"); + sptr remote = Remote(); + if (remote == nullptr) { + BGTASK_LOGE("remote is dead."); + return; + } + if (continuousTaskCallbackInfo == nullptr) { + BGTASK_LOGE("continuousTaskCallbackInfo is nullptr."); + return; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { + BGTASK_LOGE("write interface token failed."); + return; + } + + if (!data.WriteParcelable(continuousTaskCallbackInfo)) { + BGTASK_LOGE("write notification failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = remote->SendRequest(ON_CONTINUOUS_TASK_STOP, data, reply, option); + if (result != ERR_OK) { + BGTASK_LOGE("SendRequest error"); + return; + } + BGTASK_LOGI("end"); +} } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/frameworks/src/background_task_subscriber_stub.cpp b/frameworks/src/background_task_subscriber_stub.cpp index c92ad604..13aa9c45 100644 --- a/frameworks/src/background_task_subscriber_stub.cpp +++ b/frameworks/src/background_task_subscriber_stub.cpp @@ -47,18 +47,42 @@ int BackgroundTaskSubscriberStub::OnRemoteRequest(uint32_t code, } switch (code) { + case ON_CONNECTED: { + return HandleOnConnected(data); + } + case ON_DISCONNECTED: { + return HandleOnDisconnected(data); + } case ON_TRANSIENT_TASK_START: { return HandleOnTransientTaskStart(data); } case ON_TRANSIENT_TASK_END: { return HandleOnTransientTaskEnd(data); } + case ON_CONTINUOUS_TASK_START: { + return HandleOnContinuousTaskStart(data); + } + case ON_CONTINUOUS_TASK_STOP: { + return HandleOnContinuousTaskCancel(data); + } default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } } -int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskStart(MessageParcel& data) +ErrCode BackgroundTaskSubscriberStub::HandleOnConnected(MessageParcel &data) +{ + OnConnected(); + return ERR_OK; +} + +ErrCode BackgroundTaskSubscriberStub::HandleOnDisconnected(MessageParcel &data) +{ + OnDisconnected(); + return ERR_OK; +} + +ErrCode BackgroundTaskSubscriberStub::HandleOnTransientTaskStart(MessageParcel& data) { auto info = TransientTaskAppInfo::Unmarshalling(data); if (info == nullptr) { @@ -69,7 +93,7 @@ int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskStart(MessageParcel& return ERR_NONE; } -int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskEnd(MessageParcel& data) +ErrCode BackgroundTaskSubscriberStub::HandleOnTransientTaskEnd(MessageParcel& data) { auto info = TransientTaskAppInfo::Unmarshalling(data); if (info == nullptr) { @@ -79,5 +103,33 @@ int32_t BackgroundTaskSubscriberStub::HandleOnTransientTaskEnd(MessageParcel& da OnTransientTaskEnd(info); return ERR_NONE; } + +ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskStart(MessageParcel &data) +{ + BGTASK_LOGI("begin"); + sptr continuousTaskCallbackInfo = data.ReadParcelable(); + if (!continuousTaskCallbackInfo) { + BGTASK_LOGE("ContinuousTaskCallbackInfo ReadParcelable failed"); + return ERR_BGTASK_PARCELABLE_FAILED; + } + + OnContinuousTaskStart(continuousTaskCallbackInfo); + BGTASK_LOGI("end"); + return ERR_OK; +} + +ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskCancel(MessageParcel &data) +{ + BGTASK_LOGI("begin"); + sptr continuousTaskCallbackInfo = data.ReadParcelable(); + if (!continuousTaskCallbackInfo) { + BGTASK_LOGE("ContinuousTaskCallbackInfo ReadParcelable failed"); + return ERR_BGTASK_PARCELABLE_FAILED; + } + + OnContinuousTaskStop(continuousTaskCallbackInfo); + BGTASK_LOGI("end"); + return ERR_OK; +} } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index c5215865..d8643ec8 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos.gni") import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") -config("bgtaskmgr_public_config") { +config("bgtaskmgr_innerkits_public_config") { include_dirs = [ "include" ] } @@ -22,16 +22,26 @@ ohos_shared_library("bgtaskmgr_innerkits") { sources = [ "src/background_task_mgr_helper.cpp", "src/background_task_subscriber.cpp", + "src/continuous_task_callback_info.cpp", + "src/continuous_task_param.cpp", "src/delay_suspend_info.cpp", "src/expired_callback.cpp", "src/transient_task_app_info.cpp", ] - public_configs = [ ":bgtaskmgr_public_config" ] + public_configs = [ + ":bgtaskmgr_innerkits_public_config", + "//foundation/resourceschedule/background_task_mgr/frameworks:bgtaskmgr_public_config", + ] - deps = [ "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk" ] + public_deps = [ + "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + ] external_deps = [ + "ability_runtime:want", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/interfaces/innerkits/include/background_mode.h b/interfaces/innerkits/include/background_mode.h new file mode 100644 index 00000000..eaeb3051 --- /dev/null +++ b/interfaces/innerkits/include/background_mode.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_BACKGROUND_MODE_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_BACKGROUND_MODE_H + +namespace OHOS { +namespace BackgroundTaskMgr { +class BackgroundMode { +public: + virtual ~BackgroundMode() = default; + enum Type : uint32_t { + DATA_TRANSFER = 1, + AUDIO_PLAYBACK, + AUDIO_RECORDING, + LOCATION, + BLUETOOTH_INTERACTION, + MULTI_DEVICE_CONNECTION, + WIFI_INTERACTION, + VOIP, + TASK_KEEPING, + }; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/innerkits/include/background_task_mgr_helper.h b/interfaces/innerkits/include/background_task_mgr_helper.h index 036369bd..55b4a877 100644 --- a/interfaces/innerkits/include/background_task_mgr_helper.h +++ b/interfaces/innerkits/include/background_task_mgr_helper.h @@ -22,6 +22,24 @@ namespace OHOS { namespace BackgroundTaskMgr { class BackgroundTaskMgrHelper { public: + /** + * request service to keep running background + * + * @param taskParam request params. + * @return Returns ERR_OK on success, others on failure. + */ + static ErrCode RequestStartBackgroundRunning(const ContinuousTaskParam &taskParam); + + /** + * request service to stop running background + * + * @param abilityName ability name of the requester ability + * @param abilityToken ability token to mark an unique running ability instance + * @return Returns ERR_OK on success, others on failure. + */ + static ErrCode RequestStopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken); + /** * Subscribes background task event. * diff --git a/interfaces/innerkits/include/background_task_subscriber.h b/interfaces/innerkits/include/background_task_subscriber.h index 8a885575..701f7407 100644 --- a/interfaces/innerkits/include/background_task_subscriber.h +++ b/interfaces/innerkits/include/background_task_subscriber.h @@ -35,37 +35,87 @@ public: */ virtual ~BackgroundTaskSubscriber(); + /** + * Called back when the subscriber is connected to Background Task Manager Service. + */ + virtual void OnConnected(); + + /** + * Called back when the subscriber is disconnected from Background Task Manager Service. + */ + virtual void OnDisconnected(); + /** * Called back when a transient task start. * * @param info Transient task app info. **/ - virtual void OnTransientTaskStart(const std::shared_ptr& info) = 0; + virtual void OnTransientTaskStart(const std::shared_ptr& info); /** * Called back when a transient task end. * * @param info Transient task app info. **/ - virtual void OnTransientTaskEnd(const std::shared_ptr& info) = 0; + virtual void OnTransientTaskEnd(const std::shared_ptr& info); + + /** + * Called back when a continuous task start. + * + * @param info Transient task app info. + **/ + virtual void OnContinuousTaskStart(const std::shared_ptr &continuousTaskCallbackInfo); + + /** + * Called back when a continuous task end. + * + * @param info Transient task app info. + **/ + virtual void OnContinuousTaskStop(const std::shared_ptr &continuousTaskCallbackInfo); + + /** + * Called back when the Background Task Manager Service has died. + */ + virtual void OnRemoteDied(const wptr &object); private: class BackgroundTaskSubscriberImpl final : public BackgroundTaskSubscriberStub { + public: + class DeathRecipient final : public IRemoteObject::DeathRecipient { + public: + DeathRecipient(BackgroundTaskSubscriberImpl &subscriberImpl); + + ~DeathRecipient(); + + void OnRemoteDied(const wptr &object) override; + + private: + BackgroundTaskSubscriberImpl &subscriberImpl_; + }; + public: BackgroundTaskSubscriberImpl(BackgroundTaskSubscriber &subscriber); ~BackgroundTaskSubscriberImpl() {}; + void OnConnected() override; + void OnDisconnected() override; void OnTransientTaskStart(const std::shared_ptr& info) override; void OnTransientTaskEnd(const std::shared_ptr& info) override; + void OnContinuousTaskStart(const sptr &continuousTaskCallbackInfo) override; + void OnContinuousTaskStop(const sptr &continuousTaskCallbackInfo) override; + bool GetBackgroundTaskMgrProxy(); public: BackgroundTaskSubscriber &subscriber_; + sptr recipient_ {nullptr}; + sptr proxy_ {nullptr}; + std::mutex mutex_ {}; }; private: const sptr GetImpl() const; private: - sptr impl_ = nullptr; + sptr impl_ {nullptr}; friend class BackgroundTaskManager; }; diff --git a/interfaces/innerkits/include/continuous_task_callback_info.h b/interfaces/innerkits/include/continuous_task_callback_info.h new file mode 100644 index 00000000..da802a89 --- /dev/null +++ b/interfaces/innerkits/include/continuous_task_callback_info.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_LONGTIME_TASK_EVENT_DATA_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_LONGTIME_TASK_EVENT_DATA_H + +#include + +#include "parcel.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class ContinuousTaskCallbackInfo : public Parcelable { +public: + ContinuousTaskCallbackInfo(); + ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, pid_t creatorPid, std::string abilityName); + + int32_t GetTypeId(); + uid_t GetCreatorUid(); + pid_t GetCreatorPid(); + std::string GetAbilityName(); + bool Marshalling(Parcel &parcel) const; + static ContinuousTaskCallbackInfo *Unmarshalling(Parcel &parcel); + +private: + bool ReadFromParcel(Parcel &parcel); + +private: + int32_t typeId_ ; + uid_t creatorUid_ ; + pid_t creatorPid_ ; + std::string abilityName_ ; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/innerkits/include/continuous_task_param.h b/interfaces/innerkits/include/continuous_task_param.h new file mode 100644 index 00000000..7b68b9f2 --- /dev/null +++ b/interfaces/innerkits/include/continuous_task_param.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_CONTINUOUS_TASK_PARAMS_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_CONTINUOUS_TASK_PARAMS_H + +#include "iremote_object.h" +#include "parcel.h" +#include "want_agent.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +struct ContinuousTaskParam : public Parcelable { + bool isNewApi_ {false}; + uint32_t bgModeId_ {0}; + std::shared_ptr wantAgent_ {nullptr}; + std::string abilityName_ {""}; + sptr abilityToken_ {nullptr}; + + ContinuousTaskParam() = default; + ContinuousTaskParam(bool isNewApi, uint32_t bgModeId, + const std::shared_ptr wantAgent, const std::string abilityName, + const sptr abilityToken) + : isNewApi_(isNewApi), bgModeId_(bgModeId), wantAgent_(wantAgent), + abilityName_(abilityName), abilityToken_(abilityToken) {} + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static ContinuousTaskParam *Unmarshalling(Parcel &parcel); +}; +} +} + +#endif \ No newline at end of file diff --git a/interfaces/innerkits/src/background_task_mgr_helper.cpp b/interfaces/innerkits/src/background_task_mgr_helper.cpp index 5b57143d..0a98d27a 100644 --- a/interfaces/innerkits/src/background_task_mgr_helper.cpp +++ b/interfaces/innerkits/src/background_task_mgr_helper.cpp @@ -22,6 +22,17 @@ namespace OHOS { namespace BackgroundTaskMgr { +ErrCode BackgroundTaskMgrHelper::RequestStartBackgroundRunning(const ContinuousTaskParam &taskParam) +{ + return DelayedSingleton::GetInstance()->RequestStartBackgroundRunning(taskParam); +} + +ErrCode BackgroundTaskMgrHelper::RequestStopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + return DelayedSingleton::GetInstance()-> + RequestStopBackgroundRunning(abilityName, abilityToken); +} ErrCode BackgroundTaskMgrHelper::SubscribeBackgroundTask(const BackgroundTaskSubscriber &subscriber) { return DelayedSingleton::GetInstance()->SubscribeBackgroundTask(subscriber); diff --git a/interfaces/innerkits/src/background_task_subscriber.cpp b/interfaces/innerkits/src/background_task_subscriber.cpp index f982f16b..b0c2459f 100644 --- a/interfaces/innerkits/src/background_task_subscriber.cpp +++ b/interfaces/innerkits/src/background_task_subscriber.cpp @@ -15,6 +15,9 @@ #include "background_task_subscriber.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + namespace OHOS { namespace BackgroundTaskMgr { BackgroundTaskSubscriber::BackgroundTaskSubscriber() @@ -25,13 +28,55 @@ BackgroundTaskSubscriber::BackgroundTaskSubscriber() BackgroundTaskSubscriber::~BackgroundTaskSubscriber() {} +void BackgroundTaskSubscriber::OnConnected() +{} + +void BackgroundTaskSubscriber::OnDisconnected() +{} + +void BackgroundTaskSubscriber::OnTransientTaskStart(const std::shared_ptr& info) +{} + +void BackgroundTaskSubscriber::OnTransientTaskEnd(const std::shared_ptr& info) +{} + +void BackgroundTaskSubscriber::OnContinuousTaskStart( + const std::shared_ptr &continuousTaskCallbackInfo) +{} + +void BackgroundTaskSubscriber::OnContinuousTaskStop( + const std::shared_ptr &continuousTaskCallbackInfo) +{} + +void BackgroundTaskSubscriber::OnRemoteDied(const wptr &object) +{} + const sptr BackgroundTaskSubscriber::GetImpl() const { return impl_; } BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::BackgroundTaskSubscriberImpl( - BackgroundTaskSubscriber &subscriber) : subscriber_(subscriber) {} + BackgroundTaskSubscriber &subscriber) : subscriber_(subscriber) +{ + recipient_ = new (std::nothrow) DeathRecipient(*this); +} + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnConnected() +{ + if (GetBackgroundTaskMgrProxy()) { + proxy_->AsObject()->AddDeathRecipient(recipient_); + } + subscriber_.OnConnected(); +} + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnDisconnected() +{ + if (GetBackgroundTaskMgrProxy()) { + proxy_->AsObject()->RemoveDeathRecipient(recipient_); + } + subscriber_.OnDisconnected(); +} void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnTransientTaskStart( const std::shared_ptr& info) @@ -44,5 +89,54 @@ void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnTransientTaskEnd( { subscriber_.OnTransientTaskEnd(info); } + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnContinuousTaskStart( + const sptr &continuousTaskCallbackInfo) +{ + subscriber_.OnContinuousTaskStart(std::make_shared(*continuousTaskCallbackInfo)); +} + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnContinuousTaskStop( + const sptr &continuousTaskCallbackInfo) +{ + subscriber_.OnContinuousTaskStop(std::make_shared(*continuousTaskCallbackInfo)); +} + +bool BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::GetBackgroundTaskMgrProxy() +{ + if (proxy_) { + return true; + } + std::lock_guard lock(mutex_); + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + return false; + } + + sptr remoteObject = + systemAbilityManager->GetSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID); + if (!remoteObject) { + return false; + } + + proxy_ = iface_cast(remoteObject); + if ((!proxy_) || (proxy_->AsObject() == nullptr)) { + return false; + } + return true; +} + +BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::DeathRecipient::DeathRecipient( + BackgroundTaskSubscriberImpl &subscriberImpl) : subscriberImpl_(subscriberImpl) {} + +BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::DeathRecipient::~DeathRecipient() {} + +void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::DeathRecipient::OnRemoteDied( + const wptr &object) +{ + subscriberImpl_.proxy_ = nullptr; + subscriberImpl_.subscriber_.OnRemoteDied(object); +} } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/src/continuous_task_callback_info.cpp b/interfaces/innerkits/src/continuous_task_callback_info.cpp new file mode 100644 index 00000000..15efab7f --- /dev/null +++ b/interfaces/innerkits/src/continuous_task_callback_info.cpp @@ -0,0 +1,98 @@ +/* + * 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 "continuous_task_callback_info.h" +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo() +{} + +ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, + pid_t creatorPid, std::string abilityName) + : typeId_(typeId), creatorUid_(creatorUid), creatorPid_(creatorPid), abilityName_(abilityName) +{} + +int32_t ContinuousTaskCallbackInfo::GetTypeId() +{ + return typeId_; +} + +uid_t ContinuousTaskCallbackInfo::GetCreatorUid() +{ + return creatorUid_; +} + +pid_t ContinuousTaskCallbackInfo::GetCreatorPid() +{ + return creatorPid_; +} + +std::string ContinuousTaskCallbackInfo::GetAbilityName() +{ + return abilityName_; +} + +bool ContinuousTaskCallbackInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(typeId_)) { + BGTASK_LOGE("Failed to write typeId"); + return false; + } + + if (!parcel.WriteInt32(creatorUid_)) { + BGTASK_LOGE("Failed to write creator uid"); + return false; + } + + if (!parcel.WriteInt32(creatorPid_)) { + BGTASK_LOGE("Failed to write creator pid"); + return false; + } + + if (!parcel.WriteString(abilityName_)) { + BGTASK_LOGE("Failed to write ability name"); + return false; + } + return true; +} + +ContinuousTaskCallbackInfo *ContinuousTaskCallbackInfo::Unmarshalling(Parcel &parcel) +{ + auto object = new ContinuousTaskCallbackInfo(); + if ((object != nullptr) && !object->ReadFromParcel(parcel)) { + delete object; + object = nullptr; + } + + return object; +} + +bool ContinuousTaskCallbackInfo::ReadFromParcel(Parcel &parcel) +{ + typeId_ = parcel.ReadInt32(); + + creatorUid_ = static_cast(parcel.ReadInt32()); + creatorPid_ = static_cast(parcel.ReadInt32()); + + if (!parcel.ReadString(abilityName_)) { + BGTASK_LOGE("Failed to read creator ability name"); + return false; + } + return true; +} +} +} \ No newline at end of file diff --git a/interfaces/innerkits/src/continuous_task_param.cpp b/interfaces/innerkits/src/continuous_task_param.cpp new file mode 100644 index 00000000..3ca2ad7a --- /dev/null +++ b/interfaces/innerkits/src/continuous_task_param.cpp @@ -0,0 +1,113 @@ +/* + * 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 "continuous_task_param.h" +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +bool ContinuousTaskParam::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadBool(isNewApi_)) { + BGTASK_LOGE("Failed to read the flag which indicate whether is called from newApi"); + return false; + } + + if (!parcel.ReadUint32(bgModeId_)) { + BGTASK_LOGE("Failed to read request background mode info"); + return false; + } + bool valid = false; + valid = parcel.ReadBool(); + if (valid) { + wantAgent_ = std::shared_ptr( + parcel.ReadParcelable()); + if (!wantAgent_) { + BGTASK_LOGE("Failed to read wantAgent"); + return false; + } + } + + if (!parcel.ReadString(abilityName_)) { + BGTASK_LOGE("Failed to read ability name"); + return false; + } + valid = parcel.ReadBool(); + if (valid) { + abilityToken_ = parcel.ReadParcelable(); + if (!abilityToken_) { + BGTASK_LOGE("Failed to read ablityToken"); + return false; + } + } + + return true; +} + +ContinuousTaskParam *ContinuousTaskParam::Unmarshalling(Parcel &parcel) +{ + ContinuousTaskParam *param = new (std::nothrow) ContinuousTaskParam(); + if (param && !param->ReadFromParcel(parcel)) { + BGTASK_LOGE("read from parcel failed"); + delete param; + param = nullptr; + } + return param; +} + +bool ContinuousTaskParam::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteBool(isNewApi_)) { + BGTASK_LOGE("Failed to write the flag which indicate whether is called from newApi"); + return false; + } + + if (!parcel.WriteUint32(bgModeId_)) { + BGTASK_LOGE("Failed to write request background mode info"); + return false; + } + bool valid = false; + valid = wantAgent_ ? true : false; + if (!parcel.WriteBool(valid)) { + BGTASK_LOGE("Failed to write the flag which indicate whether wantAgent is null"); + return false; + } + if (valid) { + if (!parcel.WriteParcelable(wantAgent_.get())) { + BGTASK_LOGE("Failed to write wantAgent"); + return false; + } + } + + if (!parcel.WriteString(abilityName_)) { + BGTASK_LOGE("Failed to write abilityName"); + return false; + } + + valid = abilityToken_ ? true : false; + if (!parcel.WriteBool(valid)) { + BGTASK_LOGE("Failed to write the flag which indicate whether ability token is null"); + return false; + } + if (valid) { + if (!parcel.WriteParcelable(abilityToken_)) { + BGTASK_LOGE("parcel ability token failed"); + return false; + } + } + return true; +} +} +} \ No newline at end of file diff --git a/interfaces/kits/BUILD.gn b/interfaces/kits/BUILD.gn index 3ce19273..53fc2ef4 100644 --- a/interfaces/kits/BUILD.gn +++ b/interfaces/kits/BUILD.gn @@ -22,6 +22,7 @@ config("bgtaskmgr_public_config") { ohos_shared_library("backgroundtaskmanager") { sources = [ + "napi/src/bg_continuous_task_napi_module.cpp", "napi/src/cancel_suspend_delay.cpp", "napi/src/common.cpp", "napi/src/get_remaining_delay_time.cpp", @@ -34,9 +35,14 @@ ohos_shared_library("backgroundtaskmanager") { deps = [ "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", ] external_deps = [ + "ability_runtime:abilitykit_native", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", diff --git a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts index cbe6ae70..fd8692f5 100644 --- a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts +++ b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts @@ -14,6 +14,8 @@ */ import { AsyncCallback , Callback} from './basic'; +import { WantAgent } from "./@ohos.wantAgent"; +import { Context } from './app/context'; /** * Manages background tasks. @@ -70,6 +72,113 @@ declare namespace backgroundTaskManager { * @return Info of delay request */ function requestSuspendDelay(reason: string, callback: Callback): DelaySuspendInfo; + + /** + * Service ability uses this method to request start running in background. + * system will publish a notification related to the this service. + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + * @permission ohos.permission.KEEP_BACKGROUND_RUNNING + * @param context app running context. + * @param bgMode Indicates which background mode to request. + * @param wantAgent Indicates which ability to start when user click the notification bar. + */ + function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void; + function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise; + + /** + * Service ability uses this method to request stop running in background. + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + * @param context app running context. + */ + function stopBackgroundRunning(context: Context, callback: AsyncCallback): void; + function stopBackgroundRunning(context: Context): Promise; + + /** + * supported background mode. + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + export enum BackgroundMode { + /** + * data transfer mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + DATA_TRANSFER = 1, + + /** + * audio playback mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + AUDIO_PLAYBACK = 2, + + /** + * audio recording mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + AUDIO_RECORDING = 3, + + /** + * location mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + LOCATION = 4, + + /** + * bluetooth interaction mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + BLUETOOTH_INTERACTION = 5, + + /** + * multi-device connection mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + MULTI_DEVICE_CONNECTION = 6, + + /** + * wifi interaction mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + * @systemapi Hide this for inner system use. + */ + WIFI_INTERACTION = 7, + + /** + * Voice over Internet Phone mode + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + * @systemapi Hide this for inner system use. + */ + VOIP = 8, + + /** + * backgroud continuous calculate mode, for example 3d render. + * only supported in portable computer + * + * @since 8 + * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + */ + TASK_KEEPING = 9, + } } export default backgroundTaskManager; diff --git a/interfaces/kits/napi/include/bg_continuous_task_napi_module.h b/interfaces/kits/napi/include/bg_continuous_task_napi_module.h new file mode 100644 index 00000000..a7d35047 --- /dev/null +++ b/interfaces/kits/napi/include/bg_continuous_task_napi_module.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_BG_CONTINUOUS_TASK_NAPI_MODULE_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_BG_CONTINUOUS_TASK_NAPI_MODULE_H + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace BackgroundTaskMgr { + napi_value StartBackgroundRunning(napi_env env, napi_callback_info info); + napi_value StopBackgroundRunning(napi_env env, napi_callback_info info); +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_KITS_NAPI_INCLUDE_CANCEL_SUSPEND_DELAY_H \ No newline at end of file diff --git a/interfaces/kits/napi/include/init.h b/interfaces/kits/napi/include/init.h index 435dccc6..876eddca 100644 --- a/interfaces/kits/napi/include/init.h +++ b/interfaces/kits/napi/include/init.h @@ -26,7 +26,9 @@ extern "C" { #endif __attribute__((constructor)) void RegisterModule(void); +void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const char *propName); napi_value BackgroundTaskMgrInit(napi_env env, napi_value exports); +napi_value BackgroundModeInit(napi_env env, napi_value exports); static napi_value Init(napi_env env, napi_value exports); #ifdef __cplusplus diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp new file mode 100644 index 00000000..630d32b5 --- /dev/null +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -0,0 +1,458 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bg_continuous_task_napi_module.h" +#include "bgtaskmgr_inner_errors.h" +#include "continuous_task_log.h" +#include "background_mode.h" +#include "continuous_task_param.h" +#include "ability.h" +#include "background_task_mgr_helper.h" +#include "fcntl.h" +#include "want_agent.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static constexpr uint32_t MAX_START_BG_RUNNING_PARAMS = 4; +static constexpr uint32_t MAX_STOP_BG_RUNNING_PARAMS = 2; +static constexpr uint32_t CALLBACK_RESULT_PARAMS_NUM = 2; +static constexpr int32_t BG_MODE_ID_BEGIN = 1; +static constexpr int32_t BG_MODE_ID_END = 9; +} + +struct AsyncCallbackInfo { + napi_env env {nullptr}; + napi_ref callback {nullptr}; + napi_async_work asyncWork {nullptr}; + napi_deferred deferred {nullptr}; + AppExecFwk::Ability *ability {nullptr}; + int32_t bgMode {0}; + Notification::WantAgent::WantAgent *wantAgent {nullptr}; + int errCode {0}; +}; + +napi_value WrapVoidToJS(napi_env env) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value WrapUndefinedToJS(napi_env env) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &result)); + return result; +} + +napi_value GetCallbackErrorValue(napi_env env, int errCode) +{ + napi_value jsObject = nullptr; + napi_value jsValue = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &jsValue)); + NAPI_CALL(env, napi_create_object(env, &jsObject)); + NAPI_CALL(env, napi_set_named_property(env, jsObject, "code", jsValue)); + return jsObject; +} + +AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env) +{ + BGTASK_LOGI("begin"); + if (env == nullptr) { + BGTASK_LOGE("env == nullptr."); + return nullptr; + } + + napi_status ret; + napi_value global = 0; + const napi_extended_error_info *errorInfo = nullptr; + ret = napi_get_global(env, &global); + if (ret != napi_ok) { + napi_get_last_error_info(env, &errorInfo); + BGTASK_LOGE("get_global=%{public}d err:%{public}s", ret, errorInfo->error_message); + } + + napi_value abilityObj = 0; + ret = napi_get_named_property(env, global, "ability", &abilityObj); + if (ret != napi_ok) { + napi_get_last_error_info(env, &errorInfo); + BGTASK_LOGE("get_named_property=%{public}d err:%{public}s", ret, errorInfo->error_message); + } + + OHOS::AppExecFwk::Ability *ability = nullptr; + ret = napi_get_value_external(env, abilityObj, (void **)&ability); + if (ret != napi_ok) { + napi_get_last_error_info(env, &errorInfo); + BGTASK_LOGE("get_value_external=%{public}d err:%{public}s", ret, errorInfo->error_message); + } + + AsyncCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo; + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullptr"); + return nullptr; + } + asyncCallbackInfo->env = env; + asyncCallbackInfo->asyncWork = nullptr; + asyncCallbackInfo->deferred = nullptr; + asyncCallbackInfo->ability = ability; + asyncCallbackInfo->errCode = ERR_OK; + + BGTASK_LOGI("end"); + return asyncCallbackInfo; +} + +void StartBackgroundRunningExecuteCB(napi_env env, void *data) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullptr"); + return; + } + if (asyncCallbackInfo->errCode != ERR_OK) { + BGTASK_LOGE("input params parse failed"); + return; + } + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + BGTASK_LOGE("ability == nullptr"); + return; + } + const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); + if (info == nullptr) { + BGTASK_LOGE("info == nullptr"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; + } + + if (asyncCallbackInfo->wantAgent == nullptr) { + BGTASK_LOGE("wantAgent param is nullptr"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; + } + + if (asyncCallbackInfo->bgMode < BG_MODE_ID_BEGIN || asyncCallbackInfo->bgMode > BG_MODE_ID_END) { + BGTASK_LOGE("request background mode id: %{public}d out of range", asyncCallbackInfo->bgMode); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; + } + + ContinuousTaskParam taskParam = ContinuousTaskParam(true, asyncCallbackInfo->bgMode, + std::make_shared(*asyncCallbackInfo->wantAgent), info->name, nullptr); + asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam); + + BGTASK_LOGI("end"); +} + +void CallbackCompletedCB(napi_env env, napi_status status, void *data) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + napi_value callback = 0; + napi_value undefined = 0; + napi_value result[CALLBACK_RESULT_PARAMS_NUM] = {0}; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + if (asyncCallbackInfo->errCode == ERR_OK) { + result[0] = WrapUndefinedToJS(env); + napi_create_int32(env, 0, &result[1]); + } else { + result[1] = WrapUndefinedToJS(env); + result[0] = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + } + + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_call_function(env, undefined, callback, CALLBACK_RESULT_PARAMS_NUM, result, &callResult); + + if (asyncCallbackInfo->callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + BGTASK_LOGI("end"); +} + +void PromiseCompletedCB(napi_env env, napi_status status, void *data) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + napi_value result = 0; + if (asyncCallbackInfo->errCode == ERR_OK) { + napi_create_int32(env, 0, &result); + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + } else { + result = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + napi_reject_deferred(env, asyncCallbackInfo->deferred, result); + } + + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + BGTASK_LOGI("end"); + delete asyncCallbackInfo; +} + +napi_value StartBackgroundRunningAsync( + napi_env env, napi_value *argv, const size_t argCallback, AsyncCallbackInfo *asyncCallbackInfo) +{ + BGTASK_LOGI("begin"); + if (argv == nullptr || asyncCallbackInfo == nullptr) { + BGTASK_LOGE("param == nullptr"); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[argCallback], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_CALL(env, napi_create_reference(env, argv[argCallback], 1, &asyncCallbackInfo->callback)); + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + StartBackgroundRunningExecuteCB, + CallbackCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + BGTASK_LOGI("end"); + return WrapVoidToJS(env); +} + +napi_value StartBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +{ + BGTASK_LOGI("begin"); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("param == nullptr"); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + StartBackgroundRunningExecuteCB, + PromiseCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + BGTASK_LOGI("end"); + return promise; +} + +napi_value GetBackgroundMode(const napi_env &env, const napi_value &value, int32_t &bgMode) +{ + BGTASK_LOGI("begin"); + + napi_valuetype valuetype = napi_undefined; + + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, value, &bgMode); + + BGTASK_LOGI("get bgmode info: %{public}d", bgMode); + + return WrapVoidToJS(env); +} + +napi_value GetWantAgent(const napi_env &env, const napi_value &value, Notification::WantAgent::WantAgent *&wantAgent) +{ + BGTASK_LOGI("begin"); + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + napi_unwrap(env, value, (void **)&wantAgent); + + BGTASK_LOGI("end"); + return WrapVoidToJS(env); +} + +napi_value StartBackgroundRunning(napi_env env, napi_callback_info info) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullpter"); + return WrapVoidToJS(env); + } + + size_t argc = MAX_START_BG_RUNNING_PARAMS; + napi_value argv[MAX_START_BG_RUNNING_PARAMS] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc > MAX_START_BG_RUNNING_PARAMS) { + BGTASK_LOGE("wrong param nums"); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return nullptr; + } + + // argv[1] : bgMode : BackgroundMode + if (GetBackgroundMode(env, argv[1], asyncCallbackInfo->bgMode) == nullptr) { + BGTASK_LOGE("input bgmode param not number"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + } + + // argv[2] : wantAgent: WantAgent + if (GetWantAgent(env, argv[2], asyncCallbackInfo->wantAgent) == nullptr) { + BGTASK_LOGE("input wantAgent param is not object"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + } + + napi_value ret = 0; + + if (argc == MAX_START_BG_RUNNING_PARAMS) { + ret = StartBackgroundRunningAsync(env, argv, MAX_START_BG_RUNNING_PARAMS - 1, asyncCallbackInfo); + } else { + ret = StartBackgroundRunningPromise(env, asyncCallbackInfo); + } + + if (ret == nullptr) { + BGTASK_LOGE("ret == nullpter"); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + ret = WrapVoidToJS(env); + } + BGTASK_LOGI("end"); + return ret; +} + +void StopBackgroundRunningExecuteCB(napi_env env, void *data) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullptr"); + return; + } + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + BGTASK_LOGE("ability == nullptr"); + return; + } + const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); + if (info == nullptr) { + BGTASK_LOGE("abilityInfo == nullptr"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; + } + asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStopBackgroundRunning(info->name, nullptr); +} + +napi_value StopBackgroundRunningAsync(napi_env env, napi_value *argv, + const size_t argCallback, AsyncCallbackInfo *asyncCallbackInfo) +{ + BGTASK_LOGI("begin"); + if (argv == nullptr || asyncCallbackInfo == nullptr) { + BGTASK_LOGE("param == nullptr"); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, argv[argCallback], 1, &asyncCallbackInfo->callback)); + } + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + StopBackgroundRunningExecuteCB, + CallbackCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + BGTASK_LOGI("end"); + return WrapVoidToJS(env); +} + +napi_value StopBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +{ + BGTASK_LOGI("begin"); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("param == nullptr"); + return nullptr; + } + napi_value resourceName = 0; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_deferred deferred; + napi_value promise = 0; + napi_create_promise(env, &deferred, &promise); + + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work( + env, + nullptr, + resourceName, + StopBackgroundRunningExecuteCB, + PromiseCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + BGTASK_LOGI("end"); + return promise; +} + +napi_value StopBackgroundRunning(napi_env env, napi_callback_info info) +{ + BGTASK_LOGI("begin"); + AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + BGTASK_LOGE("asyncCallbackInfo == nullpter"); + return WrapVoidToJS(env); + } + + size_t argc = MAX_STOP_BG_RUNNING_PARAMS; + napi_value argv[MAX_STOP_BG_RUNNING_PARAMS] = {nullptr}; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc > MAX_STOP_BG_RUNNING_PARAMS) { + BGTASK_LOGE("wrong param nums"); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return nullptr; + } + + napi_value ret = 0; + if (argc == MAX_STOP_BG_RUNNING_PARAMS) { + ret = StopBackgroundRunningAsync(env, argv, MAX_STOP_BG_RUNNING_PARAMS - 1, asyncCallbackInfo); + } else { + ret = StopBackgroundRunningPromise(env, asyncCallbackInfo); + } + + if (ret == nullptr) { + BGTASK_LOGE("ret == nullpter"); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + ret = WrapVoidToJS(env); + } + BGTASK_LOGI("end"); + return ret; +} +} // namespace BackgroundTaskMgr +} \ No newline at end of file diff --git a/interfaces/kits/napi/src/init.cpp b/interfaces/kits/napi/src/init.cpp index 03918a74..5b7c832e 100644 --- a/interfaces/kits/napi/src/init.cpp +++ b/interfaces/kits/napi/src/init.cpp @@ -15,6 +15,8 @@ #include "init.h" +#include "background_mode.h" +#include "bg_continuous_task_napi_module.h" #include "cancel_suspend_delay.h" #include "get_remaining_delay_time.h" #include "request_suspend_delay.h" @@ -31,6 +33,8 @@ napi_value BackgroundTaskMgrInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("requestSuspendDelay", RequestSuspendDelay), DECLARE_NAPI_FUNCTION("cancelSuspendDelay", CancelSuspendDelay), DECLARE_NAPI_FUNCTION("getRemainingDelayTime", GetRemainingDelayTime), + DECLARE_NAPI_FUNCTION("startBackgroundRunning", StartBackgroundRunning), + DECLARE_NAPI_FUNCTION("stopBackgroundRunning", StopBackgroundRunning), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); @@ -38,6 +42,39 @@ napi_value BackgroundTaskMgrInit(napi_env env, napi_value exports) return exports; } +void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const char *propName) +{ + napi_value prop = nullptr; + if (napi_create_int32(env, objName, &prop) == napi_ok) { + napi_set_named_property(env, dstObj, propName, prop); + } +} + +napi_value BackgroundModeInit(napi_env env, napi_value exports) +{ + BGTASK_LOGI("begin"); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::DATA_TRANSFER, "DATA_TRANSFER"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::AUDIO_PLAYBACK, "AUDIO_PLAYBACK"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::AUDIO_RECORDING, "AUDIO_RECORDING"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::LOCATION, "LOCATION"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::BLUETOOTH_INTERACTION, "BLUETOOTH_INTERACTION"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::MULTI_DEVICE_CONNECTION, "MULTI_DEVICE_CONNECTION"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::WIFI_INTERACTION, "WIFI_INTERACTION"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::VOIP, "VOIP"); + SetNamedPropertyByInteger(env, obj, (uint32_t)BackgroundMode::TASK_KEEPING, "TASK_KEEPING"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("BackgroundMode", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + /* * Module export function */ @@ -47,6 +84,7 @@ static napi_value Init(napi_env env, napi_value exports) * Propertise define */ BackgroundTaskMgrInit(env, exports); + BackgroundModeInit(env, exports); return exports; } diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn index a130cd20..40c48381 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/BUILD.gn @@ -14,6 +14,12 @@ import("//build/test.gni") module_output_path = "background_task_mgr/interfaces" +ohos_js_unittest("ContinuousTaskJsTest") { + module_out_path = module_output_path + hap_profile = "./continuous_task_jsunittest/config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" +} + ohos_js_unittest("TransientTaskJsTest") { module_out_path = module_output_path hap_profile = "./transient_task_jsunittest/config.json" @@ -22,5 +28,8 @@ ohos_js_unittest("TransientTaskJsTest") { group("js_unittest") { testonly = true - deps = [ ":TransientTaskJsTest" ] + deps = [ + ":ContinuousTaskJsTest", + ":TransientTaskJsTest", + ] } diff --git a/interfaces/test/unittest/continuous_task_jsunittest/config.json b/interfaces/test/unittest/continuous_task_jsunittest/config.json new file mode 100644 index 00000000..b2980353 --- /dev/null +++ b/interfaces/test/unittest/continuous_task_jsunittest/config.json @@ -0,0 +1,74 @@ +{ + "app": { + "bundleName": "com.continuoustask.test", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 7, + "target": 7 + } + }, + "deviceConfig": {}, + "module": { + "package": "com.continuoustask.test", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [ + { + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "backgroundModes": [ + "dataTransfer" + ], + "name": "com.continuoustask.test.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ], + "defPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } + ] + } + } + \ No newline at end of file diff --git a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js new file mode 100644 index 00000000..c8851ad5 --- /dev/null +++ b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js @@ -0,0 +1,386 @@ +/* + * 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 notification from '@ohos.notification'; +import wantAgent from '@ohos.wantAgent'; +import particleAbility from '@ohos.ability.particleAbility' +import backgroundTaskManager from '@ohos.backgroundTaskManager' +import featureAbility from '@ohos.ability.featureAbility' + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +describe("ContinuousTaskJsTest", function () { + beforeAll(function() { + /* + * @tc.setup: setup invoked before all testcases + */ + console.info('beforeAll called') + }) + + afterAll(function() { + /* + * @tc.teardown: teardown invoked after all testcases + */ + console.info('afterAll called') + }) + + beforeEach(function() { + /* + * @tc.setup: setup invoked before each testcases + */ + console.info('beforeEach called') + }) + + afterEach(function() { + /* + * @tc.teardown: teardown invoked after each testcases + */ + console.info('afterEach called') + particleAbility.cancelBackgroundRunning(); + setTimeout(() => {}, 500); + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()); + setTimeout(() => {}, 500); + }) + + /* + * @tc.name:ContinuousTaskJsTest001 + * @tc.desc:verify new startBackgroundrunning interface promise mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO + */ + it("ContinuousTaskJsTest001", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then(() => { + console.log("ContinuousTaskJsTest001 startBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest001 startBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest002 + * @tc.desc:verify new startBackgroundrunning interface callback mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 + */ + it("ContinuousTaskJsTest002", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest002 startBackgroundRunning failed'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest002 startBackgroundRunning succeed'); + expect(true).assertTrue(); + } + setTimeout(()=>{ + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data, conTaskCallback); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest003 + * @tc.desc:verify old startBackgroundrunning interface promise mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH56K + */ + it("ContinuousTaskJsTest003", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + let basicContent = { + title: "title", + text: "text" + }; + + let notificationContent = { + contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: basicContent + }; + + let request = { + content: notificationContent, + wantAgent: data + } + + let id = 1; + + particleAbility.startBackgroundRunning(id, request).then((data) => { + console.log("ContinuousTaskJsTest003 startBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest003 startBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest004 + * @tc.desc:verify old startBackgroundrunning interface callback mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH6ET + */ + it("ContinuousTaskJsTest004", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest004 startBackgroundRunning failure'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest004 startBackgroundRunning success'); + expect(true).assertTrue(); + } + setTimeout(()=>{ + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + let basicContent = { + title: "title", + text: "text" + }; + + let notificationContent = { + contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: basicContent + }; + + let request = { + content: notificationContent, + wantAgent: data + } + + let id = 1; + + particleAbility.startBackgroundRunning(id, request, conTaskCallback); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest005 + * @tc.desc:verify new api stopBackgroundrunning interface promise mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EM AR000GH6EN AR000GH6EO + */ + it("ContinuousTaskJsTest005", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then((data) => { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then((data) => { + console.log("ContinuousTaskJsTest005 cancelBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest005 cancelBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); + }) + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest006 + * @tc.desc:verify new api stopBackgroundrunning interface callback mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EP AR000GJ9PR AR000GH6G8 + */ + it("ContinuousTaskJsTest006", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest006 startBackgroundRunning failure'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest006 startBackgroundRunning success'); + expect(true).assertTrue(); + } + setTimeout(()=>{ + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then((data) => { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), conTaskCallback); + }) + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest007 + * @tc.desc:verify old api cancelBackgroundrunning interface promise mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K + */ + it("ContinuousTaskJsTest007", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + await wantAgent.getWantAgent(wantAgentInfo).then((data) => { + particleAbility.startBackgroundRunning(data); + setTimeout(()=>{ + }, 500); + }); + + particleAbility.cancelBackgroundRunning().then(() => { + console.log("ContinuousTaskJsTest007 cancelBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch( (err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest007 cancelBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest008 + * @tc.desc:verify old cancelBackgroundrunning interface callback mode work properly + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH6ET + */ + it("ContinuousTaskJsTest008", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest008 startBackgroundRunning failure'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest008 startBackgroundRunning success'); + expect(true).assertTrue(); + } + setTimeout(()=>{ + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + await wantAgent.getWantAgent(wantAgentInfo).then((data) => { + particleAbility.startBackgroundRunning(data); + setTimeout(()=>{ + }, 500); + }); + + particleAbility.cancelBackgroundRunning(conTaskCallback); + }) +}) \ No newline at end of file diff --git a/resources/BUILD.gn b/resources/BUILD.gn new file mode 100644 index 00000000..7cc33240 --- /dev/null +++ b/resources/BUILD.gn @@ -0,0 +1,33 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("bgtaskmgr_resources") { + deps = [ ":backgroundtaskresources_hap" ] +} + +ohos_resources("backgroundtask_res") { + sources = [ "main/resources" ] + hap_profile = "./main/config.json" +} + +ohos_hap("backgroundtaskresources_hap") { + deps = [ ":backgroundtask_res" ] + hap_profile = "./main/config.json" + hap_name = "BackgroundTaskResources" + module_install_dir = "app" + certificate_profile = "./BackgroundTaskResources.p7b" + subsystem_name = "resourceschedule" + part_name = "background_task_mgr" +} diff --git a/resources/BackgroundTaskResources.p7b b/resources/BackgroundTaskResources.p7b new file mode 100644 index 0000000000000000000000000000000000000000..4c50cd1fa2a5f3336d1b57d2d44182893b1aeba2 GIT binary patch literal 3401 zcmcgvYg7|w8YUN@2oV$&WmO<5STXobNC?ncJCo}GlaP=QLgV5jnOsPi3Ar#yTrG`T z>ZNLJ&nm5#qA2Qm>8{!$yIX6!TU~3tRoBzHqN^@vSJ&2dwXLhG-5KN{^yrU0J;(gW zocHF_j#Xh2E+x*q?8$Lnzru+oMdiCTu=hy0x_4vfzp8>DP>-phC}f9Tux#F zi1RN$OyzXM`KS4D{)zd*79tSzP^5^&n+RdK5Gn#iKsa*{wo?uUhGq(JzhC6=1VaIj zEgWJegra_S0u^lVkRieqz*&@;84i0K3@!y?nXRmh5J{cPpQJ?U5S2+msR%D408}h- zIti$heGcyPI6R@KuzbFdq(UMa;iLlW6H6qLVwo5!W**JrxHCiqSXd@41EmbSV5V?@ zL4fcPc#vRjW($)JA0hIPPKv#sgJ>aql%EKQ`WaDfDmVx+*~3<2Cjudl(__a&?4m^M z4^gU7ZLVBtFrq3{4jYyIsFlP}RIYB6%VAvZf@u_iT_{RG&1fhbDN!{6TJEx-l~g?% zYXnM|#%N1SS%tw~H4K@Qh#QkzNj;E6R0_BTacOH2m@>*i8C`FdqL#XfkWDO=Vg@g* zqAiMAy}n8rL8|TQ+Hj3p6}6em!bA;XvXb>?RS2uWXjI>yrBFuvKh8qz8YGCDwQh&n z*JAS^3cV2~R5XZUMkURx!f2v(Ml6ac5S&3{EQ%SiK@3xtM&w3V^MIqp2rHBo7;Nuf zg&e_P<_>xTxm#4m{bf0yE@{xh*bb*)`h9Ow34=H z26j#k>j!sH0qgAwy$e>V>trRevf_ZM3b#152x=usuLYv0I;lE{fm*T26spj~sFFx9 z(xi0Iphg@m4eF87Vys?mj%mX&*c6;)u6N3VDj2Q6ER|6!X(p>>v1V-zrh;h=yPF1} zLlBEnr4z^0GL248k*Z3+E@lh^HE=~~6t$ojEMfP-p`ewBm7GQEnL48ymjZUOyQQhY zlxhWRb|FTaJ7D*yLZ&Lp6fQ2Vsg;GDN|h5wLxvb!iMU+NZf~Q`N>=Oj3YgYXumbVH zjfmP2sjZTc9-X?en21Cog@p>t8?H8atF30q8C7~~D4!czzm%{0jk`jgADQS`zH1!6R!d>CBd)$Ry646^=jo0P2 zk`*O7g$6K6}fzr4fhqo79zyAbC+$UVn5l{LO#JSIcIOl^79+$)A@?~3_4uG_zrx=$!KAX?u zF;-}YQb9@*&%{s4+3A_oK0`k}) zUS{^tA=vNtvHrpE&y~Yqa+W|00WlCmV&*EX&k{(=AaOA?5CZ>CBmqFt0}=&~BT*fo zoE{&MYk1&~zydOplKZ!T%Nf`Y9w(WHB=F5Axc}(k%brIIZYwC8aC zxogIsUcGSs(qwF#>|5Sv-y9;jg~mBKAN;vPzba+iAK#E1=aI_}jeo1t0IER_Lub+y z{&+C1bF=W&x;!6Y^w$sflba}>Y& z{??fG%!yy^{pIze~svIC+!)%K7&?0 zcklY9_U_BbO2>KUx0klwy0kp0WZwN>uV(2xIIsBI z()?aS_Cbz(+tsOiJEa+s?e~KV`~IH3m(h=c(a(_q{iI(iT{fHxaR0>8O$Yf8N|*Dv z(itc!^dk{L5~y^Di2B1P$fN~iJQPo2;Y<7kAuv}t4&9$lePxH6 zD(ClzQrES-f6Zb!^}^as&&Th)ciO^NFT>RB{?*8qogKG&8txjq(nj{$7q9$WJ*x9% z!G-->Hr;I)dpAF4S)e!f=}G#a1zjjhR)5`zfagIvE0j!DIEjGAT!t%&lQcw0S>+iU zcTD(2UxIGusrG_B?e+A?W5cV*b0q)=7tr-|0d(wpdfRhr)}O80w{mwu*NEjO()O44 zOn$j_hBRi~vT>ql!2!DEBpML zTh_0;1=cj{Rz=Tl%{o)qbzD8ZEs@a?&giIbKu42_gR_S-d4km&Vn&d(SUglmZ1`jx z@i7w0+wj%l_3va!cP;&7bHhKb!qW=)SF+!}c{;R6zI$8Jce`#BWFI~IhTwPmWt$iJ z>y{i|_%r{Wmag|cH30Lzb8DuTRKMH(&PQvr*KN7EWJ$)&Q|)<6ZofEhUt!MeYez1v zxFa%k+5tYyoF1u>|3hPsG`C?V49}ea2rg(k|MSvCZ-#EX_?z41?uPA$OEz3Nka75I z=9LA`3|*hbba6@R1a~+3?=#oB$9{J0>?p>p4n0ND+sgwR4c+;oyYJTR{CM^1jE{WJ z^p1;9ytnv*c6p$01%AbE2`zVhB6<6nb45^`BWFZ5hk4}(-X~JVffIH3*F}d1j34~E zNZ~=LgF!L}OdJeS5}|bFSY!@GP}YAmLiJ$Q!%;pY(3)1%x+5+5bLm0fo7uPWE?)Vf zX&Z83bag&Y!Of+*Uh3TX+HcdR{b5YwK5+93{m7g &handler); + void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); + bool Subscribe(); + bool Unsubscribe(); + +private: + bool Connect(); + void Disconnect(); + void OnRemoteDied(const wptr &object); + +private: + std::mutex mutex_ {}; + std::weak_ptr handler_ {}; + std::weak_ptr bgContinuousTaskMgr_ {}; + sptr appMgrProxy_ {nullptr}; + sptr appMgrDeathRecipient_ {nullptr}; +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h new file mode 100644 index 00000000..562e24d6 --- /dev/null +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BG_CONTINUOUS_TASK_MGR_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BG_CONTINUOUS_TASK_MGR_H + +#include +#include + +#include "ipc_skeleton.h" +#include "iremote_object.h" +#include "resource_manager.h" +#include "singleton.h" + +#include "app_state_observer.h" +#include "bgtaskmgr_inner_errors.h" +#include "bundle_info.h" +#include "continuous_task_callback_info.h" +#include "task_notification_subscriber.h" +#include "continuous_task_param.h" +#include "continuous_task_record.h" +#include "ibackground_task_subscriber.h" +#include "remote_death_recipient.h" +#include "system_event_observer.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class BackgroundTaskMgrService; + +enum class ContinuousTaskEventTriggerType: uint32_t { + TASK_START, + TASK_CANCEL, +}; + +struct CachedBundleInfo { + std::unordered_map abilityBgMode_ {}; + std::string appName_ {""}; +}; + +class BgContinuousTaskMgr : public DelayedSingleton, + public std::enable_shared_from_this { +public: + ErrCode StartBackgroundRunning(const sptr taskParam); + + ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken); + + ErrCode AddSubscriber(const sptr &subscriber); + + ErrCode RemoveSubscriber(const sptr &subscriber); + + ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); + + bool StopContinuousTaskByUser(const std::string &mapKey); + + void OnBundleInfoChanged(const std::string &action, const std::string &bundleName, uid_t uid); + + void OnProcessDied(int32_t pid); + + void OnRemoteSubscriberDied(const wptr &object); + + bool Init(); + + void InitNecessaryState(); + + void Clear(); + +private: + ErrCode StartBackgroundRunningInner(std::shared_ptr &continuousTaskRecordPtr); + + ErrCode StopBackgroundRunningInner(uid_t uid, const std::string &abilityName, + const sptr &abilityToken); + + ErrCode AddSubscriberInner(const sptr &subscriber); + + ErrCode RemoveSubscriberInner(const sptr &subscriber); + + ErrCode ShellDumpInner(const std::vector &dumpOption, std::vector &dumpInfo); + + void DumpAllTaskInfo(std::vector &dumpInfo); + + void DumpCancelTask(const std::vector &dumpOption, bool cleanAll); + + ErrCode SendContinuousTaskNotification(std::shared_ptr &ContinuousTaskRecordPtr); + + bool RemoveContinuousTaskRecord(const std::string &mapKey); + + bool InitAllBundleBriefInfos(); + + bool AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); + + std::string CreateNotificationLabel(uid_t uid, const std::string &bundleName, + const std::string &abilityName, sptr abilityToken); + + uint32_t GetBackgroundModeInfo(uid_t uid, std::string &abilityName); + + bool AddAbilityBgModeInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); + + bool RegisterNotificationSubscriber(); + + bool RegisterSysCommEventListener(); + + bool RegisterAppStateObserver(); + + bool GetContinuousTaskText(); + + bool SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName); + + void OnRemoteSubscriberDiedInner(const wptr &object); + + std::string CreateNotificationText(int32_t typeId); + + void OnContinuousTaskChanged(const std::shared_ptr continuousTaskInfo, + ContinuousTaskEventTriggerType changeEventType); + +private: + std::atomic isSysReady_ {false}; + std::shared_ptr runner_ {nullptr}; + std::shared_ptr handler_ {nullptr}; + std::unordered_map> continuousTaskInfosMap_ {}; + std::shared_ptr subscriber_ {nullptr}; + std::shared_ptr systemEventListener_ {nullptr}; + std::shared_ptr appStateObserver_ {nullptr}; + std::list> bgTaskSubscribers_ {}; + std::map, sptr> subscriberRecipients_ {}; + std::unordered_map cachedBundleInfos_ {}; + std::vector continuousTaskText_ {}; + + DECLARE_DELAYED_SINGLETON(BgContinuousTaskMgr); +}; +} +} + +#endif \ No newline at end of file diff --git a/services/continuous_task/include/bundle_manager_helper.h b/services/continuous_task/include/bundle_manager_helper.h new file mode 100644 index 00000000..e18af8c1 --- /dev/null +++ b/services/continuous_task/include/bundle_manager_helper.h @@ -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 FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BUNDLE_MANAGER_HELPER_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BUNDLE_MANAGER_HELPER_H + +#include "bundle_mgr_interface.h" +#include "ipc_skeleton.h" +#include "iremote_object.h" +#include "resource_manager.h" +#include "singleton.h" + +#include "remote_death_recipient.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +using OHOS::AppExecFwk::Constants::UNSPECIFIED_USERID; +class BundleManagerHelper : public DelayedSingleton { +public: + std::string GetClientBundleName(uid_t uid); + bool CheckPermission(const std::string &bundleName, const std::string &permission); + bool IsSystemApp(uid_t uid); + bool GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, + AppExecFwk::BundleInfo &bundleInfo, int32_t userId = UNSPECIFIED_USERID); + +private: + bool Connect(); + void Disconnect(); + + void OnRemoteDied(const wptr &object); + +private: + sptr bundleMgr_ = nullptr; + std::mutex connectionMutex_; + sptr bundleMgrDeathRecipient_ = nullptr; + + DECLARE_DELAYED_SINGLETON(BundleManagerHelper) +}; +} +} + +#endif \ No newline at end of file diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h new file mode 100644 index 00000000..c20aa1cf --- /dev/null +++ b/services/continuous_task/include/continuous_task_record.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_CONTINUOUS_TASK_INFO_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_CONTINUOUS_TASK_INFO_H + +#include "iremote_object.h" +#include "parcel.h" +#include "want_agent.h" + +#include "task_notification_subscriber.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +extern const char *ContinuousTaskModeName[10]; + +class ContinuousTaskRecord { +public: + ContinuousTaskRecord() = default; + + ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, + const std::shared_ptr &wantAgent, const sptr &abilityToken, + int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi); + + std::string GetBundleName() const; + + std::string GetAbilityName() const; + + bool IsNewApi() const; + + uint32_t GetBgModeId() const; + + int32_t GetUserId() const; + + uid_t GetUid() const; + + pid_t GetPid() const; + + std::string GetNotificationLabel() const; + + std::shared_ptr GetWantAgent() const; + + sptr GetAbilityToken() const; + +private: + std::string bundleName_ {""}; + std::string abilityName_ {""}; + std::shared_ptr wantAgent_ {nullptr}; + sptr abilityToken_ {nullptr}; + int32_t userId_ {0}; + uid_t uid_ {0}; + pid_t pid_ {0}; + uint32_t bgModeId_ {0}; + bool isNewApi_ {false}; + std::string notificationLabel_ {""}; + + friend class BgContinuousTaskMgr; +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/include/remote_death_recipient.h b/services/continuous_task/include/remote_death_recipient.h new file mode 100644 index 00000000..f6938123 --- /dev/null +++ b/services/continuous_task/include/remote_death_recipient.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_REMOTE_DEATH_RECIPIENT_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_REMOTE_DEATH_RECIPIENT_H + +#include + +#include "iremote_object.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class RemoteDeathRecipient : public IRemoteObject::DeathRecipient { +public: + RemoteDeathRecipient(std::function &)> callback) + { + callback_ = callback; + } + ~RemoteDeathRecipient() + { + callback_ = nullptr; + } + + void OnRemoteDied(const wptr &object) + { + if (callback_ != nullptr) { + callback_(object); + } + } + +private: + std::function &)> callback_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/include/system_event_observer.h b/services/continuous_task/include/system_event_observer.h new file mode 100644 index 00000000..734e5150 --- /dev/null +++ b/services/continuous_task/include/system_event_observer.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_SYSTEM_EVENT_OBSERVER_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_SYSTEM_EVENT_OBSERVER_H + +#include "common_event_manager.h" +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.h" +#include "event_handler.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class BgContinuousTaskMgr; +class SystemEventObserver : public EventFwk::CommonEventSubscriber, + public std::enable_shared_from_this { +public: + SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo); + ~SystemEventObserver() = default; + + void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; + + void SetEventHandler(const std::shared_ptr &handler); + void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); + + bool Subscribe(); + + bool Unsubscribe(); + +private: + std::weak_ptr handler_; + std::weak_ptr bgContinuousTaskMgr_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/include/task_notification_subscriber.h b/services/continuous_task/include/task_notification_subscriber.h new file mode 100644 index 00000000..d16a06c5 --- /dev/null +++ b/services/continuous_task/include/task_notification_subscriber.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_NOTIFICATION_SUBSCRIBER_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_NOTIFICATION_SUBSCRIBER_H + +#include "notification_helper.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class BgContinuousTaskMgr; + +class TaskNotificationSubscriber : public Notification::NotificationSubscriber { +public: + TaskNotificationSubscriber(); + + virtual ~TaskNotificationSubscriber(); + + virtual void OnConnected() override; + + virtual void OnDisconnected() override; + + virtual void OnCanceled(const std::shared_ptr &request) override; + + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override; + + virtual void OnConsumed(const std::shared_ptr &request) override; + + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override; + + virtual void OnUpdate(const std::shared_ptr &sortingMap) override; + + virtual void OnDied() override; + + virtual void OnDoNotDisturbDateChange( + const std::shared_ptr &date) override; + +private: + std::vector StringSplit(const std::string &str, const char *delim); + +private: + static std::shared_ptr continuousTaskMgr_; +}; +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/continuous_task/src/app_state_observer.cpp b/services/continuous_task/src/app_state_observer.cpp new file mode 100644 index 00000000..8e5776dd --- /dev/null +++ b/services/continuous_task/src/app_state_observer.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_state_observer.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "bg_continuous_task_mgr.h" +#include "continuous_task_log.h" +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +const std::string TASK_ON_PROCESS_DIED = "OnProcessDiedTask"; +} + +AppStateObserver::AppStateObserver() +{ + appMgrDeathRecipient_ = new RemoteDeathRecipient(std::bind(&AppStateObserver::OnRemoteDied, + this, std::placeholders::_1)); +} + +AppStateObserver::~AppStateObserver() +{ + std::lock_guard lock(mutex_); + Disconnect(); +} + +void AppStateObserver::OnProcessDied(const AppExecFwk::ProcessData &processData) +{ + BGTASK_LOGI("process died, pid : %{public}d", processData.pid); + auto handler = handler_.lock(); + if (!handler) { + BGTASK_LOGE("handler is null"); + return; + } + auto bgContinuousTaskMgr = bgContinuousTaskMgr_.lock(); + if (!bgContinuousTaskMgr) { + BGTASK_LOGE("bgContinuousTaskMgr is null"); + return; + } + + auto task = [=]() { bgContinuousTaskMgr->OnProcessDied(processData.pid); }; + handler->PostTask(task, TASK_ON_PROCESS_DIED); +} + +void AppStateObserver::SetEventHandler(const std::shared_ptr &handler) +{ + handler_ = handler; +} + +void AppStateObserver::SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr) +{ + bgContinuousTaskMgr_ = bgContinuousTaskMgr; +} + +bool AppStateObserver::Subscribe() +{ + BGTASK_LOGI("Subscribe called"); + std::lock_guard lock(mutex_); + + if (!Connect()) { + return false; + } + appMgrProxy_->RegisterApplicationStateObserver(iface_cast(this)); + return true; +} + +bool AppStateObserver::Unsubscribe() +{ + BGTASK_LOGI("UnSubscribe called"); + std::lock_guard lock(mutex_); + if (!Connect()) { + return false; + } + appMgrProxy_->UnregisterApplicationStateObserver(iface_cast(this)); + return true; +} + +bool AppStateObserver::Connect() +{ + if (appMgrProxy_ != nullptr) { + return true; + } + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + BGTASK_LOGE("get SystemAbilityManager failed"); + return false; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + BGTASK_LOGE("get App Manager Service failed"); + return false; + } + + appMgrProxy_ = iface_cast(remoteObject); + if (!appMgrProxy_ || !appMgrProxy_->AsObject()) { + BGTASK_LOGE("get app mgr proxy failed!"); + return false; + } + appMgrProxy_->AsObject()->AddDeathRecipient(appMgrDeathRecipient_); + return true; +} + +void AppStateObserver::Disconnect() +{ + if (appMgrProxy_ != nullptr) { + appMgrProxy_->AsObject()->RemoveDeathRecipient(appMgrDeathRecipient_); + appMgrProxy_ = nullptr; + } +} + +void AppStateObserver::OnRemoteDied(const wptr &object) +{ + std::lock_guard lock(mutex_); + Disconnect(); +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp new file mode 100644 index 00000000..c94ba645 --- /dev/null +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -0,0 +1,854 @@ +/* + * 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 "bg_continuous_task_mgr.h" + +#include + +#include "bundle_constants.h" +#include "bundle_manager_helper.h" +#include "common_event_support.h" +#include "common_event_manager.h" +#include "errors.h" +#include "if_system_ability_manager.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "ohos/aafwk/base/string_wrapper.h" +#include "os_account_manager.h" +#include "system_ability_definition.h" + +#include "bgtaskmgr_inner_errors.h" +#include "continuous_task_record.h" +#include "continuous_task_log.h" +#include "system_event_observer.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static const char *CONTI_TASK_TEXT_RES_NAMES[] = { + "ohos_bgmode_prompt_data_transfer", + "ohos_bgmode_prompt_audio_playback", + "ohos_bgmode_prompt_audio_recording", + "ohos_bgmode_prompt_location", + "ohos_bgmode_prompt_bluetooth_interaction", + "ohos_bgmode_prompt_multidevice_connection", + "ohos_bgmode_prompt_wifi_interaction", + "ohos_bgmode_prompt_voip", + "ohos_bgmode_prompt_task_keeping", + "ohos_bgmode_prompt_default_value", +}; + +static constexpr char BG_CONTINUOUS_TASK_MGR_NAME[] = "BgContinuousTaskMgr"; +static constexpr char SEPARATOR[] = "_"; +static constexpr char DUMP_PARAM_LIST_ALL[] = "--all"; +static constexpr char DUMP_PARAM_CANCEL_ALL[] = "--cancel_all"; +static constexpr char DUMP_PARAM_CANCEL[] = "--cancel"; +static constexpr char NOTIFICATION_PREFIX[] = "bgmode"; +static constexpr char BGMODE_PERMISSION[] = "ohos.permission.KEEP_BACKGROUND_RUNNING"; +static constexpr char BG_TASK_RES_BUNDLE_NAME[] = "ohos.global.backgroundtaskres"; +static constexpr uint32_t SYSTEM_APP_BGMODE_WIFI_INTERACTION = 64; +static constexpr uint32_t SYSTEM_APP_BGMODE_VOIP = 128; +static constexpr unsigned int SYSTEM_UID = 1000; +static constexpr int32_t DEFAULT_NOTIFICATION_ID = 0; +static constexpr int DELAY_TIME = 2000; +static constexpr uint32_t INVALID_BGMODE = 0; +static constexpr uint32_t BG_MODE_INDEX_HEAD = 1; +static constexpr int BGMODE_NUMS = 10; +} + +BgContinuousTaskMgr::BgContinuousTaskMgr() +{} + +BgContinuousTaskMgr::~BgContinuousTaskMgr() +{} + +bool BgContinuousTaskMgr::Init() +{ + runner_ = AppExecFwk::EventRunner::Create(BG_CONTINUOUS_TASK_MGR_NAME); + if (runner_ == nullptr) { + BGTASK_LOGE("BgContinuousTaskMgr runner create failed!"); + return false; + } + handler_ = std::make_shared(runner_); + if (handler_ == nullptr) { + BGTASK_LOGE("BgContinuousTaskMgr handler create failed!"); + return false; + } + auto task = [this]() { this->InitNecessaryState(); }; + handler_->PostSyncTask(task); + return true; +} + +void BgContinuousTaskMgr::Clear() +{ + Notification::NotificationHelper::UnSubscribeNotification(*subscriber_); + if (systemEventListener_ != nullptr) { + systemEventListener_->Unsubscribe(); + } + if (appStateObserver_ != nullptr) { + appStateObserver_->Unsubscribe(); + } +} + +void BgContinuousTaskMgr::InitNecessaryState() +{ + sptr systemAbilityManager + = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr + || systemAbilityManager->CheckSystemAbility(APP_MGR_SERVICE_ID) == nullptr + || systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr + || systemAbilityManager->CheckSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID) == nullptr + || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr) { + BGTASK_LOGW("request system service is not ready yet!"); + auto task = [this]() { this->InitNecessaryState(); }; + handler_->PostTask(task, DELAY_TIME); + return; + } + + bool isInitSucceed = true; + if (!RegisterNotificationSubscriber()) { + BGTASK_LOGE("RegisterNotificationSubscriber failed"); + isInitSucceed = false; + } + if (!RegisterAppStateObserver()) { + BGTASK_LOGE("RegisterAppStateObserver failed"); + isInitSucceed = false; + } + if (!RegisterSysCommEventListener()) { + BGTASK_LOGE("RegisterSysCommEventListener failed"); + isInitSucceed = false; + } + if (!GetContinuousTaskText()) { + BGTASK_LOGE("GetContinuousTaskText failed"); + isInitSucceed = false; + } + isSysReady_.store(isInitSucceed); +} + +bool BgContinuousTaskMgr::RegisterNotificationSubscriber() +{ + BGTASK_LOGI("begin"); + bool res = true; + subscriber_ = std::make_shared(); + if (Notification::NotificationHelper::SubscribeNotification(*subscriber_) != ERR_OK) { + BGTASK_LOGE("SubscribeNotification failed!"); + res = false; + } + return res; +} + +bool BgContinuousTaskMgr::RegisterAppStateObserver() +{ + bool res = true; + appStateObserver_ = std::make_shared(); + if (appStateObserver_ != nullptr) { + appStateObserver_->SetEventHandler(handler_); + appStateObserver_->SetBgContinuousTaskMgr(shared_from_this()); + res = appStateObserver_->Subscribe(); + } + return res; +} + +bool BgContinuousTaskMgr::GetContinuousTaskText() +{ + AppExecFwk::BundleInfo bundleInfo; + if (!BundleManagerHelper::GetInstance()->GetBundleInfo(BG_TASK_RES_BUNDLE_NAME, + AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo)) { + BGTASK_LOGE("get background task res: %{public}s bundle info failed", BG_TASK_RES_BUNDLE_NAME); + return false; + } + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (!resourceManager) { + BGTASK_LOGE("create resourceManager failed"); + return false; + } + for (auto moduleResPath : bundleInfo.moduleResPaths) { + if (!moduleResPath.empty()) { + if (!resourceManager->AddResource(moduleResPath.c_str())) { + BGTASK_LOGE("AddResource failed"); + } + } + } + std::string taskText {""}; + for (std::string name : CONTI_TASK_TEXT_RES_NAMES) { + resourceManager->GetStringByName(name.c_str(), taskText); + if (taskText.empty()) { + BGTASK_LOGE("get continuous task notification text failed!"); + return false; + } + BGTASK_LOGI("get taskText: %{public}s", taskText.c_str()); + continuousTaskText_.push_back(taskText); + } + return true; +} + +bool BgContinuousTaskMgr::RegisterSysCommEventListener() +{ + bool res = true; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REPLACED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); + EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills); + systemEventListener_ = std::make_shared(commonEventSubscribeInfo); + if (systemEventListener_ != nullptr) { + systemEventListener_->SetEventHandler(handler_); + systemEventListener_->SetBgContinuousTaskMgr(shared_from_this()); + res = systemEventListener_->Subscribe(); + } + return res; +} + +bool BgContinuousTaskMgr::SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName) +{ + AppExecFwk::BundleInfo bundleInfo; + if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, + AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId)) { + BGTASK_LOGW("get bundle info: %{public}s failure!", bundleName.c_str()); + return false; + } + + CachedBundleInfo cachedBundleInfo = CachedBundleInfo(); + if (AddAbilityBgModeInfos(bundleInfo, cachedBundleInfo) + && AddAppNameInfos(bundleInfo, cachedBundleInfo)) { + cachedBundleInfos_.emplace(uid, cachedBundleInfo); + return true; + } + return false; +} + +bool BgContinuousTaskMgr::AddAbilityBgModeInfos(const AppExecFwk::BundleInfo &bundleInfo, + CachedBundleInfo &cachedBundleInfo) +{ + for (auto abilityInfo : bundleInfo.abilityInfos) { + if (abilityInfo.backgroundModes != INVALID_BGMODE) { + cachedBundleInfo.abilityBgMode_.emplace(abilityInfo.name, abilityInfo.backgroundModes); + BGTASK_LOGI("abilityName: %{public}s, abilityNameHash: %{public}s, Background Mode: %{public}d.", + abilityInfo.name.c_str(), std::to_string(std::hash()(abilityInfo.name)).c_str(), + abilityInfo.backgroundModes); + } + } + if (cachedBundleInfo.abilityBgMode_.empty()) { + return false; + } + return true; +} + +bool BgContinuousTaskMgr::AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo) +{ + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (resourceManager == nullptr) { + BGTASK_LOGE("resourceManager init failed!"); + return false; + } + int32_t labelId = bundleInfo.applicationInfo.labelId; + std::string bundleName = bundleInfo.name; + std::string appName {""}; + for (auto resPath = bundleInfo.moduleResPaths.begin(); resPath != bundleInfo.moduleResPaths.end(); resPath++) { + if (resPath->empty()) { + continue; + } + if (!resourceManager->AddResource(resPath->c_str())) { + BGTASK_LOGE("resourceManager add %{public}s resource path failed!", bundleInfo.name.c_str()); + } + } + resourceManager->GetStringById(labelId, appName); + appName = appName.empty() ? bundleInfo.applicationInfo.label : appName; + BGTASK_LOGI("get app display info, labelId: %{public}d, appname: %{public}s", labelId, appName.c_str()); + cachedBundleInfo.appName_ = appName; + return true; +} + +bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool isNewApi, uid_t uid) +{ + if (!isNewApi) { + if (configuredBgMode == INVALID_BGMODE) { + BGTASK_LOGE("ability without background mode config"); + return false; + } else { + return true; + } + } else { + uint32_t recordedBgMode = BG_MODE_INDEX_HEAD << (requestedBgModeId - 1); + if ((recordedBgMode == SYSTEM_APP_BGMODE_WIFI_INTERACTION || recordedBgMode == SYSTEM_APP_BGMODE_VOIP) + && !BundleManagerHelper::GetInstance()->IsSystemApp(uid)) { + BGTASK_LOGW("voip and wifiInteraction background mode only support for system app"); + return false; + } + if (requestedBgModeId == INVALID_BGMODE || (configuredBgMode + & (BG_MODE_INDEX_HEAD << (requestedBgModeId - 1))) == 0) { + BGTASK_LOGE("requested background mode is not declared in config file!"); + return false; + } + } + return true; +} + +uint32_t BgContinuousTaskMgr::GetBackgroundModeInfo(uid_t uid, std::string &abilityName) +{ + if (cachedBundleInfos_.find(uid) != cachedBundleInfos_.end()) { + auto cachedBundleInfo = cachedBundleInfos_.at(uid); + if (cachedBundleInfo.abilityBgMode_.find(abilityName) != + cachedBundleInfo.abilityBgMode_.end()) { + return cachedBundleInfo.abilityBgMode_.at(abilityName); + } + } + return INVALID_BGMODE; +} + +ErrCode BgContinuousTaskMgr::StartBackgroundRunning(const sptr taskParam) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + + if (!taskParam) { + BGTASK_LOGE("continuous task params is null!"); + return ERR_BGTASK_INVALID_PARAM; + } + + if (taskParam->isNewApi_) { + if (taskParam->wantAgent_ == nullptr || taskParam->abilityName_.empty()) { + BGTASK_LOGE("continuous task params invalid!"); + return ERR_BGTASK_INVALID_PARAM; + } + } else { + if (taskParam->abilityName_.empty()) { + BGTASK_LOGE("continuous task params invalid!"); + return ERR_BGTASK_INVALID_PARAM; + } + } + + ErrCode result = ERR_OK; + + uid_t callingUid = IPCSkeleton::GetCallingUid(); + pid_t callingPid = IPCSkeleton::GetCallingPid(); + std::string bundleName = BundleManagerHelper::GetInstance()->GetClientBundleName(callingUid); + int32_t userId = -1; + AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); + + std::shared_ptr continuousTaskRecord = std::make_shared(bundleName, + taskParam->abilityName_, taskParam->wantAgent_, taskParam->abilityToken_, userId, callingUid, callingPid, + taskParam->bgModeId_, taskParam->isNewApi_); + + handler_->PostSyncTask([this, continuousTaskRecord, &result]() mutable { + result = this->StartBackgroundRunningInner(continuousTaskRecord); + }, AppExecFwk::EventQueue::Priority::HIGH); + + BGTASK_LOGI("end"); + return result; +} + +ErrCode BgContinuousTaskMgr::StartBackgroundRunningInner(std::shared_ptr &continuousTaskRecord) +{ + BGTASK_LOGI("begin"); + + std::stringstream stream; + stream.clear(); + stream.str(""); + continuousTaskRecord->abilityToken_ ? stream << continuousTaskRecord->abilityToken_ : stream << 0; + std::string abilityTokeLabel = stream.str(); + std::string taskInfoMapKey = std::to_string(continuousTaskRecord->uid_) + SEPARATOR + + continuousTaskRecord->abilityName_ + SEPARATOR + abilityTokeLabel; + if (continuousTaskInfosMap_.find(taskInfoMapKey) != continuousTaskInfosMap_.end()) { + BGTASK_LOGI("continuous task is already exist: %{public}s", taskInfoMapKey.c_str()); + return ERR_BGTASK_OBJECT_EXISTS; + } + + if (!BundleManagerHelper::GetInstance()->CheckPermission(continuousTaskRecord->bundleName_, BGMODE_PERMISSION)) { + BGTASK_LOGE("background mode permission is not passed"); + return ERR_BGTASK_PERMISSION_DENIED; + } + + if (cachedBundleInfos_.find(continuousTaskRecord->uid_) == cachedBundleInfos_.end()) { + SetCachedBundleInfo(continuousTaskRecord->uid_, continuousTaskRecord->userId_, + continuousTaskRecord->bundleName_); + } + + uint32_t configuredBgMode = GetBackgroundModeInfo(continuousTaskRecord->uid_, + continuousTaskRecord->abilityName_); + if (!checkBgmodeType(configuredBgMode, continuousTaskRecord->bgModeId_, continuousTaskRecord->isNewApi_, + continuousTaskRecord->uid_)) { + BGTASK_LOGE("background mode invalid!"); + return ERR_BGTASK_INVALID_BGMODE; + } + + if (SendContinuousTaskNotification(continuousTaskRecord) != ERR_OK) { + BGTASK_LOGE("publish error"); + return ERR_BGTASK_NOTIFICATION_ERR; + } + continuousTaskInfosMap_.emplace(taskInfoMapKey, continuousTaskRecord); + OnContinuousTaskChanged(continuousTaskRecord, ContinuousTaskEventTriggerType::TASK_START); + return ERR_OK; +} + +int32_t GetBgModeNameIndex(uint32_t bgModeId, bool isNewApi) +{ + if (!isNewApi) { + return BGMODE_NUMS - 1; + } else { + return bgModeId - 1; + } +} + +ErrCode BgContinuousTaskMgr::SendContinuousTaskNotification( + std::shared_ptr &continuousTaskRecord) +{ + BGTASK_LOGI("begin"); + std::shared_ptr normalContent + = std::make_shared(); + + std::string notificationText {""}; + int32_t index = GetBgModeNameIndex(continuousTaskRecord->GetBgModeId(), continuousTaskRecord->isNewApi_); + if (index >= 0 && index < BGMODE_NUMS) { + notificationText = continuousTaskText_.at(index); + } + std::string appName {""}; + if (cachedBundleInfos_.find(continuousTaskRecord->uid_) != cachedBundleInfos_.end()) { + appName = cachedBundleInfos_.at(continuousTaskRecord->uid_).appName_; + } + if (appName.empty() || notificationText.empty()) { + BGTASK_LOGE("get notification prompt info failed"); + return ERR_BGTASK_INVALID_PARAM; + } + + normalContent->SetTitle(appName); + normalContent->SetText(notificationText); + + Notification::NotificationRequest notificationRequest = Notification::NotificationRequest(); + + std::shared_ptr extraInfo = std::make_shared(); + extraInfo->SetParam("abilityName", AAFwk::String::Box(continuousTaskRecord->abilityName_)); + + std::string notificationLabel = CreateNotificationLabel(continuousTaskRecord->uid_, + continuousTaskRecord->bundleName_, continuousTaskRecord->abilityName_, continuousTaskRecord->abilityToken_); + + // set extraInfo to save abilityname Info. + notificationRequest.SetAdditionalData(extraInfo); + + // set basic notification content + notificationRequest.SetContent(std::make_shared(normalContent)); + + // set wantagent param for click jump to target ability + notificationRequest.SetWantAgent(continuousTaskRecord->wantAgent_); + + // set notification label distinguish different notification + notificationRequest.SetLabel(notificationLabel); + + // set creator uid as system uid 1000 + notificationRequest.SetCreatorUid(SYSTEM_UID); + + // set creator user id to -2 means to get all user's notification event callback. + notificationRequest.SetCreatorUserId(-2); + + if (Notification::NotificationHelper::PublishContinuousTaskNotification(notificationRequest) != ERR_OK) { + BGTASK_LOGI("publish notification error"); + return ERR_BGTASK_NOTIFICATION_ERR; + } + continuousTaskRecord->notificationLabel_ = notificationLabel; + + BGTASK_LOGI("end"); + return ERR_OK; +} + +std::string BgContinuousTaskMgr::CreateNotificationLabel(uid_t uid, const std::string &bundleName, + const std::string &abilityName, const sptr abilityToken) +{ + std::stringstream stream; + stream.clear(); + stream.str(""); + stream << NOTIFICATION_PREFIX << SEPARATOR << uid << SEPARATOR << std::hash()(abilityName) + << SEPARATOR << (abilityToken ? (abilityToken) : 0); + std::string label = stream.str(); + BGTASK_LOGI("notification label: %{public}s", label.c_str()); + return label; +} + +ErrCode BgContinuousTaskMgr::StopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + if (abilityName.empty()) { + BGTASK_LOGE("abilityName is empty!"); + return ERR_BGTASK_INVALID_PARAM; + } + uid_t callingUid = IPCSkeleton::GetCallingUid(); + + ErrCode result = ERR_OK; + + handler_->PostSyncTask([this, callingUid, abilityName, abilityToken, &result]() { + result = this->StopBackgroundRunningInner(callingUid, abilityName, abilityToken); + }, AppExecFwk::EventQueue::Priority::HIGH); + + return result; +} + +ErrCode BgContinuousTaskMgr::StopBackgroundRunningInner(uid_t uid, const std::string &abilityName, + const sptr &abilityToken) +{ + BGTASK_LOGI("begin"); + std::stringstream stream; + stream.clear(); + stream.str(""); + abilityToken ? stream << abilityToken : stream << 0; + std::string abilityTokeLabel = stream.str(); + std::string mapKey = std::to_string(uid) + SEPARATOR + abilityName + SEPARATOR + abilityTokeLabel; + + auto iter = continuousTaskInfosMap_.find(mapKey); + if (iter == continuousTaskInfosMap_.end()) { + BGTASK_LOGW("%{public}s continuous task not exists", mapKey.c_str()); + return ERR_BGTASK_INVALID_PARAM; + } + ErrCode result = Notification::NotificationHelper::CancelContinuousTaskNotification( + iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); + RemoveContinuousTaskRecord(mapKey); + BGTASK_LOGI("end"); + return result; +} + +ErrCode BgContinuousTaskMgr::AddSubscriber(const sptr &subscriber) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + if (subscriber == nullptr) { + BGTASK_LOGI("subscriber is null."); + return ERR_BGTASK_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask([this, &subscriber, &result]() { + result = AddSubscriberInner(subscriber); + }, AppExecFwk::EventQueue::Priority::HIGH); + + return result; +} + +ErrCode BgContinuousTaskMgr::AddSubscriberInner(const sptr &subscriber) +{ + BGTASK_LOGI("begin"); + auto remoteObj = subscriber->AsObject(); + auto findSuscriber = [&remoteObj](const auto& target) { + return remoteObj == target->AsObject(); + }; + + auto subscriberIter = find_if(bgTaskSubscribers_.begin(), bgTaskSubscribers_.end(), findSuscriber); + if (subscriberIter != bgTaskSubscribers_.end()) { + BGTASK_LOGW("target subscriber already exist"); + return ERR_BGTASK_OBJECT_EXISTS; + } + + bgTaskSubscribers_.emplace_back(subscriber); + + if (subscriber->AsObject() == nullptr) { + return ERR_BGTASK_INVALID_PARAM; + } + if (subscriberRecipients_.find(subscriber->AsObject()) != subscriberRecipients_.end()) { + return ERR_BGTASK_OBJECT_EXISTS; + } + sptr deathRecipient = + new RemoteDeathRecipient([this](const wptr &remote) { this->OnRemoteSubscriberDied(remote); }); + subscriber->AsObject()->AddDeathRecipient(deathRecipient); + subscriberRecipients_.emplace(subscriber->AsObject(), deathRecipient); + subscriber->OnConnected(); + BGTASK_LOGI("end"); + return ERR_OK; +} + +ErrCode BgContinuousTaskMgr::RemoveSubscriber(const sptr &subscriber) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + if (subscriber == nullptr) { + BGTASK_LOGE("subscriber is null."); + return ERR_BGTASK_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask([this, &subscriber, &result]() { + result = this->RemoveSubscriberInner(subscriber); + }, AppExecFwk::EventQueue::Priority::HIGH); + + return result; +} + +ErrCode BgContinuousTaskMgr::RemoveSubscriberInner(const sptr &subscriber) +{ + BGTASK_LOGI("begin"); + auto subscriberIter = bgTaskSubscribers_.begin(); + while (subscriberIter != bgTaskSubscribers_.end()) { + if ((*subscriberIter)->AsObject() == subscriber->AsObject()) { + subscriberIter = bgTaskSubscribers_.erase(subscriberIter); + } else { + subscriberIter++; + } + } + if (subscriber->AsObject() == nullptr) { + return ERR_BGTASK_INVALID_PARAM; + } + auto iter = subscriberRecipients_.find(subscriber->AsObject()); + if (iter != subscriberRecipients_.end()) { + iter->first->RemoveDeathRecipient(iter->second); + subscriberRecipients_.erase(iter); + } + subscriber->OnDisconnected(); + BGTASK_LOGI("end"); + return ERR_OK; +} + +ErrCode BgContinuousTaskMgr::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + ErrCode result = ERR_OK; + handler_->PostSyncTask([&]() { + result = ShellDumpInner(dumpOption, dumpInfo); + }); + + return result; +} + +ErrCode BgContinuousTaskMgr::ShellDumpInner(const std::vector &dumpOption, + std::vector &dumpInfo) +{ + BGTASK_LOGI("begin"); + if (dumpOption[1] == DUMP_PARAM_LIST_ALL) { + DumpAllTaskInfo(dumpInfo); + } else if (dumpOption[1] == DUMP_PARAM_CANCEL_ALL) { + DumpCancelTask(dumpOption, true); + } else if (dumpOption[1] == DUMP_PARAM_CANCEL) { + DumpCancelTask(dumpOption, false); + } + return ERR_OK; +} + +void BgContinuousTaskMgr::DumpAllTaskInfo(std::vector &dumpInfo) +{ + BGTASK_LOGI("begin"); + std::stringstream stream; + if (continuousTaskInfosMap_.empty()) { + dumpInfo.emplace_back("No running continuous task\n"); + return; + } + std::unordered_map>::iterator iter; + uint32_t index = 1; + for (iter = continuousTaskInfosMap_.begin(); iter != continuousTaskInfosMap_.end(); iter++) { + stream.str(""); + stream.clear(); + stream << "No." << index; + stream << "\tcontinuousTaskKey: " << iter->first << "\n"; + stream << "\tcontinuousTaskValue:" << "\n"; + stream << "\t\tbundleName: " << iter->second->GetBundleName() << "\n"; + stream << "\t\tabilityName: " << iter->second->GetAbilityName() << "\n"; + stream << "\t\tisFromNewApi: " << (iter->second->IsNewApi() ? "true" : "false") << "\n"; + stream << "\t\tbackgroundMode: " << ContinuousTaskModeName[GetBgModeNameIndex( + iter->second->GetBgModeId(), iter->second->IsNewApi())] << "\n"; + stream << "\t\tuid: " << iter->second->GetUid() << "\n"; + stream << "\t\tuserId: " << iter->second->GetUserId() << "\n"; + stream << "\t\tpid: " << iter->second->GetPid() << "\n"; + stream << "\t\tnotificationLabel: " << iter->second->GetNotificationLabel() << "\n"; + auto wantAgent = iter->second->GetWantAgent(); + if (wantAgent != nullptr && wantAgent->GetPendingWant() != nullptr) { + auto want = wantAgent->GetPendingWant()->GetWant(wantAgent->GetPendingWant()->GetTarget()); + if (want != nullptr) { + stream << "\t\twantAgentBundleName: " << want->GetOperation().GetBundleName() << "\n"; + stream << "\t\twantAgentAbilityName: " << want->GetOperation().GetAbilityName() << "\n"; + } + } else { + stream << "\t\twantAgentBundleName: " << "NULL" << "\n"; + stream << "\t\twantAgentAbilityName: " << "NULL" << "\n"; + } + stream << "\n"; + dumpInfo.emplace_back(stream.str()); + index++; + } +} + +void BgContinuousTaskMgr::DumpCancelTask(const std::vector &dumpOption, bool cleanAll) +{ + BGTASK_LOGI("begin"); + if (cleanAll) { + for (auto item : continuousTaskInfosMap_) { + Notification::NotificationHelper::CancelContinuousTaskNotification(item.second->GetNotificationLabel(), + DEFAULT_NOTIFICATION_ID); + OnContinuousTaskChanged(item.second, ContinuousTaskEventTriggerType::TASK_CANCEL); + } + continuousTaskInfosMap_.clear(); + } else { + std::string taskKey = dumpOption[2]; + auto iter = continuousTaskInfosMap_.find(taskKey); + if (iter == continuousTaskInfosMap_.end()) { + return; + } + Notification::NotificationHelper::CancelContinuousTaskNotification(iter->second->GetNotificationLabel(), + DEFAULT_NOTIFICATION_ID); + RemoveContinuousTaskRecord(taskKey); + } +} + +bool BgContinuousTaskMgr::RemoveContinuousTaskRecord(const std::string &mapKey) +{ + BGTASK_LOGI("task info: %{public}s", mapKey.c_str()); + if (continuousTaskInfosMap_.find(mapKey) == continuousTaskInfosMap_.end()) { + BGTASK_LOGW("remove TaskInfo failure, no matched task: %{public}s", mapKey.c_str()); + return false; + } + OnContinuousTaskChanged(continuousTaskInfosMap_.at(mapKey), ContinuousTaskEventTriggerType::TASK_CANCEL); + continuousTaskInfosMap_.erase(mapKey); + BGTASK_LOGI("end"); + return true; +} + +bool BgContinuousTaskMgr::StopContinuousTaskByUser(const std::string &mapKey) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return ERR_BGTASK_SYS_NOT_READY; + } + bool result = true; + handler_->PostSyncTask([this, mapKey, &result]() { + result = RemoveContinuousTaskRecord(mapKey); + }); + return result; +} + +void BgContinuousTaskMgr::OnRemoteSubscriberDied(const wptr &object) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return; + } + if (object == nullptr) { + BGTASK_LOGI("remote object is null."); + return; + } + + handler_->PostSyncTask([this, &object]() { this->OnRemoteSubscriberDiedInner(object); }); +} + +void BgContinuousTaskMgr::OnRemoteSubscriberDiedInner(const wptr &object) +{ + BGTASK_LOGI("begin"); + sptr objectProxy = object.promote(); + if (!objectProxy) { + BGTASK_LOGE("get remote object failed"); + return; + } + auto iter = bgTaskSubscribers_.begin(); + while (iter != bgTaskSubscribers_.end()) { + if ((*iter)->AsObject() == objectProxy) { + iter = bgTaskSubscribers_.erase(iter); + } else { + iter++; + } + } + subscriberRecipients_.erase(objectProxy); +} + +void BgContinuousTaskMgr::OnProcessDied(int32_t pid) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return; + } + + auto iter = continuousTaskInfosMap_.begin(); + while (iter != continuousTaskInfosMap_.end()) { + if (iter->second->GetPid() == pid) { + OnContinuousTaskChanged(iter->second, ContinuousTaskEventTriggerType::TASK_CANCEL); + Notification::NotificationHelper::CancelContinuousTaskNotification( + iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); + iter = continuousTaskInfosMap_.erase(iter); + } else { + iter++; + } + } +} + +void BgContinuousTaskMgr::OnContinuousTaskChanged(const std::shared_ptr continuousTaskInfo, + ContinuousTaskEventTriggerType changeEventType) +{ + BGTASK_LOGI("begin"); + if (continuousTaskInfo == nullptr) { + BGTASK_LOGW("ContinuousTaskRecord is null"); + return; + } + + if (bgTaskSubscribers_.empty()) { + BGTASK_LOGI("Background Task Subscriber List is empty"); + return; + } + + sptr continuousTaskCallbackInfo = new ContinuousTaskCallbackInfo( + continuousTaskInfo->GetBgModeId(), continuousTaskInfo->GetUid(), + continuousTaskInfo->GetPid(), continuousTaskInfo->GetAbilityName()); + + switch (changeEventType) { + case ContinuousTaskEventTriggerType::TASK_START: + for (auto iter = bgTaskSubscribers_.begin(); iter != bgTaskSubscribers_.end(); iter++) { + BGTASK_LOGI("continuous task start callback trigger"); + (*iter)->OnContinuousTaskStart(continuousTaskCallbackInfo); + } + break; + case ContinuousTaskEventTriggerType::TASK_CANCEL: + for (auto iter = bgTaskSubscribers_.begin(); iter != bgTaskSubscribers_.end(); iter++) { + BGTASK_LOGI("continuous task stop callback trigger"); + (*iter)->OnContinuousTaskStop(continuousTaskCallbackInfo); + } + break; + } +} + +void BgContinuousTaskMgr::OnBundleInfoChanged(const std::string &action, const std::string &bundleName, uid_t uid) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return; + } + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REPLACED) { + cachedBundleInfos_.erase(uid); + } else { + BGTASK_LOGW("get unregister common event!"); + return; + } +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/bundle_manager_helper.cpp b/services/continuous_task/src/bundle_manager_helper.cpp new file mode 100644 index 00000000..b25de200 --- /dev/null +++ b/services/continuous_task/src/bundle_manager_helper.cpp @@ -0,0 +1,132 @@ +/* + * 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 "bundle_manager_helper.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED; + +BundleManagerHelper::BundleManagerHelper() +{ + bundleMgrDeathRecipient_ = new RemoteDeathRecipient( + [this](const wptr &object) { this->OnRemoteDied(object); }); +} + +BundleManagerHelper::~BundleManagerHelper() +{ + std::lock_guard lock(connectionMutex_); + Disconnect(); +} + +std::string BundleManagerHelper::GetClientBundleName(uid_t uid) +{ + std::string bundle {""}; + std::lock_guard lock(connectionMutex_); + Connect(); + if (bundleMgr_ != nullptr) { + bundleMgr_->GetBundleNameForUid(uid, bundle); + } + BGTASK_LOGI("get client Bundle Name: %{public}s", bundle.c_str()); + return bundle; +} + +bool BundleManagerHelper::CheckPermission(const std::string &bundleName, + const std::string &permission) +{ + std::lock_guard lock(connectionMutex_); + Connect(); + if (bundleMgr_ != nullptr) { + auto result = bundleMgr_->CheckPermission(bundleName, permission); + BGTASK_LOGI("permission check result: %{public}d", result); + if (result == PERMISSION_GRANTED) { + return true; + } + } + return false; +} + +bool BundleManagerHelper::IsSystemApp(uid_t uid) +{ + bool isSystemApp = false; + std::lock_guard lock(connectionMutex_); + Connect(); + if (bundleMgr_ != nullptr) { + isSystemApp = bundleMgr_->CheckIsSystemAppByUid(uid); + } + return isSystemApp; +} + +bool BundleManagerHelper::GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, + AppExecFwk::BundleInfo &bundleInfo, int32_t userId) +{ + std::lock_guard lock(connectionMutex_); + + Connect(); + + if (bundleMgr_ != nullptr && bundleMgr_->GetBundleInfo(bundleName, flag, bundleInfo, userId)) { + return true; + } + return false; +} + +bool BundleManagerHelper::Connect() +{ + if (bundleMgr_ != nullptr) { + return true; + } + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + BGTASK_LOGE("get SystemAbilityManager failed"); + return false; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + BGTASK_LOGE("get Bundle Manager failed"); + return false; + } + + bundleMgr_ = iface_cast(remoteObject); + if (bundleMgr_ != nullptr) { + bundleMgr_->AsObject()->AddDeathRecipient(bundleMgrDeathRecipient_); + return true; + } + BGTASK_LOGE("get bundleMgr failed"); + return false; +} + +void BundleManagerHelper::Disconnect() +{ + if (bundleMgr_ != nullptr) { + bundleMgr_->AsObject()->RemoveDeathRecipient(bundleMgrDeathRecipient_); + bundleMgr_ = nullptr; + } +} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{ + std::lock_guard lock(connectionMutex_); + Disconnect(); +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp new file mode 100644 index 00000000..a3bfa181 --- /dev/null +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -0,0 +1,92 @@ +/* + * 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 "continuous_task_record.h" + +#include "iremote_object.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +const char *ContinuousTaskModeName[10] = { + "dataTransfer", + "audioPlayback", + "audioRecording", + "location", + "bluetoothInteraction", + "multiDeviceConnection", + "wifiInteraction", + "voip", + "taskKeeping", + "default", +}; + +ContinuousTaskRecord::ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, + const std::shared_ptr &wantAgent, const sptr &abilityToken, + int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi) + : bundleName_(bundleName), abilityName_(abilityName), wantAgent_(wantAgent), abilityToken_(abilityToken), + userId_(userId), uid_(uid), pid_(pid), bgModeId_(bgModeId), isNewApi_(isNewApi) +{} + +std::string ContinuousTaskRecord::GetBundleName() const +{ + return bundleName_; +} + +std::string ContinuousTaskRecord::GetAbilityName() const +{ + return abilityName_; +} + +bool ContinuousTaskRecord::IsNewApi() const +{ + return isNewApi_; +} + +uint32_t ContinuousTaskRecord::GetBgModeId() const +{ + return bgModeId_; +} + +int32_t ContinuousTaskRecord::GetUserId() const +{ + return userId_; +} + +uid_t ContinuousTaskRecord::GetUid() const +{ + return uid_; +} + +pid_t ContinuousTaskRecord::GetPid() const +{ + return pid_; +} + +std::string ContinuousTaskRecord::GetNotificationLabel() const +{ + return notificationLabel_; +} + +std::shared_ptr ContinuousTaskRecord::GetWantAgent() const +{ + return wantAgent_; +} + +sptr ContinuousTaskRecord::GetAbilityToken() const +{ + return abilityToken_; +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp new file mode 100644 index 00000000..0f36f44f --- /dev/null +++ b/services/continuous_task/src/system_event_observer.cpp @@ -0,0 +1,90 @@ +/* + * 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 "system_event_observer.h" + +#include "bundle_constants.h" +#include "common_event_support.h" + +#include "bg_continuous_task_mgr.h" +#include "bgtaskmgr_inner_errors.h" +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +const std::string TASK_ON_BUNDLEINFO_CHANGED = "OnBundleInfoChanged"; +} + +SystemEventObserver::SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo) + : EventFwk::CommonEventSubscriber(subscribeInfo) +{} + +bool SystemEventObserver::Subscribe() +{ + BGTASK_LOGI("Subscribe called"); + + if (EventFwk::CommonEventManager::SubscribeCommonEvent(shared_from_this()) != true) { + BGTASK_LOGI("SubscribeCommonEvent occur exception."); + return false; + } + return true; +} + +bool SystemEventObserver::Unsubscribe() +{ + BGTASK_LOGI("UnSubscribe called"); + if (EventFwk::CommonEventManager::UnSubscribeCommonEvent(shared_from_this()) != true) { + BGTASK_LOGI("UnsubscribeCommonEvent occur exception."); + return false; + } + return true; +} + +void SystemEventObserver::SetEventHandler(const std::shared_ptr &handler) +{ + BGTASK_LOGI("set app state observer handler"); + handler_ = handler; +} + +void SystemEventObserver::SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr) +{ + BGTASK_LOGI("set app state oberver bgContinuousTaskMgr"); + bgContinuousTaskMgr_ = bgContinuousTaskMgr; +} + +void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + BGTASK_LOGI("OnReceiveEvent enter"); + auto handler = handler_.lock(); + if (!handler) { + BGTASK_LOGE("handler is null"); + return; + } + auto bgContinuousTaskMgr = bgContinuousTaskMgr_.lock(); + if (!bgContinuousTaskMgr) { + BGTASK_LOGE("bgContinuousTaskMgr is null"); + return; + } + AAFwk::Want want = eventData.GetWant(); + std::string action = want.GetAction(); + std::string bundleName = want.GetElement().GetBundleName(); + int uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); + BGTASK_LOGI("OnReceiveEvent action = %{public}s, bundle = %{public}s", action.c_str(), bundleName.c_str()); + auto task = [=]() { bgContinuousTaskMgr->OnBundleInfoChanged(action, bundleName, uid); }; + handler->PostTask(task, TASK_ON_BUNDLEINFO_CHANGED); +} +} +} \ No newline at end of file diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp new file mode 100644 index 00000000..7c360c32 --- /dev/null +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -0,0 +1,134 @@ +/* + * 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 "task_notification_subscriber.h" + +#include +#include + +#include "ohos/aafwk/base/string_wrapper.h" + +#include "bg_continuous_task_mgr.h" +#include "continuous_task_log.h" + + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static constexpr char LABEL_SPLITER[] = "_"; +static constexpr char NOTIFICATION_PREFIX[] = "bgmode"; +static constexpr uint32_t SYSTEM_UID = 1000; +static constexpr uint32_t LABEL_BGMODE_PREFIX_POS = 0; +static constexpr uint32_t LABEL_APP_UID_POS = 1; +static constexpr uint32_t LABEL_ABILITY_TOKEN_POS = 3; +static constexpr uint32_t LABEL_SIZE = 4; +} + +std::shared_ptr TaskNotificationSubscriber::continuousTaskMgr_ + = BgContinuousTaskMgr::GetInstance(); + +TaskNotificationSubscriber::TaskNotificationSubscriber() +{} + +TaskNotificationSubscriber::~TaskNotificationSubscriber() +{} + +void TaskNotificationSubscriber::OnConnected() +{} + +void TaskNotificationSubscriber::OnDisconnected() +{} + +void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification) +{} + +void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification, + const std::shared_ptr &sortingMap, int deleteReason) +{ + BGTASK_LOGI("notification cancel event triggered"); + if (notification == nullptr) { + BGTASK_LOGW("notification param is null"); + return; + } + Notification::NotificationRequest request = notification->GetNotificationRequest(); + if (request.GetCreatorUid() != SYSTEM_UID) { + return; + } + + // continuous task notification label is consisted of bgmode prefix, app uid, abilityName hash code, ability token. + std::string notificationLabel = request.GetLabel(); + std::vector labelSplits = StringSplit(notificationLabel, LABEL_SPLITER); + + if (labelSplits.empty() || labelSplits[LABEL_BGMODE_PREFIX_POS] != NOTIFICATION_PREFIX + || labelSplits.size() != LABEL_SIZE) { + BGTASK_LOGW("notification callback label is invalid"); + return; + } + + if (deleteReason == Notification::NotificationConstant::APP_CANCEL_REASON_DELETE) { + BGTASK_LOGI("notification remove action is already tiggered by cancel method."); + return; + } + + BGTASK_LOGI("stop continuous task by user, the label is : %{public}s", notificationLabel.c_str()); + std::shared_ptr extraInfo = request.GetAdditionalData(); + + if (extraInfo == nullptr) { + BGTASK_LOGI("notification extraInfo is null"); + return; + } + + std::string abilityName = AAFwk::String::Unbox(AAFwk::IString::Query(extraInfo->GetParam("abilityName"))); + std::string taskInfoMapKey = labelSplits[LABEL_APP_UID_POS] + LABEL_SPLITER + abilityName + + LABEL_SPLITER + labelSplits[LABEL_ABILITY_TOKEN_POS]; + + if (continuousTaskMgr_->StopContinuousTaskByUser(taskInfoMapKey)) { + BGTASK_LOGI("remove continuous task record Key: %{public}s", taskInfoMapKey.c_str()); + } +} + +void TaskNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification) +{} + +void TaskNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification, + const std::shared_ptr &sortingMap) +{} + +void TaskNotificationSubscriber::OnUpdate( + const std::shared_ptr &sortingMap) +{} + +void TaskNotificationSubscriber::OnDied() +{} + +void TaskNotificationSubscriber::OnDoNotDisturbDateChange( + const std::shared_ptr &date) +{} + +std::vector TaskNotificationSubscriber::StringSplit(const std::string &str, const char *delim) +{ + std::vector strlist; + char *saveptr = NULL; + char *p = const_cast(str.c_str()); + char *input = strdup(p); + while ((input = strtok_r(input, delim, &saveptr)) != NULL) { + strlist.emplace_back(input); + input = NULL; + } + free(input); + return strlist; +} +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/core/include/background_task_mgr_service.h b/services/core/include/background_task_mgr_service.h index edcdf06b..92cb51e7 100644 --- a/services/core/include/background_task_mgr_service.h +++ b/services/core/include/background_task_mgr_service.h @@ -29,6 +29,7 @@ #include "system_ability_definition.h" #include "background_task_mgr_stub.h" +#include "bg_continuous_task_mgr.h" #include "bg_transient_task_mgr.h" #include "bgtaskmgr_inner_errors.h" @@ -53,6 +54,8 @@ public: const sptr& callback, std::shared_ptr &delayInfo) override; ErrCode CancelSuspendDelay(int32_t requestId) override; ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) override; + ErrCode StartBackgroundRunning(const sptr taskParam) override; + ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken) override; ErrCode SubscribeBackgroundTask(const sptr& subscriber) override; ErrCode UnsubscribeBackgroundTask(const sptr& subscriber) override; ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) override; diff --git a/services/core/src/background_task_mgr_service.cpp b/services/core/src/background_task_mgr_service.cpp index 7b1f9894..593ecb5f 100644 --- a/services/core/src/background_task_mgr_service.cpp +++ b/services/core/src/background_task_mgr_service.cpp @@ -18,6 +18,7 @@ #include #include "ability_manager_client.h" +#include "bgtaskmgr_inner_errors.h" #include "bundle_constants.h" #include "common_event_manager.h" #include "common_event_support.h" @@ -28,6 +29,7 @@ namespace OHOS { namespace BackgroundTaskMgr { namespace { +static const std::string CONTINUOUS_TASK_DUMP = "-C"; static const std::string TRANSIENT_TASK_DUMP = "-T"; const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility( DelayedSingleton::GetInstance().get()); @@ -60,10 +62,12 @@ void BackgroundTaskMgrService::OnStart() void BackgroundTaskMgrService::Init() { DelayedSingleton::GetInstance()->Init(); + BgContinuousTaskMgr::GetInstance()->Init(); } void BackgroundTaskMgrService::OnStop() { + BgContinuousTaskMgr::GetInstance()->Clear(); state_ = ServiceRunningState::STATE_NOT_START; BGTASK_LOGI("background task manager stop"); } @@ -89,14 +93,31 @@ void BackgroundTaskMgrService::ForceCancelSuspendDelay(int32_t requestId) DelayedSingleton::GetInstance()->ForceCancelSuspendDelay(requestId); } +ErrCode BackgroundTaskMgrService::StartBackgroundRunning(const sptr taskParam) +{ + return BgContinuousTaskMgr::GetInstance()->StartBackgroundRunning(taskParam); +} + +ErrCode BackgroundTaskMgrService::StopBackgroundRunning(const std::string &abilityName, + const sptr &abilityToken) +{ + return BgContinuousTaskMgr::GetInstance()->StopBackgroundRunning(abilityName, abilityToken); +} + ErrCode BackgroundTaskMgrService::SubscribeBackgroundTask(const sptr& subscriber) { - return DelayedSingleton::GetInstance()->SubscribeBackgroundTask(subscriber); + ErrCode ret = ERR_OK; + ret = DelayedSingleton::GetInstance()->SubscribeBackgroundTask(subscriber); + ret = BgContinuousTaskMgr::GetInstance()->AddSubscriber(subscriber); + return ret; } ErrCode BackgroundTaskMgrService::UnsubscribeBackgroundTask(const sptr& subscriber) { - return DelayedSingleton::GetInstance()->UnsubscribeBackgroundTask(subscriber); + ErrCode ret = ERR_OK; + ret = DelayedSingleton::GetInstance()->UnsubscribeBackgroundTask(subscriber); + ret = BgContinuousTaskMgr::GetInstance()->RemoveSubscriber(subscriber); + return ret; } void BackgroundTaskMgrService::HandleRequestExpired(const int32_t requestId) @@ -120,6 +141,11 @@ ErrCode BackgroundTaskMgrService::ShellDump(const std::vector &dump ErrCode ret = ERR_OK; if (dumpOption[0] == TRANSIENT_TASK_DUMP) { ret = DelayedSingleton::GetInstance()->ShellDump(dumpOption, dumpInfo); + } else if (dumpOption[0] == CONTINUOUS_TASK_DUMP) { + ret = BgContinuousTaskMgr::GetInstance()->ShellDump(dumpOption, dumpInfo); + } else { + BGTASK_LOGI("invalid dump param"); + ret = ERR_BGTASK_INVALID_PARAM; } return ret; } diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 8475be68..0eb19e51 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -23,13 +23,19 @@ ohos_unittest("bgtask_unit_test") { "${bgtaskmgr_services_path}/transient_task/inlcude", "${bgtaskmgr_services_path}/core/inlcude", "${bgtaskmgr_interfaces_path}/innerkits/transient_task/include", + "//base/global/resmgr_standard/frameworks/resmgr/include", + "//third_party/icu/icu4c/source/i18n", ] sources = [ "background_task_mgr_service_test.cpp", + "bg_continuous_task_mgr_test.cpp", "bg_transient_task_mgr_test.cpp", + "mock/mock_bundle_manager_helper.cpp", "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", + "mock/mock_notification_helper.cpp", + "mock/mock_resource_manager.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -38,6 +44,8 @@ ohos_unittest("bgtask_unit_test") { "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", "${bgtaskmgr_services_path}:bgtaskmgr_service", + "//base/notification/ans_standard/frameworks/ans/core:ans_core", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//third_party/googletest:gtest_main", ] diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp new file mode 100644 index 00000000..0484c3d2 --- /dev/null +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -0,0 +1,184 @@ +/* + * 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 +#include +#include + +#include "gtest/gtest.h" + +#define private public + +#include "bgtaskmgr_inner_errors.h" +#include "background_task_subscriber.h" +#include "bg_continuous_task_mgr.h" +#include "want_agent.h" + +using namespace testing::ext; + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static constexpr int32_t SLEEP_TIME = 500; +} +class BgContinuousTaskMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + inline void SleepForFC() + { + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); + } + + static std::shared_ptr bgContinuousTaskMgr_; +}; + +std::shared_ptr BgContinuousTaskMgrTest::bgContinuousTaskMgr_ = nullptr; + +void BgContinuousTaskMgrTest::SetUpTestCase() +{ + bgContinuousTaskMgr_ = BgContinuousTaskMgr::GetInstance(); + bgContinuousTaskMgr_->Init(); +} + +void BgContinuousTaskMgrTest::TearDownTestCase() +{ + bgContinuousTaskMgr_->Clear(); + bgContinuousTaskMgr_ = nullptr; +} + +void BgContinuousTaskMgrTest::SetUp() +{} + +void BgContinuousTaskMgrTest::TearDown() +{ + std::vector dumpOption; + dumpOption.emplace_back("-C"); + dumpOption.emplace_back("--cancel_all"); + std::vector dumpInfo; + bgContinuousTaskMgr_->ShellDump(dumpOption, dumpInfo); +} + +class TestBackgroundTaskSubscriber : public BackgroundTaskSubscriber { +public: + virtual void OnContinuousTaskStart(const std::shared_ptr + &continuousTaskCallbackInfo) override + {} + + virtual void OnContinuousTaskStop(const std::shared_ptr + &continuousTaskCallbackInfo) override + {} +}; + +/** + * @tc.name: StartBackgroundRunning_001 + * @tc.desc: start background runnging use new api test. + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO + */ +HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_001, TestSize.Level1) +{ + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(nullptr), (int)ERR_BGTASK_INVALID_PARAM); + sptr taskParam = new ContinuousTaskParam(); + taskParam->isNewApi_ = true; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); + taskParam->wantAgent_ = std::make_shared(); + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); + taskParam->abilityName_ = ""; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); + taskParam->abilityName_ = "ability1"; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_BGMODE); + taskParam->bgModeId_ = 9; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_BGMODE); + taskParam->bgModeId_ = 2; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_BGMODE); + taskParam->bgModeId_ = 1; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_OK); +} + +/** + * @tc.name: StartBackgroundRunning_002 + * @tc.desc: start background runnging use old api test. + * @tc.type: FUNC + * @tc.require: AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 + */ +HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) +{ + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(nullptr), (int)ERR_BGTASK_INVALID_PARAM); + sptr taskParam = new ContinuousTaskParam(); + taskParam->isNewApi_ = false; + taskParam->bgModeId_ = 0; + taskParam->abilityName_ = ""; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); + taskParam->abilityName_ = "ability1"; + EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_OK); +} + +/** + * @tc.name: StopBackgroundRunning_001 + * @tc.desc: start background runnging use new api test. + * @tc.type: FUNC + * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K + */ +HWTEST_F(BgContinuousTaskMgrTest, StopBackgroundRunning_001, TestSize.Level1) +{ + sptr taskParam = new ContinuousTaskParam(); + taskParam->wantAgent_ = std::make_shared(); + taskParam->abilityName_ = "ability1"; + taskParam->bgModeId_ = 1; + EXPECT_EQ((int)bgContinuousTaskMgr_->StopBackgroundRunning("", nullptr), (int)ERR_BGTASK_INVALID_PARAM); + SleepForFC(); + EXPECT_EQ((int)bgContinuousTaskMgr_->StopBackgroundRunning("ability1", nullptr), (int)ERR_BGTASK_INVALID_PARAM); + SleepForFC(); + bgContinuousTaskMgr_->StartBackgroundRunning(taskParam); + SleepForFC(); + EXPECT_EQ((int)bgContinuousTaskMgr_->StopBackgroundRunning("ability1", nullptr), (int)ERR_OK); +} + +/** + * @tc.name: StartBackgroundRunning_001 + * @tc.desc: subscribe continuous task event callback test. + * @tc.type: FUNC + * @tc.require: AR000GH6EM AR000GH6G9 AR000GH6ET + */ +HWTEST_F(BgContinuousTaskMgrTest, SubscribeContinuousTask_001, TestSize.Level1) +{ + EXPECT_EQ((int)bgContinuousTaskMgr_->AddSubscriber(nullptr), (int)ERR_BGTASK_INVALID_PARAM); + SleepForFC(); + auto subscriber = new TestBackgroundTaskSubscriber(); + EXPECT_EQ((int)bgContinuousTaskMgr_->AddSubscriber(subscriber->GetImpl()), (int)ERR_OK); + SleepForFC(); + EXPECT_EQ((int)bgContinuousTaskMgr_->AddSubscriber(subscriber->GetImpl()), (int)ERR_BGTASK_OBJECT_EXISTS); +} + +/** + * @tc.name: UnsubscribeContinuousTask_001 + * @tc.desc: unsubscribe continuous task event callback test. + * @tc.type: FUNC + * @tc.require: AR000GH6EM AR000GH6G9 AR000GH6ET + */ +HWTEST_F(BgContinuousTaskMgrTest, UnsubscribeContinuousTask_001, TestSize.Level1) +{ + EXPECT_EQ((int)bgContinuousTaskMgr_->RemoveSubscriber(nullptr), (int)ERR_BGTASK_INVALID_PARAM); + SleepForFC(); + auto subscriber = new TestBackgroundTaskSubscriber(); + bgContinuousTaskMgr_->AddSubscriber(subscriber->GetImpl()); + SleepForFC(); + EXPECT_EQ((int)bgContinuousTaskMgr_->RemoveSubscriber(subscriber->GetImpl()), (int)ERR_OK); +} +} +} diff --git a/services/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/test/unittest/mock/mock_bundle_manager_helper.cpp new file mode 100644 index 00000000..032aa4aa --- /dev/null +++ b/services/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ability_info.h" +#include "bundle_info.h" +#include "bundle_manager_helper.h" + +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static constexpr char TEST_DEFAULT_BUNDLE[] = "bundleName"; +} + +BundleManagerHelper::BundleManagerHelper() +{} + +BundleManagerHelper::~BundleManagerHelper() +{} + +std::string BundleManagerHelper::GetClientBundleName(uid_t uid) +{ + return TEST_DEFAULT_BUNDLE; +} + +bool BundleManagerHelper::CheckPermission(const std::string &bundleName, + const std::string &permission) +{ + return true; +} + +bool BundleManagerHelper::IsSystemApp(uid_t uid) +{ + return true; +} + +bool BundleManagerHelper::GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, + AppExecFwk::BundleInfo &bundleInfo, int32_t userId) +{ + AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.name = "ability1"; + abilityInfo.backgroundModes = 1; + bundleInfo.abilityInfos.emplace_back(abilityInfo); + bundleInfo.name = TEST_DEFAULT_BUNDLE; + return true; +} + +bool BundleManagerHelper::Connect() +{ + return true; +} + +void BundleManagerHelper::Disconnect() +{} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{} +} +} \ No newline at end of file diff --git a/services/test/unittest/mock/mock_notification_helper.cpp b/services/test/unittest/mock/mock_notification_helper.cpp new file mode 100644 index 00000000..4611c313 --- /dev/null +++ b/services/test/unittest/mock/mock_notification_helper.cpp @@ -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. + */ + +#include "notification_helper.h" +#include "ans_notification.h" +#include "singleton.h" + +namespace OHOS { +namespace Notification { +ErrCode NotificationHelper::PublishContinuousTaskNotification(const NotificationRequest &request) +{ + return 0; +} + +ErrCode NotificationHelper::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) +{ + return 0; +} + +ErrCode NotificationHelper::SubscribeNotification(const NotificationSubscriber &subscriber) +{ + return 0; +} + +ErrCode NotificationHelper::SubscribeNotification( + const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo) +{ + return 0; +} + +ErrCode NotificationHelper::UnSubscribeNotification(NotificationSubscriber &subscriber) +{ + return 0; +} + +ErrCode NotificationHelper::UnSubscribeNotification( + NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo) +{ + return 0; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp new file mode 100644 index 00000000..68402953 --- /dev/null +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -0,0 +1,207 @@ +/* + * 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 "resource_manager_impl.h" + +namespace OHOS { +namespace Global { +namespace Resource { +ResourceManager *CreateResourceManager() +{ + ResourceManagerImpl *impl = new (std::nothrow) ResourceManagerImpl; + return impl; +} + +ResourceManager::~ResourceManager() +{} + +ResourceManagerImpl::ResourceManagerImpl() +{} + +ResourceManagerImpl::~ResourceManagerImpl() +{} + +bool ResourceManagerImpl::AddResource(const char *path) +{ + return true; +} + +RState ResourceManagerImpl::UpdateResConfig(ResConfig &resConfig) +{ + return SUCCESS; +} + +void ResourceManagerImpl::GetResConfig(ResConfig &resConfig) +{} + +RState ResourceManagerImpl::GetStringById(uint32_t id, std::string &outValue) +{ + outValue = "ENTRY"; + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringByName(const char *name, std::string &outValue) +{ + outValue = "bgmode_test"; + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringFormatById(std::string &outValue, uint32_t id, ...) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringFormatByName(std::string &outValue, const char *name, ...) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringArrayById(uint32_t id, std::vector &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetStringArrayByName(const char *name, std::vector &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPatternById(uint32_t id, std::map &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPatternByName(const char *name, std::map &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPluralStringById(uint32_t id, int quantity, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPluralStringByName(const char *name, int quantity, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPluralStringByIdFormat(std::string &outValue, uint32_t id, int quantity, ...) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetPluralStringByNameFormat(std::string &outValue, const char *name, int quantity, ...) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetThemeById(uint32_t id, std::map &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetThemeByName(const char *name, std::map &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetBooleanById(uint32_t id, bool &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetBooleanByName(const char *name, bool &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetIntegerById(uint32_t id, int &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetIntegerByName(const char *name, int &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetFloatById(uint32_t id, float &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetFloatById(uint32_t id, float &outValue, std::string &unit) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetFloatByName(const char *name, float &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetFloatByName(const char *name, float &outValue, std::string &unit) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetIntArrayById(uint32_t id, std::vector &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetIntArrayByName(const char *name, std::vector &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetColorById(uint32_t id, uint32_t &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetColorByName(const char *name, uint32_t &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetProfileById(uint32_t id, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetProfileByName(const char *name, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetMediaById(uint32_t id, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetMediaByName(const char *name, std::string &outValue) +{ + return SUCCESS; +} + +RState ResourceManagerImpl::GetRawFilePathByName(const std::string &name, std::string &outValue) +{ + return SUCCESS; +} +} +} +} \ No newline at end of file diff --git a/test/systemtest/bgtask_dump_test.cpp b/test/systemtest/bgtask_dump_test.cpp index 8c12dc03..80de86a4 100644 --- a/test/systemtest/bgtask_dump_test.cpp +++ b/test/systemtest/bgtask_dump_test.cpp @@ -90,5 +90,23 @@ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_001, Function | MediumTest | L EXPECT_EQ(ret, 0); } } + +/* + * @tc.name: BgtaskDumpTest_ShellDump_002 + * @tc.desc: Shell dump + * @tc.type: FUNC + * @tc.require: AR000GH6EQ + */ +HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_002, Function | MediumTest | Level0) +{ + std::vector infos; + std::vector options; + options.push_back("-C"); + options.push_back("--all"); + if (bgtaskMgr_ != nullptr) { + auto ret = bgtaskMgr_->ShellDump(options, infos); + EXPECT_EQ(ret, 0); + } +} } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/utils/BUILD.gn b/utils/BUILD.gn index dd79d914..3218c9d5 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -16,4 +16,5 @@ import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") group("bgtaskmgr_dump") { deps = [ "dump:btm_target" ] + deps += [ "bgtask_observer:bgtask_observer_target" ] } diff --git a/utils/bgtask_observer/BUILD.gn b/utils/bgtask_observer/BUILD.gn new file mode 100644 index 00000000..7f7c33c2 --- /dev/null +++ b/utils/bgtask_observer/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") + +group("bgtask_observer_target") { + deps = [ ":bgtask_observer" ] +} + +ohos_executable("bgtask_observer") { + include_dirs = [ "include" ] + + sources = [ + "src/bgtask_observer.cpp", + "src/main.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", + "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + ] + + configs = [] + + external_deps = [ + "ability_runtime:want", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + "utils_base:utils", + ] + + install_enable = false + part_name = "background_task_mgr" +} diff --git a/utils/bgtask_observer/include/bgtask_observer.h b/utils/bgtask_observer/include/bgtask_observer.h new file mode 100644 index 00000000..79eccba1 --- /dev/null +++ b/utils/bgtask_observer/include/bgtask_observer.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_UTILS_BGTASK_OBSERVER_INCLUDE_BGTASK_OBSERVER_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_UTILS_BGTASK_OBSERVER_INCLUDE_BGTASK_OBSERVER_H + +#include "background_task_mgr_helper.h" +#include "background_task_subscriber.h" +#include "iremote_object.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class BgTaskObserver : public OHOS::BackgroundTaskMgr::BackgroundTaskSubscriber { +public: + virtual void OnContinuousTaskStart(const std::shared_ptr + &continuousTaskCallbackInfo) override; + + virtual void OnContinuousTaskStop(const std::shared_ptr + &continuousTaskCallbackInfo) override; + + virtual void OnRemoteDied(const wptr &object) override; + + std::atomic isRemoteDied_ {false}; +}; +} +} +#endif \ No newline at end of file diff --git a/utils/bgtask_observer/src/bgtask_observer.cpp b/utils/bgtask_observer/src/bgtask_observer.cpp new file mode 100644 index 00000000..a8e7d707 --- /dev/null +++ b/utils/bgtask_observer/src/bgtask_observer.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bgtask_observer.h" + +#include + +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +void BgTaskObserver::OnContinuousTaskStart(const std::shared_ptr &continuousTaskCallbackInfo) +{ + BGTASK_LOGI("Continuous Task Start"); + std::stringstream stream; + int32_t typeId = continuousTaskCallbackInfo->GetTypeId(); + uid_t uid = continuousTaskCallbackInfo->GetCreatorUid(); + pid_t pid = continuousTaskCallbackInfo->GetCreatorPid(); + std::string abiliytName = continuousTaskCallbackInfo->GetAbilityName(); + stream.str(""); + stream.clear(); + stream << "Continuous Task Start:" << "\n"; + stream << "\ttask typeId: " << typeId << "\n"; + stream << "\ttask uid: " << uid << "\n"; + stream << "\ttask pid: " << pid << "\n"; + stream << "\ttask abiliytName: " << abiliytName << "\n"; + + std::cout << stream.str() << std::endl; +} + +void BgTaskObserver::OnContinuousTaskStop(const std::shared_ptr &continuousTaskCallbackInfo) +{ + BGTASK_LOGI("Continuous Task Stop"); + std::stringstream stream; + int32_t typeId = continuousTaskCallbackInfo->GetTypeId(); + uid_t uid = continuousTaskCallbackInfo->GetCreatorUid(); + pid_t pid = continuousTaskCallbackInfo->GetCreatorPid(); + std::string abiliytName = continuousTaskCallbackInfo->GetAbilityName(); + stream.str(""); + stream.clear(); + stream << "Continuous Task Stop:" << "\n"; + stream << "\ttask typeId: " << typeId << "\n"; + stream << "\ttask uid: " << uid << "\n"; + stream << "\ttask pid: " << pid << "\n"; + stream << "\ttask abiliytName: " << abiliytName << "\n"; + + std::cout << stream.str() << std::endl; +} + +void BgTaskObserver::OnRemoteDied(const wptr &object) +{ + BGTASK_LOGI("remote service died"); + isRemoteDied_.store(true); +} +} +} \ No newline at end of file diff --git a/utils/bgtask_observer/src/main.cpp b/utils/bgtask_observer/src/main.cpp new file mode 100644 index 00000000..6291bc13 --- /dev/null +++ b/utils/bgtask_observer/src/main.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "background_task_mgr_helper.h" +#include "background_task_subscriber.h" +#include "bgtask_observer.h" + +namespace { +static constexpr int32_t DELAY_TIME = 1000; +static constexpr int32_t MAX_CHAR_NUMS = 100; + +void CycleTest() +{ + auto bgtaskObserver = std::make_shared(); + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver) + == OHOS::ERR_OK) { + std::cout << "register succeed in cycletest" << std::endl; + } + while (true) { + if (bgtaskObserver->isRemoteDied_.load()) { + std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_TIME)); + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver) + == OHOS::ERR_OK) { + std::cout << "try to subscribe again succeed" << std::endl; + bgtaskObserver->isRemoteDied_.store(false); + } + } + } +} + +void PatchTest(int nums) +{ + std::list> observerList; + for (int i = 0; i < nums; i++) { + auto bgtaskObserver = std::make_shared(); + observerList.emplace_back(bgtaskObserver); + } + + int index = 1; + for (auto observer : observerList) { + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*observer) + == OHOS::ERR_OK) { + std::cout << "register succeed No." << index << std::endl; + } + index++; + } + std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_TIME)); + index = 1; + for (auto observer : observerList) { + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*observer) + == OHOS::ERR_OK) { + std::cout << "unregister succeed No." << index << std::endl; + } + index++; + } +} +} + +int main(int argc, char *argv[]) +{ + auto bgtaskObserver = std::make_shared(); + char command[MAX_CHAR_NUMS]; + int nums; + while (std::cin >> command >> nums) { + std::string commandStr = command; + if (commandStr == "register") { + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver) + == OHOS::ERR_OK) { + std::cout << "register once succeed" << std::endl; + } + } + if (commandStr == "unregister") { + if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*bgtaskObserver) + == OHOS::ERR_OK) { + std::cout << "unregister once succeed" << std::endl; + } + } + if (commandStr == "patchtest") { + PatchTest(nums); + } + if (commandStr == "cycletest") { + CycleTest(); + } + } + return 0; +} \ No newline at end of file diff --git a/utils/dump/src/bgtaskmgr_shell_command.cpp b/utils/dump/src/bgtaskmgr_shell_command.cpp index 3e6a44dd..2845c1f5 100644 --- a/utils/dump/src/bgtaskmgr_shell_command.cpp +++ b/utils/dump/src/bgtaskmgr_shell_command.cpp @@ -28,9 +28,11 @@ namespace OHOS { namespace BackgroundTaskMgr { namespace { +static constexpr int32_t MIN_CONTINUOUS_TASK_DUMP_PARAMS_NUM = 4; static const struct option OPTIONS[] = { {"help", no_argument, nullptr, 'h'}, {"transient", no_argument, nullptr, 'T'}, + {"continuous", no_argument, nullptr, 'C'}, }; static const std::string HELP_MSG = "usage: bgtask []\n" @@ -47,7 +49,10 @@ static const std::string DUMP_HELP_MSG = " SCREEN_ON sreen on mode\n" " SCREEN_OFF sreen off mode\n" " DUMP_CANCEL cancel dump mode\n" - " All list all request\n"; + " All list all request\n" + " -C, --all list all running continuous task infos\n" + " --cancel_all cancel all running continuous task\n" + " --cancel cancel one task by specifying task key\n"; } // namespace BgtaskmgrShellCommand::BgtaskmgrShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "bgtask") @@ -95,7 +100,7 @@ ErrCode BgtaskmgrShellCommand::RunAsHelpCommand() ErrCode BgtaskmgrShellCommand::RunAsDumpCommand() { int ind = 0; - int option = getopt_long(argc_, argv_, "hT", OPTIONS, &ind); + int option = getopt_long(argc_, argv_, "hTC", OPTIONS, &ind); ErrCode ret = ERR_OK; if (btm_ == nullptr) { @@ -112,6 +117,14 @@ ErrCode BgtaskmgrShellCommand::RunAsDumpCommand() ret = btm_->ShellDump(argList_, infos); } break; + case 'C': + if (argc_ < MIN_CONTINUOUS_TASK_DUMP_PARAMS_NUM || btm_ == nullptr) { + resultReceiver_.append(DUMP_HELP_MSG); + ret = ERR_BGTASK_SERVICE_NOT_CONNECTED; + break; + } + ret = btm_->ShellDump(argList_, infos); + break; default: resultReceiver_.append("Please input correct command!\n"); resultReceiver_.append(DUMP_HELP_MSG); -- Gitee From 8b90c686350cf597b2b62e8504a195913b0ba590 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 08:49:19 +0800 Subject: [PATCH 26/77] bugfix for notification prompt init failed Signed-off-by: zhangxin_T --- .../include/bg_continuous_task_mgr.h | 2 ++ .../src/bg_continuous_task_mgr.cpp | 20 ++++++++++++++----- services/test/unittest/BUILD.gn | 1 + 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index 562e24d6..30d11de1 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -74,6 +74,8 @@ public: void InitNecessaryState(); + void InitNotificationPrompt(); + void Clear(); private: diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index c94ba645..1214b5b0 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -86,8 +86,8 @@ bool BgContinuousTaskMgr::Init() BGTASK_LOGE("BgContinuousTaskMgr handler create failed!"); return false; } - auto task = [this]() { this->InitNecessaryState(); }; - handler_->PostSyncTask(task); + auto registerTask = [this]() { this->InitNecessaryState(); }; + handler_->PostSyncTask(registerTask); return true; } @@ -130,11 +130,21 @@ void BgContinuousTaskMgr::InitNecessaryState() BGTASK_LOGE("RegisterSysCommEventListener failed"); isInitSucceed = false; } + if (isInitSucceed) { + auto getPromptTask = [this]() { this->InitNotificationPrompt(); }; + handler_->PostTask(getPromptTask, DELAY_TIME); + } +} + +void BgContinuousTaskMgr::InitNotificationPrompt() { if (!GetContinuousTaskText()) { - BGTASK_LOGE("GetContinuousTaskText failed"); - isInitSucceed = false; + BGTASK_LOGW("init continuous task notification prompt failed. will try again"); + isSysReady_.store(false); + auto task = [this]() { this->InitNotificationPrompt(); }; + handler_->PostTask(task, DELAY_TIME); + return; } - isSysReady_.store(isInitSucceed); + isSysReady_.store(true); } bool BgContinuousTaskMgr::RegisterNotificationSubscriber() diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 0eb19e51..10c6c533 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("bgtask_unit_test") { "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_image_standard:image_native", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "utils_base:utils", -- Gitee From 47d5c459889854c22b477c7462db92fd18cf81a8 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 11:57:54 +0800 Subject: [PATCH 27/77] add new api ability token and codeCheck bugfix Signed-off-by: zhangxin_T --- frameworks/include/ibackground_task_mgr.h | 8 ++--- .../include/continuous_task_callback_info.h | 8 ++--- .../src/background_task_subscriber.cpp | 24 +++++-------- .../src/continuous_task_callback_info.cpp | 14 ++++---- interfaces/innerkits/src/expired_callback.cpp | 3 +- .../src/bg_continuous_task_napi_module.cpp | 18 ++++++++-- .../kits/napi/src/request_suspend_delay.cpp | 3 +- .../src/bg_continuous_task_mgr.cpp | 9 +++-- .../src/continuous_task_record.cpp | 3 +- .../src/system_event_observer.cpp | 3 +- .../src/task_notification_subscriber.cpp | 30 ++++++---------- .../core/src/background_task_mgr_service.cpp | 6 ++-- .../unittest/bg_continuous_task_mgr_test.cpp | 9 ++--- .../unittest/bg_transient_task_mgr_test.cpp | 6 ++-- .../mock/mock_bundle_manager_helper.cpp | 12 +++---- .../test/unittest/mock/mock_event_handler.cpp | 36 +++++++------------ .../unittest/mock/mock_resource_manager.cpp | 12 +++---- test/systemtest/bgtask_dump_test.cpp | 9 ++--- utils/dump/src/bgtaskmgr_shell_command.cpp | 3 +- utils/dump/src/shell_command.cpp | 3 +- 20 files changed, 88 insertions(+), 131 deletions(-) diff --git a/frameworks/include/ibackground_task_mgr.h b/frameworks/include/ibackground_task_mgr.h index 256f9cf9..79d974d6 100644 --- a/frameworks/include/ibackground_task_mgr.h +++ b/frameworks/include/ibackground_task_mgr.h @@ -39,13 +39,13 @@ public: virtual ErrCode RequestSuspendDelay(const std::u16string& reason, const sptr& callback, std::shared_ptr &delayInfo) = 0; - virtual ErrCode CancelSuspendDelay(int32_t requestId) = 0; + virtual ErrCode CancelSuspendDelay(int32_t requestId) = 0; virtual ErrCode GetRemainingDelayTime(int32_t requestId, int32_t &delayTime) = 0; virtual ErrCode StartBackgroundRunning(const sptr taskParam) = 0; virtual ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken) = 0; - virtual ErrCode SubscribeBackgroundTask(const sptr& subscriber) = 0; - virtual ErrCode UnsubscribeBackgroundTask(const sptr& subscriber) = 0; - virtual ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) = 0; + virtual ErrCode SubscribeBackgroundTask(const sptr &subscriber) = 0; + virtual ErrCode UnsubscribeBackgroundTask(const sptr &subscriber) = 0; + virtual ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) = 0; public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.resourceschedule.IBackgroundTaskMgr"); diff --git a/interfaces/innerkits/include/continuous_task_callback_info.h b/interfaces/innerkits/include/continuous_task_callback_info.h index da802a89..cae9910e 100644 --- a/interfaces/innerkits/include/continuous_task_callback_info.h +++ b/interfaces/innerkits/include/continuous_task_callback_info.h @@ -27,10 +27,10 @@ public: ContinuousTaskCallbackInfo(); ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, pid_t creatorPid, std::string abilityName); - int32_t GetTypeId(); - uid_t GetCreatorUid(); - pid_t GetCreatorPid(); - std::string GetAbilityName(); + int32_t GetTypeId() const; + uid_t GetCreatorUid() const; + pid_t GetCreatorPid() const; + std::string GetAbilityName() const; bool Marshalling(Parcel &parcel) const; static ContinuousTaskCallbackInfo *Unmarshalling(Parcel &parcel); diff --git a/interfaces/innerkits/src/background_task_subscriber.cpp b/interfaces/innerkits/src/background_task_subscriber.cpp index b0c2459f..ad56a6f9 100644 --- a/interfaces/innerkits/src/background_task_subscriber.cpp +++ b/interfaces/innerkits/src/background_task_subscriber.cpp @@ -25,31 +25,23 @@ BackgroundTaskSubscriber::BackgroundTaskSubscriber() impl_ = new BackgroundTaskSubscriberImpl(*this); }; -BackgroundTaskSubscriber::~BackgroundTaskSubscriber() -{} +BackgroundTaskSubscriber::~BackgroundTaskSubscriber() {} -void BackgroundTaskSubscriber::OnConnected() -{} +void BackgroundTaskSubscriber::OnConnected() {} -void BackgroundTaskSubscriber::OnDisconnected() -{} +void BackgroundTaskSubscriber::OnDisconnected() {} -void BackgroundTaskSubscriber::OnTransientTaskStart(const std::shared_ptr& info) -{} +void BackgroundTaskSubscriber::OnTransientTaskStart(const std::shared_ptr& info) {} -void BackgroundTaskSubscriber::OnTransientTaskEnd(const std::shared_ptr& info) -{} +void BackgroundTaskSubscriber::OnTransientTaskEnd(const std::shared_ptr& info) {} void BackgroundTaskSubscriber::OnContinuousTaskStart( - const std::shared_ptr &continuousTaskCallbackInfo) -{} + const std::shared_ptr &continuousTaskCallbackInfo) {} void BackgroundTaskSubscriber::OnContinuousTaskStop( - const std::shared_ptr &continuousTaskCallbackInfo) -{} + const std::shared_ptr &continuousTaskCallbackInfo) {} -void BackgroundTaskSubscriber::OnRemoteDied(const wptr &object) -{} +void BackgroundTaskSubscriber::OnRemoteDied(const wptr &object) {} const sptr BackgroundTaskSubscriber::GetImpl() const { diff --git a/interfaces/innerkits/src/continuous_task_callback_info.cpp b/interfaces/innerkits/src/continuous_task_callback_info.cpp index 15efab7f..c70d99dd 100644 --- a/interfaces/innerkits/src/continuous_task_callback_info.cpp +++ b/interfaces/innerkits/src/continuous_task_callback_info.cpp @@ -18,30 +18,28 @@ namespace OHOS { namespace BackgroundTaskMgr { -ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo() -{} +ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo() {} ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, pid_t creatorPid, std::string abilityName) - : typeId_(typeId), creatorUid_(creatorUid), creatorPid_(creatorPid), abilityName_(abilityName) -{} + : typeId_(typeId), creatorUid_(creatorUid), creatorPid_(creatorPid), abilityName_(abilityName) {} -int32_t ContinuousTaskCallbackInfo::GetTypeId() +int32_t ContinuousTaskCallbackInfo::GetTypeId() const { return typeId_; } -uid_t ContinuousTaskCallbackInfo::GetCreatorUid() +uid_t ContinuousTaskCallbackInfo::GetCreatorUid() const { return creatorUid_; } -pid_t ContinuousTaskCallbackInfo::GetCreatorPid() +pid_t ContinuousTaskCallbackInfo::GetCreatorPid() const { return creatorPid_; } -std::string ContinuousTaskCallbackInfo::GetAbilityName() +std::string ContinuousTaskCallbackInfo::GetAbilityName() const { return abilityName_; } diff --git a/interfaces/innerkits/src/expired_callback.cpp b/interfaces/innerkits/src/expired_callback.cpp index a7a43225..239f158d 100644 --- a/interfaces/innerkits/src/expired_callback.cpp +++ b/interfaces/innerkits/src/expired_callback.cpp @@ -22,8 +22,7 @@ ExpiredCallback::ExpiredCallback() impl_ = new ExpiredCallbackImpl(*this); }; -ExpiredCallback::~ExpiredCallback() -{} +ExpiredCallback::~ExpiredCallback() {} const sptr ExpiredCallback::GetImpl() const { diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp index 630d32b5..ff0b4e4d 100644 --- a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -144,6 +144,13 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) return; } + sptr token {nullptr}; + auto abilityContext = asyncCallbackInfo->ability->GetAbilityContext(); + if (abilityContext) { + BGTASK_LOGI("get ability context succeed"); + token = abilityContext->GetToken(); + } + if (asyncCallbackInfo->bgMode < BG_MODE_ID_BEGIN || asyncCallbackInfo->bgMode > BG_MODE_ID_END) { BGTASK_LOGE("request background mode id: %{public}d out of range", asyncCallbackInfo->bgMode); asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; @@ -151,7 +158,7 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) } ContinuousTaskParam taskParam = ContinuousTaskParam(true, asyncCallbackInfo->bgMode, - std::make_shared(*asyncCallbackInfo->wantAgent), info->name, nullptr); + std::make_shared(*asyncCallbackInfo->wantAgent), info->name, token); asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam); BGTASK_LOGI("end"); @@ -356,7 +363,14 @@ void StopBackgroundRunningExecuteCB(napi_env env, void *data) asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; return; } - asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStopBackgroundRunning(info->name, nullptr); + + sptr token {nullptr}; + auto abilityContext = asyncCallbackInfo->ability->GetAbilityContext(); + if (abilityContext) { + BGTASK_LOGI("get ability context succeed"); + token = abilityContext->GetToken(); + } + asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStopBackgroundRunning(info->name, token); } napi_value StopBackgroundRunningAsync(napi_env env, napi_value *argv, diff --git a/interfaces/kits/napi/src/request_suspend_delay.cpp b/interfaces/kits/napi/src/request_suspend_delay.cpp index 3d5bed19..865a97e2 100644 --- a/interfaces/kits/napi/src/request_suspend_delay.cpp +++ b/interfaces/kits/napi/src/request_suspend_delay.cpp @@ -24,8 +24,7 @@ namespace OHOS { namespace BackgroundTaskMgr { static const int32_t REQUEST_SUSPEND_DELAY_PARAMS = 2; -CallbackInstance::CallbackInstance() -{} +CallbackInstance::CallbackInstance() {} CallbackInstance::~CallbackInstance() { diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 1214b5b0..cd27e6e5 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -68,11 +68,9 @@ static constexpr uint32_t BG_MODE_INDEX_HEAD = 1; static constexpr int BGMODE_NUMS = 10; } -BgContinuousTaskMgr::BgContinuousTaskMgr() -{} +BgContinuousTaskMgr::BgContinuousTaskMgr() {} -BgContinuousTaskMgr::~BgContinuousTaskMgr() -{} +BgContinuousTaskMgr::~BgContinuousTaskMgr() {} bool BgContinuousTaskMgr::Init() { @@ -136,7 +134,8 @@ void BgContinuousTaskMgr::InitNecessaryState() } } -void BgContinuousTaskMgr::InitNotificationPrompt() { +void BgContinuousTaskMgr::InitNotificationPrompt() +{ if (!GetContinuousTaskText()) { BGTASK_LOGW("init continuous task notification prompt failed. will try again"); isSysReady_.store(false); diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index a3bfa181..1f66de05 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -36,8 +36,7 @@ ContinuousTaskRecord::ContinuousTaskRecord(const std::string &bundleName, const const std::shared_ptr &wantAgent, const sptr &abilityToken, int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi) : bundleName_(bundleName), abilityName_(abilityName), wantAgent_(wantAgent), abilityToken_(abilityToken), - userId_(userId), uid_(uid), pid_(pid), bgModeId_(bgModeId), isNewApi_(isNewApi) -{} + userId_(userId), uid_(uid), pid_(pid), bgModeId_(bgModeId), isNewApi_(isNewApi) {} std::string ContinuousTaskRecord::GetBundleName() const { diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp index 0f36f44f..92d4987d 100644 --- a/services/continuous_task/src/system_event_observer.cpp +++ b/services/continuous_task/src/system_event_observer.cpp @@ -29,8 +29,7 @@ const std::string TASK_ON_BUNDLEINFO_CHANGED = "OnBundleInfoChanged"; } SystemEventObserver::SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo) - : EventFwk::CommonEventSubscriber(subscribeInfo) -{} + : EventFwk::CommonEventSubscriber(subscribeInfo) {} bool SystemEventObserver::Subscribe() { diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index 7c360c32..d8ee070b 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -39,20 +39,15 @@ static constexpr uint32_t LABEL_SIZE = 4; std::shared_ptr TaskNotificationSubscriber::continuousTaskMgr_ = BgContinuousTaskMgr::GetInstance(); -TaskNotificationSubscriber::TaskNotificationSubscriber() -{} +TaskNotificationSubscriber::TaskNotificationSubscriber() {} -TaskNotificationSubscriber::~TaskNotificationSubscriber() -{} +TaskNotificationSubscriber::~TaskNotificationSubscriber() {} -void TaskNotificationSubscriber::OnConnected() -{} +void TaskNotificationSubscriber::OnConnected() {} -void TaskNotificationSubscriber::OnDisconnected() -{} +void TaskNotificationSubscriber::OnDisconnected() {} -void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification) -{} +void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification) {} void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification, const std::shared_ptr &sortingMap, int deleteReason) @@ -99,23 +94,18 @@ void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr ¬ification) -{} +void TaskNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification) {} void TaskNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification, - const std::shared_ptr &sortingMap) -{} + const std::shared_ptr &sortingMap) {} void TaskNotificationSubscriber::OnUpdate( - const std::shared_ptr &sortingMap) -{} + const std::shared_ptr &sortingMap) {} -void TaskNotificationSubscriber::OnDied() -{} +void TaskNotificationSubscriber::OnDied() {} void TaskNotificationSubscriber::OnDoNotDisturbDateChange( - const std::shared_ptr &date) -{} + const std::shared_ptr &date) {} std::vector TaskNotificationSubscriber::StringSplit(const std::string &str, const char *delim) { diff --git a/services/core/src/background_task_mgr_service.cpp b/services/core/src/background_task_mgr_service.cpp index 593ecb5f..85386396 100644 --- a/services/core/src/background_task_mgr_service.cpp +++ b/services/core/src/background_task_mgr_service.cpp @@ -36,11 +36,9 @@ const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility( } BackgroundTaskMgrService::BackgroundTaskMgrService() - : SystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID, true) -{} + : SystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID, true) {} -BackgroundTaskMgrService::~BackgroundTaskMgrService() -{} +BackgroundTaskMgrService::~BackgroundTaskMgrService() {} void BackgroundTaskMgrService::OnStart() { diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp index 0484c3d2..0e8f106e 100644 --- a/services/test/unittest/bg_continuous_task_mgr_test.cpp +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -61,8 +61,7 @@ void BgContinuousTaskMgrTest::TearDownTestCase() bgContinuousTaskMgr_ = nullptr; } -void BgContinuousTaskMgrTest::SetUp() -{} +void BgContinuousTaskMgrTest::SetUp() {} void BgContinuousTaskMgrTest::TearDown() { @@ -76,12 +75,10 @@ void BgContinuousTaskMgrTest::TearDown() class TestBackgroundTaskSubscriber : public BackgroundTaskSubscriber { public: virtual void OnContinuousTaskStart(const std::shared_ptr - &continuousTaskCallbackInfo) override - {} + &continuousTaskCallbackInfo) override {} virtual void OnContinuousTaskStop(const std::shared_ptr - &continuousTaskCallbackInfo) override - {} + &continuousTaskCallbackInfo) override {} }; /** diff --git a/services/test/unittest/bg_transient_task_mgr_test.cpp b/services/test/unittest/bg_transient_task_mgr_test.cpp index ada0fe80..188d9e05 100644 --- a/services/test/unittest/bg_transient_task_mgr_test.cpp +++ b/services/test/unittest/bg_transient_task_mgr_test.cpp @@ -27,10 +27,8 @@ namespace OHOS { namespace BackgroundTaskMgr { class TestBackgroundTaskSubscriber : public BackgroundTaskSubscriber { public: - void OnTransientTaskStart(const std::shared_ptr& info) override - {} - void OnTransientTaskEnd(const std::shared_ptr& info) override - {} + void OnTransientTaskStart(const std::shared_ptr& info) override {} + void OnTransientTaskEnd(const std::shared_ptr& info) override {} }; class BgTransientTaskMgrTest : public testing::Test { diff --git a/services/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/test/unittest/mock/mock_bundle_manager_helper.cpp index 032aa4aa..00cfa133 100644 --- a/services/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -25,11 +25,9 @@ namespace { static constexpr char TEST_DEFAULT_BUNDLE[] = "bundleName"; } -BundleManagerHelper::BundleManagerHelper() -{} +BundleManagerHelper::BundleManagerHelper() {} -BundleManagerHelper::~BundleManagerHelper() -{} +BundleManagerHelper::~BundleManagerHelper() {} std::string BundleManagerHelper::GetClientBundleName(uid_t uid) { @@ -63,10 +61,8 @@ bool BundleManagerHelper::Connect() return true; } -void BundleManagerHelper::Disconnect() -{} +void BundleManagerHelper::Disconnect() {} -void BundleManagerHelper::OnRemoteDied(const wptr &object) -{} +void BundleManagerHelper::OnRemoteDied(const wptr &object) {} } } \ No newline at end of file diff --git a/services/test/unittest/mock/mock_event_handler.cpp b/services/test/unittest/mock/mock_event_handler.cpp index e317c0c5..94d094c7 100644 --- a/services/test/unittest/mock/mock_event_handler.cpp +++ b/services/test/unittest/mock/mock_event_handler.cpp @@ -23,11 +23,9 @@ std::shared_ptr EventHandler::Current() return wp.lock(); } -EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) -{} +EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) {} -EventHandler::~EventHandler() -{} +EventHandler::~EventHandler() {} bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Priority priority) { @@ -48,17 +46,13 @@ bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) return true; } -void EventHandler::RemoveAllEvents() -{} +void EventHandler::RemoveAllEvents() {} -void EventHandler::RemoveEvent(uint32_t innerEventId) -{} +void EventHandler::RemoveEvent(uint32_t innerEventId) {} -void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) -{} +void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) {} -void EventHandler::RemoveTask(const std::string &name) -{} +void EventHandler::RemoveTask(const std::string &name) {} ErrCode EventHandler::AddFileDescriptorListener( int32_t fileDescriptor, uint32_t events, const std::shared_ptr &listener) @@ -66,20 +60,15 @@ ErrCode EventHandler::AddFileDescriptorListener( return EVENT_HANDLER_ERR_INVALID_PARAM; } -void EventHandler::RemoveAllFileDescriptorListeners() -{} +void EventHandler::RemoveAllFileDescriptorListeners() {} -void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) -{} +void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) {} -void EventHandler::SetEventRunner(const std::shared_ptr &runner) -{} +void EventHandler::SetEventRunner(const std::shared_ptr &runner) {} -void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) -{} +void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) {} -void EventHandler::Dump(Dumper &dumper) -{} +void EventHandler::Dump(Dumper &dumper) {} bool EventHandler::HasInnerEvent(uint32_t innerEventId) { @@ -101,7 +90,6 @@ bool EventHandler::IsIdle() return true; } -void EventHandler::ProcessEvent(const InnerEvent::Pointer &) -{} +void EventHandler::ProcessEvent(const InnerEvent::Pointer &) {} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp index 68402953..eb3fb0a2 100644 --- a/services/test/unittest/mock/mock_resource_manager.cpp +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -24,14 +24,11 @@ ResourceManager *CreateResourceManager() return impl; } -ResourceManager::~ResourceManager() -{} +ResourceManager::~ResourceManager() {} -ResourceManagerImpl::ResourceManagerImpl() -{} +ResourceManagerImpl::ResourceManagerImpl() {} -ResourceManagerImpl::~ResourceManagerImpl() -{} +ResourceManagerImpl::~ResourceManagerImpl() {} bool ResourceManagerImpl::AddResource(const char *path) { @@ -43,8 +40,7 @@ RState ResourceManagerImpl::UpdateResConfig(ResConfig &resConfig) return SUCCESS; } -void ResourceManagerImpl::GetResConfig(ResConfig &resConfig) -{} +void ResourceManagerImpl::GetResConfig(ResConfig &resConfig) {} RState ResourceManagerImpl::GetStringById(uint32_t id, std::string &outValue) { diff --git a/test/systemtest/bgtask_dump_test.cpp b/test/systemtest/bgtask_dump_test.cpp index 80de86a4..e1f7c70b 100644 --- a/test/systemtest/bgtask_dump_test.cpp +++ b/test/systemtest/bgtask_dump_test.cpp @@ -40,11 +40,9 @@ public: std::shared_ptr bgtaskMgr_; }; -void BgtaskDumpTest::SetUpTestCase() -{} +void BgtaskDumpTest::SetUpTestCase() {} -void BgtaskDumpTest::TearDownTestCase() -{} +void BgtaskDumpTest::TearDownTestCase() {} void BgtaskDumpTest::SetUp() { @@ -53,8 +51,7 @@ void BgtaskDumpTest::SetUp() } } -void BgtaskDumpTest::TearDown() -{} +void BgtaskDumpTest::TearDown() {} /* * @tc.name: BgtaskDumpTest_GetServiceObject_001 diff --git a/utils/dump/src/bgtaskmgr_shell_command.cpp b/utils/dump/src/bgtaskmgr_shell_command.cpp index 2845c1f5..ea908c7c 100644 --- a/utils/dump/src/bgtaskmgr_shell_command.cpp +++ b/utils/dump/src/bgtaskmgr_shell_command.cpp @@ -55,8 +55,7 @@ static const std::string DUMP_HELP_MSG = " --cancel cancel one task by specifying task key\n"; } // namespace -BgtaskmgrShellCommand::BgtaskmgrShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "bgtask") -{} +BgtaskmgrShellCommand::BgtaskmgrShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, "bgtask") {} ErrCode BgtaskmgrShellCommand::CreateCommandMap() { diff --git a/utils/dump/src/shell_command.cpp b/utils/dump/src/shell_command.cpp index afb6ab4e..2a9c4d93 100644 --- a/utils/dump/src/shell_command.cpp +++ b/utils/dump/src/shell_command.cpp @@ -37,8 +37,7 @@ ShellCommand::ShellCommand(int argc, char *argv[], std::string name) } } -ShellCommand::~ShellCommand() -{} +ShellCommand::~ShellCommand() {} ErrCode ShellCommand::OnCommand() { -- Gitee From 33d966f66e63c21f032fa20f4c57d90d4dd16461 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 15:07:54 +0800 Subject: [PATCH 28/77] test case related SR number Signed-off-by: zhangxin_T --- .../continuous_task_jsunit.test.js | 16 ++++++++-------- .../unittest/bg_continuous_task_mgr_test.cpp | 10 +++++----- test/systemtest/bgtask_dump_test.cpp | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js index c8851ad5..daf02b6d 100644 --- a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js +++ b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js @@ -58,7 +58,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest001 * @tc.desc:verify new startBackgroundrunning interface promise mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO + * @tc.require: SR000GGT7U AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO */ it("ContinuousTaskJsTest001", 0, async function (done) { let wantAgentInfo = { @@ -94,7 +94,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest002 * @tc.desc:verify new startBackgroundrunning interface callback mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 + * @tc.require: SR000GGT7T AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 */ it("ContinuousTaskJsTest002", 0, async function (done) { function conTaskCallback(err, data) { @@ -130,7 +130,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest003 * @tc.desc:verify old startBackgroundrunning interface promise mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH56K + * @tc.require: SR000GGT7V AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH56K */ it("ContinuousTaskJsTest003", 0, async function (done) { let wantAgentInfo = { @@ -182,7 +182,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest004 * @tc.desc:verify old startBackgroundrunning interface callback mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH6ET + * @tc.require: SR000GGT81 AR000GH6ER AR000GH6EM AR000GH6G9 AR000GH6ET */ it("ContinuousTaskJsTest004", 0, async function (done) { function conTaskCallback(err, data) { @@ -234,7 +234,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest005 * @tc.desc:verify new api stopBackgroundrunning interface promise mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EM AR000GH6EN AR000GH6EO + * @tc.require: SR000GGT7U AR000GH6ES AR000GH6EM AR000GH6EN AR000GH6EO */ it("ContinuousTaskJsTest005", 0, async function (done) { let wantAgentInfo = { @@ -272,7 +272,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest006 * @tc.desc:verify new api stopBackgroundrunning interface callback mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EP AR000GJ9PR AR000GH6G8 + * @tc.require: SR000GGT7T AR000GH6ES AR000GH6EP AR000GJ9PR AR000GH6G8 */ it("ContinuousTaskJsTest006", 0, async function (done) { function conTaskCallback(err, data) { @@ -310,7 +310,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest007 * @tc.desc:verify old api cancelBackgroundrunning interface promise mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K + * @tc.require: SR000GGT7V AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K */ it("ContinuousTaskJsTest007", 0, async function (done) { let wantAgentInfo = { @@ -349,7 +349,7 @@ describe("ContinuousTaskJsTest", function () { * @tc.name:ContinuousTaskJsTest008 * @tc.desc:verify old cancelBackgroundrunning interface callback mode work properly * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH6ET + * @tc.require: SR000GGT81 AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH6ET */ it("ContinuousTaskJsTest008", 0, async function (done) { function conTaskCallback(err, data) { diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp index 0e8f106e..b4bfbff5 100644 --- a/services/test/unittest/bg_continuous_task_mgr_test.cpp +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -85,7 +85,7 @@ public: * @tc.name: StartBackgroundRunning_001 * @tc.desc: start background runnging use new api test. * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO + * @tc.require: SR000GGT7U AR000GH6ER AR000GH6EM AR000GH6EN AR000GH6EO */ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_001, TestSize.Level1) { @@ -111,7 +111,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_001, TestSize.Level1) * @tc.name: StartBackgroundRunning_002 * @tc.desc: start background runnging use old api test. * @tc.type: FUNC - * @tc.require: AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 + * @tc.require: SR000GGT7T AR000GH6ER AR000GH6EP AR000GJ9PR AR000GH6G8 */ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) { @@ -129,7 +129,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) * @tc.name: StopBackgroundRunning_001 * @tc.desc: start background runnging use new api test. * @tc.type: FUNC - * @tc.require: AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K + * @tc.require: SR000GGT7V AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K */ HWTEST_F(BgContinuousTaskMgrTest, StopBackgroundRunning_001, TestSize.Level1) { @@ -150,7 +150,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StopBackgroundRunning_001, TestSize.Level1) * @tc.name: StartBackgroundRunning_001 * @tc.desc: subscribe continuous task event callback test. * @tc.type: FUNC - * @tc.require: AR000GH6EM AR000GH6G9 AR000GH6ET + * @tc.require: SR000GGT81 AR000GH6EM AR000GH6G9 AR000GH6ET */ HWTEST_F(BgContinuousTaskMgrTest, SubscribeContinuousTask_001, TestSize.Level1) { @@ -166,7 +166,7 @@ HWTEST_F(BgContinuousTaskMgrTest, SubscribeContinuousTask_001, TestSize.Level1) * @tc.name: UnsubscribeContinuousTask_001 * @tc.desc: unsubscribe continuous task event callback test. * @tc.type: FUNC - * @tc.require: AR000GH6EM AR000GH6G9 AR000GH6ET + * @tc.require: SR000GGT7U AR000GH6EM AR000GH6G9 AR000GH6ET */ HWTEST_F(BgContinuousTaskMgrTest, UnsubscribeContinuousTask_001, TestSize.Level1) { diff --git a/test/systemtest/bgtask_dump_test.cpp b/test/systemtest/bgtask_dump_test.cpp index e1f7c70b..2f58ac12 100644 --- a/test/systemtest/bgtask_dump_test.cpp +++ b/test/systemtest/bgtask_dump_test.cpp @@ -92,7 +92,7 @@ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_001, Function | MediumTest | L * @tc.name: BgtaskDumpTest_ShellDump_002 * @tc.desc: Shell dump * @tc.type: FUNC - * @tc.require: AR000GH6EQ + * @tc.require: SR000GGT80 AR000GH6EQ */ HWTEST_F(BgtaskDumpTest, BgtaskDumpTest_ShellDump_002, Function | MediumTest | Level0) { -- Gitee From e9ecd4a107b76d9190840ff407a948ce4266e014 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 16:57:07 +0800 Subject: [PATCH 29/77] change License info Signed-off-by: zhangxin_T --- frameworks/common/include/continuous_task_log.h | 2 +- interfaces/innerkits/include/continuous_task_callback_info.h | 2 +- interfaces/innerkits/include/continuous_task_param.h | 2 +- interfaces/innerkits/src/continuous_task_callback_info.cpp | 2 +- interfaces/innerkits/src/continuous_task_param.cpp | 2 +- .../continuous_task_jsunittest/continuous_task_jsunit.test.js | 2 +- services/continuous_task/include/app_state_observer.h | 2 +- services/continuous_task/include/bg_continuous_task_mgr.h | 2 +- services/continuous_task/include/bundle_manager_helper.h | 2 +- services/continuous_task/include/continuous_task_record.h | 2 +- services/continuous_task/include/remote_death_recipient.h | 2 +- services/continuous_task/include/system_event_observer.h | 2 +- services/continuous_task/include/task_notification_subscriber.h | 2 +- services/continuous_task/src/app_state_observer.cpp | 2 +- services/continuous_task/src/bg_continuous_task_mgr.cpp | 2 +- services/continuous_task/src/bundle_manager_helper.cpp | 2 +- services/continuous_task/src/continuous_task_record.cpp | 2 +- services/continuous_task/src/system_event_observer.cpp | 2 +- services/continuous_task/src/task_notification_subscriber.cpp | 2 +- services/test/unittest/bg_continuous_task_mgr_test.cpp | 2 +- services/test/unittest/mock/mock_bundle_manager_helper.cpp | 2 +- services/test/unittest/mock/mock_notification_helper.cpp | 2 +- services/test/unittest/mock/mock_resource_manager.cpp | 2 +- 23 files changed, 23 insertions(+), 23 deletions(-) diff --git a/frameworks/common/include/continuous_task_log.h b/frameworks/common/include/continuous_task_log.h index db3f7e91..282ef60d 100644 --- a/frameworks/common/include/continuous_task_log.h +++ b/frameworks/common/include/continuous_task_log.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/innerkits/include/continuous_task_callback_info.h b/interfaces/innerkits/include/continuous_task_callback_info.h index cae9910e..1aa13997 100644 --- a/interfaces/innerkits/include/continuous_task_callback_info.h +++ b/interfaces/innerkits/include/continuous_task_callback_info.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/innerkits/include/continuous_task_param.h b/interfaces/innerkits/include/continuous_task_param.h index 7b68b9f2..d5aa92f0 100644 --- a/interfaces/innerkits/include/continuous_task_param.h +++ b/interfaces/innerkits/include/continuous_task_param.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/innerkits/src/continuous_task_callback_info.cpp b/interfaces/innerkits/src/continuous_task_callback_info.cpp index c70d99dd..72379b23 100644 --- a/interfaces/innerkits/src/continuous_task_callback_info.cpp +++ b/interfaces/innerkits/src/continuous_task_callback_info.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/innerkits/src/continuous_task_param.cpp b/interfaces/innerkits/src/continuous_task_param.cpp index 3ca2ad7a..973cfa1b 100644 --- a/interfaces/innerkits/src/continuous_task_param.cpp +++ b/interfaces/innerkits/src/continuous_task_param.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js index daf02b6d..15cc39a4 100644 --- a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js +++ b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/app_state_observer.h b/services/continuous_task/include/app_state_observer.h index 85e48696..3f118aed 100644 --- a/services/continuous_task/include/app_state_observer.h +++ b/services/continuous_task/include/app_state_observer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index 30d11de1..9ef40bbd 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/bundle_manager_helper.h b/services/continuous_task/include/bundle_manager_helper.h index e18af8c1..21b5af19 100644 --- a/services/continuous_task/include/bundle_manager_helper.h +++ b/services/continuous_task/include/bundle_manager_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h index c20aa1cf..83722030 100644 --- a/services/continuous_task/include/continuous_task_record.h +++ b/services/continuous_task/include/continuous_task_record.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/remote_death_recipient.h b/services/continuous_task/include/remote_death_recipient.h index f6938123..d43ff79f 100644 --- a/services/continuous_task/include/remote_death_recipient.h +++ b/services/continuous_task/include/remote_death_recipient.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/system_event_observer.h b/services/continuous_task/include/system_event_observer.h index 734e5150..0225c3de 100644 --- a/services/continuous_task/include/system_event_observer.h +++ b/services/continuous_task/include/system_event_observer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/include/task_notification_subscriber.h b/services/continuous_task/include/task_notification_subscriber.h index d16a06c5..6e4c0e41 100644 --- a/services/continuous_task/include/task_notification_subscriber.h +++ b/services/continuous_task/include/task_notification_subscriber.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/app_state_observer.cpp b/services/continuous_task/src/app_state_observer.cpp index 8e5776dd..b9d050c5 100644 --- a/services/continuous_task/src/app_state_observer.cpp +++ b/services/continuous_task/src/app_state_observer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index cd27e6e5..4935dab6 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/bundle_manager_helper.cpp b/services/continuous_task/src/bundle_manager_helper.cpp index b25de200..a2b838f9 100644 --- a/services/continuous_task/src/bundle_manager_helper.cpp +++ b/services/continuous_task/src/bundle_manager_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index 1f66de05..dae7312d 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp index 92d4987d..87aafde6 100644 --- a/services/continuous_task/src/system_event_observer.cpp +++ b/services/continuous_task/src/system_event_observer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index d8ee070b..9cc29b8f 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp index b4bfbff5..8cb18d16 100644 --- a/services/test/unittest/bg_continuous_task_mgr_test.cpp +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/test/unittest/mock/mock_bundle_manager_helper.cpp index 00cfa133..77f444bd 100644 --- a/services/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/test/unittest/mock/mock_notification_helper.cpp b/services/test/unittest/mock/mock_notification_helper.cpp index 4611c313..b78edb36 100644 --- a/services/test/unittest/mock/mock_notification_helper.cpp +++ b/services/test/unittest/mock/mock_notification_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp index eb3fb0a2..383cdc0e 100644 --- a/services/test/unittest/mock/mock_resource_manager.cpp +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -- Gitee From 35d2fc96c296e5116553e8e7f8b3ba428dfdd09e Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Feb 2022 21:21:57 +0800 Subject: [PATCH 30/77] code format modify Signed-off-by: zhangxin_T --- frameworks/src/background_task_mgr_proxy.cpp | 73 ++++++++++--------- .../src/background_task_subscriber_proxy.cpp | 24 +++--- .../src/background_task_subscriber_stub.cpp | 2 - frameworks/src/expired_callback_proxy.cpp | 4 +- frameworks/src/expired_callback_stub.cpp | 2 +- .../src/bg_continuous_task_napi_module.cpp | 32 ++++---- .../kits/napi/src/request_suspend_delay.cpp | 4 +- .../include/app_state_observer.h | 1 - .../include/bg_continuous_task_mgr.h | 37 +--------- .../include/bundle_manager_helper.h | 1 - .../include/continuous_task_record.h | 11 --- .../include/remote_death_recipient.h | 1 + .../include/system_event_observer.h | 4 - .../include/task_notification_subscriber.h | 10 --- .../src/bg_continuous_task_mgr.cpp | 6 +- .../src/task_notification_subscriber.cpp | 7 +- .../core/src/background_task_mgr_service.cpp | 8 +- utils/bgtask_observer/src/bgtask_observer.cpp | 2 +- utils/dump/src/shell_command.cpp | 1 - 19 files changed, 80 insertions(+), 150 deletions(-) diff --git a/frameworks/src/background_task_mgr_proxy.cpp b/frameworks/src/background_task_mgr_proxy.cpp index deead535..a5d88bf4 100644 --- a/frameworks/src/background_task_mgr_proxy.cpp +++ b/frameworks/src/background_task_mgr_proxy.cpp @@ -32,7 +32,7 @@ ErrCode BackgroundTaskMgrProxy::RequestSuspendDelay(const std::u16string& reason const sptr& callback, std::shared_ptr &delayInfo) { if (callback == nullptr) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s callback is null", __func__); + BGTASK_LOGE("callback is null"); return ERR_BGTASK_INVALID_PARAM; } @@ -40,30 +40,30 @@ ErrCode BackgroundTaskMgrProxy::RequestSuspendDelay(const std::u16string& reason MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write descriptor failed", __func__); + BGTASK_LOGE("write descriptor failed"); return ERR_BGTASK_PARCELABLE_FAILED; } if (!data.WriteString16(reason)) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write reason failed", __func__); + BGTASK_LOGE("write reason failed"); return ERR_BGTASK_PARCELABLE_FAILED; } if (!data.WriteRemoteObject(callback->AsObject())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write callback failed", __func__); + BGTASK_LOGE("write callback failed"); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(REQUEST_SUSPEND_DELAY, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } delayInfo = DelaySuspendInfo::Unmarshalling(reply); if (delayInfo == nullptr) { - BGTASK_LOGE("BackgroundTaskMgrProxy::%{public}s, read result failed", __func__); + BGTASK_LOGE("read result failed"); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -75,21 +75,21 @@ ErrCode BackgroundTaskMgrProxy::CancelSuspendDelay(int32_t requestId) MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write descriptor failed", __func__); + BGTASK_LOGE("write descriptor failed"); return ERR_BGTASK_PARCELABLE_FAILED; } if (!data.WriteInt32(requestId)) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write requestId failed", __func__); + BGTASK_LOGE("write requestId failed"); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(CANCEL_SUSPEND_DELAY, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -111,15 +111,15 @@ ErrCode BackgroundTaskMgrProxy::GetRemainingDelayTime(int32_t requestId, int32_t ErrCode result = InnerTransact(GET_REMAINING_DELAY_TIME, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } if (!reply.ReadInt32(delayTime)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -146,11 +146,11 @@ ErrCode BackgroundTaskMgrProxy::StartBackgroundRunning(const sptr& subscriber) { if (subscriber == nullptr) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s subscriber is null", __func__); + BGTASK_LOGE("subscriber is null"); return ERR_BGTASK_PARCELABLE_FAILED; } @@ -202,21 +203,21 @@ ErrCode BackgroundTaskMgrProxy::SubscribeBackgroundTask(const sptrAsObject())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write subscriber failed", __func__); + BGTASK_LOGE("write subscriber failed"); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(SUBSCRIBE_BACKGROUND_TASK, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -225,7 +226,7 @@ ErrCode BackgroundTaskMgrProxy::SubscribeBackgroundTask(const sptr& subscriber) { if (subscriber == nullptr) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s subscriber is null", __func__); + BGTASK_LOGE("subscriber is null"); return ERR_BGTASK_PARCELABLE_FAILED; } @@ -233,21 +234,21 @@ ErrCode BackgroundTaskMgrProxy::UnsubscribeBackgroundTask(const sptrAsObject())) { - BGTASK_LOGE(" BackgroundTaskMgrProxy::%{public}s, write subscriber failed", __func__); + BGTASK_LOGE("write subscriber failed"); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(UNSUBSCRIBE_BACKGROUND_TASK, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -260,26 +261,26 @@ ErrCode BackgroundTaskMgrProxy::ShellDump(const std::vector &dumpOp MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; if (!data.WriteInterfaceToken(BackgroundTaskMgrProxy::GetDescriptor())) { - BGTASK_LOGE("[ShellDump] fail: write interface token failed."); + BGTASK_LOGE("write interface token failed."); return ERR_BGTASK_PARCELABLE_FAILED; } if (!data.WriteStringVector(dumpOption)) { - BGTASK_LOGE("[ShellDump] fail: write option failed."); + BGTASK_LOGE("write option failed."); return ERR_BGTASK_PARCELABLE_FAILED; } ErrCode result = InnerTransact(SHELL_DUMP, option, data, reply); if (result != ERR_OK) { - BGTASK_LOGI("fail: transact ErrCode=%{public}d", result); + BGTASK_LOGE("fail: transact ErrCode=%{public}d", result); return ERR_BGTASK_TRANSACT_FAILED; } if (!reply.ReadInt32(result)) { - BGTASK_LOGI("fail: read result failed."); + BGTASK_LOGE("fail: read result failed."); return ERR_BGTASK_PARCELABLE_FAILED; } if (!reply.ReadStringVector(&dumpInfo)) { - BGTASK_LOGI("[ShellDump] fail: read dumpInfo failed."); + BGTASK_LOGE("read dumpInfo failed."); return ERR_BGTASK_PARCELABLE_FAILED; } return result; @@ -290,7 +291,7 @@ ErrCode BackgroundTaskMgrProxy::InnerTransact(uint32_t code, MessageOption &flag { auto remote = Remote(); if (remote == nullptr) { - BGTASK_LOGI("[InnerTransact] fail: get Remote fail code %{public}d", code); + BGTASK_LOGE("get Remote fail code %{public}d", code); return ERR_DEAD_OBJECT; } int err = remote->SendRequest(code, data, reply, flags); @@ -299,11 +300,11 @@ ErrCode BackgroundTaskMgrProxy::InnerTransact(uint32_t code, MessageOption &flag return ERR_OK; } case DEAD_OBJECT: { - BGTASK_LOGI("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); + BGTASK_LOGE("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); return ERR_DEAD_OBJECT; } default: { - BGTASK_LOGI("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); + BGTASK_LOGE("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); return ERR_BGTASK_TRANSACT_FAILED; } } diff --git a/frameworks/src/background_task_subscriber_proxy.cpp b/frameworks/src/background_task_subscriber_proxy.cpp index 1e2d253f..acc38797 100644 --- a/frameworks/src/background_task_subscriber_proxy.cpp +++ b/frameworks/src/background_task_subscriber_proxy.cpp @@ -34,7 +34,7 @@ void BackgroundTaskSubscriberProxy::OnConnected() } MessageParcel data; if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { - BGTASK_LOGE("[OnConnected] fail: write interface token failed."); + BGTASK_LOGE("write interface token failed."); return; } @@ -56,7 +56,7 @@ void BackgroundTaskSubscriberProxy::OnDisconnected() } MessageParcel data; if (!data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor())) { - BGTASK_LOGE("[OnDisconnected] fail: write interface token failed."); + BGTASK_LOGE("write interface token failed."); return; } @@ -73,25 +73,25 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskStart(const std::shared_ptr remote = Remote(); if (remote == nullptr) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s remote is dead.", __func__); + BGTASK_LOGE("remote is dead."); return; } MessageParcel data; bool res = data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor()); if (!res) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, write descriptor failed.", __func__); + BGTASK_LOGE("write descriptor failed."); return; } if (!info->Marshalling(data)) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, write parcel failed.", __func__); + BGTASK_LOGE("write parcel failed."); return; } MessageParcel reply; MessageOption option; int ret = remote->SendRequest(ON_TRANSIENT_TASK_START, data, reply, option); if (ret != ERR_NONE) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, SendRequest failed, error code: %d", __func__, ret); + BGTASK_LOGE("SendRequest failed, error code: %d", ret); return; } } @@ -100,25 +100,25 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskEnd(const std::shared_ptr remote = Remote(); if (remote == nullptr) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s remote is dead.", __func__); + BGTASK_LOGE("remote is dead."); return; } MessageParcel data; bool res = data.WriteInterfaceToken(BackgroundTaskSubscriberProxy::GetDescriptor()); if (!res) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, write descriptor failed.", __func__); + BGTASK_LOGE("write descriptor failed."); return; } if (!info->Marshalling(data)) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, write parcel failed.", __func__); + BGTASK_LOGE("write parcel failed."); return; } MessageParcel reply; MessageOption option; int ret = remote->SendRequest(ON_TRANSIENT_TASK_END, data, reply, option); if (ret != ERR_NONE) { - BGTASK_LOGE("BackgroundTaskSubscriberProxy::%{public}s, SendRequest failed, error code: %d", __func__, ret); + BGTASK_LOGE("SendRequest failed, error code: %d", ret); return; } } @@ -144,7 +144,7 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStart( } if (!data.WriteParcelable(continuousTaskCallbackInfo)) { - BGTASK_LOGI("write continuousTaskCallbackInfo failed."); + BGTASK_LOGE("write continuousTaskCallbackInfo failed."); return; } @@ -155,7 +155,6 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStart( BGTASK_LOGE("SendRequest error"); return; } - BGTASK_LOGI("end"); } void BackgroundTaskSubscriberProxy::OnContinuousTaskStop( @@ -190,7 +189,6 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStop( BGTASK_LOGE("SendRequest error"); return; } - BGTASK_LOGI("end"); } } // namespace BackgroundTaskMgr } // namespace OHOS \ No newline at end of file diff --git a/frameworks/src/background_task_subscriber_stub.cpp b/frameworks/src/background_task_subscriber_stub.cpp index 13aa9c45..c3328bf6 100644 --- a/frameworks/src/background_task_subscriber_stub.cpp +++ b/frameworks/src/background_task_subscriber_stub.cpp @@ -114,7 +114,6 @@ ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskStart(MessageParcel } OnContinuousTaskStart(continuousTaskCallbackInfo); - BGTASK_LOGI("end"); return ERR_OK; } @@ -128,7 +127,6 @@ ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskCancel(MessageParcel } OnContinuousTaskStop(continuousTaskCallbackInfo); - BGTASK_LOGI("end"); return ERR_OK; } } // namespace BackgroundTaskMgr diff --git a/frameworks/src/expired_callback_proxy.cpp b/frameworks/src/expired_callback_proxy.cpp index 9e93f1d8..b474f015 100644 --- a/frameworks/src/expired_callback_proxy.cpp +++ b/frameworks/src/expired_callback_proxy.cpp @@ -29,7 +29,7 @@ void ExpiredCallbackProxy::OnExpired() { sptr remote = Remote(); if (remote == nullptr) { - BGTASK_LOGE("ExpiredCallbackProxy::%{public}s remote is dead.", __func__); + BGTASK_LOGE("remote is dead."); return; } @@ -38,7 +38,7 @@ void ExpiredCallbackProxy::OnExpired() MessageOption option(MessageOption::TF_ASYNC); bool res = data.WriteInterfaceToken(ExpiredCallbackProxy::GetDescriptor()); if (!res) { - BGTASK_LOGE("ExpiredCallbackProxy::%{public}s, write descriptor failed.", __func__); + BGTASK_LOGE("write descriptor failed."); return; } remote->SendRequest(ON_EXPIRED, data, reply, option); diff --git a/frameworks/src/expired_callback_stub.cpp b/frameworks/src/expired_callback_stub.cpp index 3582ee00..9d5d6814 100644 --- a/frameworks/src/expired_callback_stub.cpp +++ b/frameworks/src/expired_callback_stub.cpp @@ -30,7 +30,7 @@ int ExpiredCallbackStub::OnRemoteRequest(uint32_t code, std::u16string descriptor = ExpiredCallbackStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { - BGTASK_LOGE("ExpiredCallbackStub::%{public}s, local descriptor not match remote.", __func__); + BGTASK_LOGE("local descriptor not match remote."); return ERR_TRANSACTION_FAILED; } switch (code) { diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp index ff0b4e4d..b9687efc 100644 --- a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -72,7 +72,7 @@ AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env) { BGTASK_LOGI("begin"); if (env == nullptr) { - BGTASK_LOGE("env == nullptr."); + BGTASK_LOGE("env is nullptr."); return nullptr; } @@ -101,7 +101,7 @@ AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env) AsyncCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo; if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("asyncCallbackInfo == nullptr"); + BGTASK_LOGE("asyncCallbackInfo is nullptr"); return nullptr; } asyncCallbackInfo->env = env; @@ -119,7 +119,7 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) BGTASK_LOGI("begin"); AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("asyncCallbackInfo == nullptr"); + BGTASK_LOGE("asyncCallbackInfo is nullptr"); return; } if (asyncCallbackInfo->errCode != ERR_OK) { @@ -128,12 +128,12 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) } if (asyncCallbackInfo->ability == nullptr) { asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; - BGTASK_LOGE("ability == nullptr"); + BGTASK_LOGE("ability is nullptr"); return; } const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); if (info == nullptr) { - BGTASK_LOGE("info == nullptr"); + BGTASK_LOGE("info is nullptr"); asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; return; } @@ -216,7 +216,7 @@ napi_value StartBackgroundRunningAsync( { BGTASK_LOGI("begin"); if (argv == nullptr || asyncCallbackInfo == nullptr) { - BGTASK_LOGE("param == nullptr"); + BGTASK_LOGE("param is nullptr"); return nullptr; } napi_value resourceName = 0; @@ -244,7 +244,7 @@ napi_value StartBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncC { BGTASK_LOGI("begin"); if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("param == nullptr"); + BGTASK_LOGE("param is nullptr"); return nullptr; } napi_value resourceName; @@ -271,13 +271,11 @@ napi_value GetBackgroundMode(const napi_env &env, const napi_value &value, int32 BGTASK_LOGI("begin"); napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, value, &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, value, &bgMode); BGTASK_LOGI("get bgmode info: %{public}d", bgMode); - return WrapVoidToJS(env); } @@ -333,7 +331,7 @@ napi_value StartBackgroundRunning(napi_env env, napi_callback_info info) } if (ret == nullptr) { - BGTASK_LOGE("ret == nullpter"); + BGTASK_LOGE("ret is nullpter"); if (asyncCallbackInfo != nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; @@ -349,17 +347,17 @@ void StopBackgroundRunningExecuteCB(napi_env env, void *data) BGTASK_LOGI("begin"); AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("asyncCallbackInfo == nullptr"); + BGTASK_LOGE("asyncCallbackInfo is nullptr"); return; } if (asyncCallbackInfo->ability == nullptr) { asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; - BGTASK_LOGE("ability == nullptr"); + BGTASK_LOGE("ability is nullptr"); return; } const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); if (info == nullptr) { - BGTASK_LOGE("abilityInfo == nullptr"); + BGTASK_LOGE("abilityInfo is nullptr"); asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; return; } @@ -378,7 +376,7 @@ napi_value StopBackgroundRunningAsync(napi_env env, napi_value *argv, { BGTASK_LOGI("begin"); if (argv == nullptr || asyncCallbackInfo == nullptr) { - BGTASK_LOGE("param == nullptr"); + BGTASK_LOGE("param is nullptr"); return nullptr; } napi_value resourceName = 0; @@ -406,7 +404,7 @@ napi_value StopBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCa { BGTASK_LOGI("begin"); if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("param == nullptr"); + BGTASK_LOGE("param is nullptr"); return nullptr; } napi_value resourceName = 0; @@ -435,7 +433,7 @@ napi_value StopBackgroundRunning(napi_env env, napi_callback_info info) BGTASK_LOGI("begin"); AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("asyncCallbackInfo == nullpter"); + BGTASK_LOGE("asyncCallbackInfo is nullpter"); return WrapVoidToJS(env); } @@ -458,7 +456,7 @@ napi_value StopBackgroundRunning(napi_env env, napi_callback_info info) } if (ret == nullptr) { - BGTASK_LOGE("ret == nullpter"); + BGTASK_LOGE("ret is nullpter"); if (asyncCallbackInfo != nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; diff --git a/interfaces/kits/napi/src/request_suspend_delay.cpp b/interfaces/kits/napi/src/request_suspend_delay.cpp index 865a97e2..ab7ae7dd 100644 --- a/interfaces/kits/napi/src/request_suspend_delay.cpp +++ b/interfaces/kits/napi/src/request_suspend_delay.cpp @@ -38,7 +38,7 @@ void CallbackInstance::OnExpired() BGTASK_LOGI("enter"); if (expiredCallbackInfo_.ref == nullptr) { - BGTASK_LOGI("expired callback unset"); + BGTASK_LOGE("expired callback unset"); return; } @@ -116,7 +116,7 @@ napi_value RequestSuspendDelay(napi_env env, napi_callback_info info) napi_value result = nullptr; napi_create_object(env, &result); if (!Common::SetDelaySuspendInfo(env, delaySuspendInfo, result)) { - BGTASK_LOGI("Set DelaySuspendInfo object failed"); + BGTASK_LOGW("Set DelaySuspendInfo object failed"); } return result; } diff --git a/services/continuous_task/include/app_state_observer.h b/services/continuous_task/include/app_state_observer.h index 3f118aed..672ef69b 100644 --- a/services/continuous_task/include/app_state_observer.h +++ b/services/continuous_task/include/app_state_observer.h @@ -32,7 +32,6 @@ public: AppStateObserver(); ~AppStateObserver(); void OnProcessDied(const AppExecFwk::ProcessData &processData) override; - void SetEventHandler(const std::shared_ptr &handler); void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); bool Subscribe(); diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index 9ef40bbd..915834b7 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -53,76 +53,41 @@ class BgContinuousTaskMgr : public DelayedSingleton, public std::enable_shared_from_this { public: ErrCode StartBackgroundRunning(const sptr taskParam); - ErrCode StopBackgroundRunning(const std::string &abilityName, const sptr &abilityToken); - ErrCode AddSubscriber(const sptr &subscriber); - ErrCode RemoveSubscriber(const sptr &subscriber); - ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); - bool StopContinuousTaskByUser(const std::string &mapKey); - void OnBundleInfoChanged(const std::string &action, const std::string &bundleName, uid_t uid); - void OnProcessDied(int32_t pid); - void OnRemoteSubscriberDied(const wptr &object); - bool Init(); - void InitNecessaryState(); - void InitNotificationPrompt(); - void Clear(); private: ErrCode StartBackgroundRunningInner(std::shared_ptr &continuousTaskRecordPtr); - ErrCode StopBackgroundRunningInner(uid_t uid, const std::string &abilityName, const sptr &abilityToken); - ErrCode AddSubscriberInner(const sptr &subscriber); - ErrCode RemoveSubscriberInner(const sptr &subscriber); - ErrCode ShellDumpInner(const std::vector &dumpOption, std::vector &dumpInfo); - + ErrCode SendContinuousTaskNotification(std::shared_ptr &ContinuousTaskRecordPtr); void DumpAllTaskInfo(std::vector &dumpInfo); - void DumpCancelTask(const std::vector &dumpOption, bool cleanAll); - - ErrCode SendContinuousTaskNotification(std::shared_ptr &ContinuousTaskRecordPtr); - bool RemoveContinuousTaskRecord(const std::string &mapKey); - - bool InitAllBundleBriefInfos(); - bool AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); - std::string CreateNotificationLabel(uid_t uid, const std::string &bundleName, const std::string &abilityName, sptr abilityToken); - uint32_t GetBackgroundModeInfo(uid_t uid, std::string &abilityName); - bool AddAbilityBgModeInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); - bool RegisterNotificationSubscriber(); - bool RegisterSysCommEventListener(); - bool RegisterAppStateObserver(); - bool GetContinuousTaskText(); - bool SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName); - void OnRemoteSubscriberDiedInner(const wptr &object); - - std::string CreateNotificationText(int32_t typeId); - void OnContinuousTaskChanged(const std::shared_ptr continuousTaskInfo, ContinuousTaskEventTriggerType changeEventType); diff --git a/services/continuous_task/include/bundle_manager_helper.h b/services/continuous_task/include/bundle_manager_helper.h index 21b5af19..1c17c875 100644 --- a/services/continuous_task/include/bundle_manager_helper.h +++ b/services/continuous_task/include/bundle_manager_helper.h @@ -38,7 +38,6 @@ public: private: bool Connect(); void Disconnect(); - void OnRemoteDied(const wptr &object); private: diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h index 83722030..90f87d15 100644 --- a/services/continuous_task/include/continuous_task_record.h +++ b/services/continuous_task/include/continuous_task_record.h @@ -29,29 +29,18 @@ extern const char *ContinuousTaskModeName[10]; class ContinuousTaskRecord { public: ContinuousTaskRecord() = default; - ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, const std::shared_ptr &wantAgent, const sptr &abilityToken, int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi); - std::string GetBundleName() const; - std::string GetAbilityName() const; - bool IsNewApi() const; - uint32_t GetBgModeId() const; - int32_t GetUserId() const; - uid_t GetUid() const; - pid_t GetPid() const; - std::string GetNotificationLabel() const; - std::shared_ptr GetWantAgent() const; - sptr GetAbilityToken() const; private: diff --git a/services/continuous_task/include/remote_death_recipient.h b/services/continuous_task/include/remote_death_recipient.h index d43ff79f..d1587747 100644 --- a/services/continuous_task/include/remote_death_recipient.h +++ b/services/continuous_task/include/remote_death_recipient.h @@ -28,6 +28,7 @@ public: { callback_ = callback; } + ~RemoteDeathRecipient() { callback_ = nullptr; diff --git a/services/continuous_task/include/system_event_observer.h b/services/continuous_task/include/system_event_observer.h index 0225c3de..c46e20a9 100644 --- a/services/continuous_task/include/system_event_observer.h +++ b/services/continuous_task/include/system_event_observer.h @@ -29,14 +29,10 @@ class SystemEventObserver : public EventFwk::CommonEventSubscriber, public: SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo); ~SystemEventObserver() = default; - void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; - void SetEventHandler(const std::shared_ptr &handler); void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); - bool Subscribe(); - bool Unsubscribe(); private: diff --git a/services/continuous_task/include/task_notification_subscriber.h b/services/continuous_task/include/task_notification_subscriber.h index 6e4c0e41..fc9ff891 100644 --- a/services/continuous_task/include/task_notification_subscriber.h +++ b/services/continuous_task/include/task_notification_subscriber.h @@ -25,27 +25,17 @@ class BgContinuousTaskMgr; class TaskNotificationSubscriber : public Notification::NotificationSubscriber { public: TaskNotificationSubscriber(); - virtual ~TaskNotificationSubscriber(); - virtual void OnConnected() override; - virtual void OnDisconnected() override; - virtual void OnCanceled(const std::shared_ptr &request) override; - virtual void OnCanceled(const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) override; - virtual void OnConsumed(const std::shared_ptr &request) override; - virtual void OnConsumed(const std::shared_ptr &request, const std::shared_ptr &sortingMap) override; - virtual void OnUpdate(const std::shared_ptr &sortingMap) override; - virtual void OnDied() override; - virtual void OnDoNotDisturbDateChange( const std::shared_ptr &date) override; diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 4935dab6..6692982d 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -228,7 +228,7 @@ bool BgContinuousTaskMgr::SetCachedBundleInfo(uid_t uid, int32_t userId, std::st AppExecFwk::BundleInfo bundleInfo; if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId)) { - BGTASK_LOGW("get bundle info: %{public}s failure!", bundleName.c_str()); + BGTASK_LOGE("get bundle info: %{public}s failure!", bundleName.c_str()); return false; } @@ -296,7 +296,7 @@ bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool uint32_t recordedBgMode = BG_MODE_INDEX_HEAD << (requestedBgModeId - 1); if ((recordedBgMode == SYSTEM_APP_BGMODE_WIFI_INTERACTION || recordedBgMode == SYSTEM_APP_BGMODE_VOIP) && !BundleManagerHelper::GetInstance()->IsSystemApp(uid)) { - BGTASK_LOGW("voip and wifiInteraction background mode only support for system app"); + BGTASK_LOGE("voip and wifiInteraction background mode only support for system app"); return false; } if (requestedBgModeId == INVALID_BGMODE || (configuredBgMode @@ -468,7 +468,7 @@ ErrCode BgContinuousTaskMgr::SendContinuousTaskNotification( notificationRequest.SetCreatorUserId(-2); if (Notification::NotificationHelper::PublishContinuousTaskNotification(notificationRequest) != ERR_OK) { - BGTASK_LOGI("publish notification error"); + BGTASK_LOGE("publish notification error"); return ERR_BGTASK_NOTIFICATION_ERR; } continuousTaskRecord->notificationLabel_ = notificationLabel; diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index 9cc29b8f..7a09b1bb 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -68,7 +68,7 @@ void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr extraInfo = request.GetAdditionalData(); - if (extraInfo == nullptr) { - BGTASK_LOGI("notification extraInfo is null"); + BGTASK_LOGE("notification extraInfo is null"); return; } + BGTASK_LOGI("stop continuous task by user, the label is : %{public}s", notificationLabel.c_str()); std::string abilityName = AAFwk::String::Unbox(AAFwk::IString::Query(extraInfo->GetParam("abilityName"))); std::string taskInfoMapKey = labelSplits[LABEL_APP_UID_POS] + LABEL_SPLITER + abilityName diff --git a/services/core/src/background_task_mgr_service.cpp b/services/core/src/background_task_mgr_service.cpp index 85386396..5f5b985a 100644 --- a/services/core/src/background_task_mgr_service.cpp +++ b/services/core/src/background_task_mgr_service.cpp @@ -43,14 +43,12 @@ BackgroundTaskMgrService::~BackgroundTaskMgrService() {} void BackgroundTaskMgrService::OnStart() { if (state_ == ServiceRunningState::STATE_RUNNING) { - BGTASK_LOGI("Service has already started."); + BGTASK_LOGW("Service has already started."); return; } - Init(); - if (!Publish(DelayedSingleton::GetInstance().get())) { - BGTASK_LOGI("Service start failed!"); + BGTASK_LOGE("Service start failed!"); return; } state_ = ServiceRunningState::STATE_RUNNING; @@ -142,7 +140,7 @@ ErrCode BackgroundTaskMgrService::ShellDump(const std::vector &dump } else if (dumpOption[0] == CONTINUOUS_TASK_DUMP) { ret = BgContinuousTaskMgr::GetInstance()->ShellDump(dumpOption, dumpInfo); } else { - BGTASK_LOGI("invalid dump param"); + BGTASK_LOGW("invalid dump param"); ret = ERR_BGTASK_INVALID_PARAM; } return ret; diff --git a/utils/bgtask_observer/src/bgtask_observer.cpp b/utils/bgtask_observer/src/bgtask_observer.cpp index a8e7d707..8e0d594d 100644 --- a/utils/bgtask_observer/src/bgtask_observer.cpp +++ b/utils/bgtask_observer/src/bgtask_observer.cpp @@ -63,7 +63,7 @@ void BgTaskObserver::OnContinuousTaskStop(const std::shared_ptr &object) { - BGTASK_LOGI("remote service died"); + BGTASK_LOGW("remote service died"); isRemoteDied_.store(true); } } diff --git a/utils/dump/src/shell_command.cpp b/utils/dump/src/shell_command.cpp index 2a9c4d93..d4c97289 100644 --- a/utils/dump/src/shell_command.cpp +++ b/utils/dump/src/shell_command.cpp @@ -104,7 +104,6 @@ std::string ShellCommand::GetUnknownOptionMsg(std::string &unknownOption) const std::string ShellCommand::GetMessageFromCode(const int32_t code) const { - BGTASK_LOGI("[%{public}s(%{public}s)] enter", __FILE__, __FUNCTION__); BGTASK_LOGI("code = %{public}d", code); std::string result = ""; -- Gitee From 8c3bb78931d142a5633ecc4c8738244e403d32ba Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Sat, 12 Feb 2022 01:31:29 +0800 Subject: [PATCH 31/77] change want so file module name Signed-off-by: zhangxin_T --- frameworks/BUILD.gn | 2 +- interfaces/innerkits/BUILD.gn | 2 +- interfaces/kits/BUILD.gn | 2 +- services/BUILD.gn | 3 ++- utils/bgtask_observer/BUILD.gn | 4 ++-- 5 files changed, 7 insertions(+), 6 deletions(-) diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn index 656ea94e..de89fce6 100644 --- a/frameworks/BUILD.gn +++ b/frameworks/BUILD.gn @@ -47,7 +47,7 @@ ohos_shared_library("bgtaskmgr_fwk") { public_configs = [ ":bgtaskmgr_public_config" ] external_deps = [ - "ability_runtime:want", + "ability_base:want", "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index d8643ec8..927239f1 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -40,7 +40,7 @@ ohos_shared_library("bgtaskmgr_innerkits") { ] external_deps = [ - "ability_runtime:want", + "ability_base:want", "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/interfaces/kits/BUILD.gn b/interfaces/kits/BUILD.gn index 53fc2ef4..5b49d614 100644 --- a/interfaces/kits/BUILD.gn +++ b/interfaces/kits/BUILD.gn @@ -40,7 +40,7 @@ ohos_shared_library("backgroundtaskmanager") { external_deps = [ "ability_runtime:abilitykit_native", - "ability_runtime:want", + "ability_base:want", "bundle_framework:appexecfwk_base", "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", diff --git a/services/BUILD.gn b/services/BUILD.gn index e23a85f8..1cf3476d 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -60,10 +60,11 @@ ohos_shared_library("bgtaskmgr_service") { "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:app_manager", - "ability_runtime:base", + "ability_base:base", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/utils/bgtask_observer/BUILD.gn b/utils/bgtask_observer/BUILD.gn index 7f7c33c2..0143e0a0 100644 --- a/utils/bgtask_observer/BUILD.gn +++ b/utils/bgtask_observer/BUILD.gn @@ -9,7 +9,7 @@ # 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. +# limitations under the License. import("//build/ohos.gni") import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") @@ -40,7 +40,7 @@ ohos_executable("bgtask_observer") { configs = [] external_deps = [ - "ability_runtime:want", + "ability_base:want", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "samgr_standard:samgr_proxy", -- Gitee From 493d178b3b83f5d92b174c2ecd650eb12e47e443 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Sat, 12 Feb 2022 09:13:41 +0800 Subject: [PATCH 32/77] add missing so file Signed-off-by: zhangxin_T --- interfaces/kits/BUILD.gn | 2 +- services/test/unittest/BUILD.gn | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/BUILD.gn b/interfaces/kits/BUILD.gn index 5b49d614..296fe043 100644 --- a/interfaces/kits/BUILD.gn +++ b/interfaces/kits/BUILD.gn @@ -39,8 +39,8 @@ ohos_shared_library("backgroundtaskmanager") { ] external_deps = [ - "ability_runtime:abilitykit_native", "ability_base:want", + "ability_runtime:abilitykit_native", "bundle_framework:appexecfwk_base", "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 10c6c533..fa5f0ec4 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("bgtask_unit_test") { "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", -- Gitee From 190363375b74633cb920c884952a3f27eb81a1df Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Sat, 12 Feb 2022 09:46:01 +0800 Subject: [PATCH 33/77] gn file format modify Signed-off-by: zhangxin_T --- services/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/BUILD.gn b/services/BUILD.gn index 1cf3476d..58e1b78f 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -57,10 +57,10 @@ ohos_shared_library("bgtaskmgr_service") { ] external_deps = [ + "ability_base:base", "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:app_manager", - "ability_base:base", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", -- Gitee From c77923b01d6d29434c69ad7c93195fd92957a7c8 Mon Sep 17 00:00:00 2001 From: zengsiyu Date: Sun, 13 Feb 2022 23:47:19 +0800 Subject: [PATCH 34/77] =?UTF-8?q?feat:=20=E9=80=9A=E7=9F=A5=E5=8F=91?= =?UTF-8?q?=E9=80=81=E4=BD=BF=E8=83=BD=E8=83=BD=E5=8A=9B=E5=A2=9E=E5=BC=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zengsiyu Change-Id: I24063bfef2af88777fbf5d96c16f290b36772402 Signed-off-by: zengsiyu --- .../continuous_task/include/task_notification_subscriber.h | 2 ++ services/continuous_task/src/task_notification_subscriber.cpp | 3 +++ 2 files changed, 5 insertions(+) diff --git a/services/continuous_task/include/task_notification_subscriber.h b/services/continuous_task/include/task_notification_subscriber.h index fc9ff891..54591ecc 100644 --- a/services/continuous_task/include/task_notification_subscriber.h +++ b/services/continuous_task/include/task_notification_subscriber.h @@ -38,6 +38,8 @@ public: virtual void OnDied() override; virtual void OnDoNotDisturbDateChange( const std::shared_ptr &date) override; + virtual void OnEnabledNotificationChanged( + const std::shared_ptr &callbackData) override; private: std::vector StringSplit(const std::string &str, const char *delim); diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index 7a09b1bb..89c2d8a4 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -106,6 +106,9 @@ void TaskNotificationSubscriber::OnDied() {} void TaskNotificationSubscriber::OnDoNotDisturbDateChange( const std::shared_ptr &date) {} +void TaskNotificationSubscriber::OnEnabledNotificationChanged( + const std::shared_ptr &callbackData) {} + std::vector TaskNotificationSubscriber::StringSplit(const std::string &str, const char *delim) { std::vector strlist; -- Gitee From 773e3977ee736dea832966d283170aaeb3fbf03a Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Mon, 14 Feb 2022 08:29:15 +0800 Subject: [PATCH 35/77] bugfix for account stage change Signed-off-by: zhangxin_T --- .../src/background_task_subscriber_proxy.cpp | 6 -- .../continuous_task_jsunittest/config.json | 2 +- services/BUILD.gn | 1 + .../include/bg_continuous_task_mgr.h | 4 + .../include/os_account_observer.h | 45 ++++++++++ .../src/bg_continuous_task_mgr.cpp | 48 ++++++++++- .../src/os_account_observer.cpp | 82 +++++++++++++++++++ 7 files changed, 178 insertions(+), 10 deletions(-) create mode 100644 services/continuous_task/include/os_account_observer.h create mode 100644 services/continuous_task/src/os_account_observer.cpp diff --git a/frameworks/src/background_task_subscriber_proxy.cpp b/frameworks/src/background_task_subscriber_proxy.cpp index acc38797..3fe7d5e5 100644 --- a/frameworks/src/background_task_subscriber_proxy.cpp +++ b/frameworks/src/background_task_subscriber_proxy.cpp @@ -43,7 +43,6 @@ void BackgroundTaskSubscriberProxy::OnConnected() ErrCode ret = remote->SendRequest(ON_CONNECTED, data, reply, option); if (ret!= ERR_OK) { BGTASK_LOGE("SendRequest failed, error code: %d", ret); - return; } } @@ -65,7 +64,6 @@ void BackgroundTaskSubscriberProxy::OnDisconnected() ErrCode ret = remote->SendRequest(ON_DISCONNECTED, data, reply, option); if (ret != ERR_OK) { BGTASK_LOGE("SendRequest failed, error code: %d", ret); - return; } } @@ -92,7 +90,6 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskStart(const std::shared_ptrSendRequest(ON_TRANSIENT_TASK_START, data, reply, option); if (ret != ERR_NONE) { BGTASK_LOGE("SendRequest failed, error code: %d", ret); - return; } } @@ -119,7 +116,6 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskEnd(const std::shared_ptrSendRequest(ON_TRANSIENT_TASK_END, data, reply, option); if (ret != ERR_NONE) { BGTASK_LOGE("SendRequest failed, error code: %d", ret); - return; } } @@ -153,7 +149,6 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStart( ErrCode result = remote->SendRequest(ON_CONTINUOUS_TASK_START, data, reply, option); if (result != ERR_OK) { BGTASK_LOGE("SendRequest error"); - return; } } @@ -187,7 +182,6 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStop( ErrCode result = remote->SendRequest(ON_CONTINUOUS_TASK_STOP, data, reply, option); if (result != ERR_OK) { BGTASK_LOGE("SendRequest error"); - return; } } } // namespace BackgroundTaskMgr diff --git a/interfaces/test/unittest/continuous_task_jsunittest/config.json b/interfaces/test/unittest/continuous_task_jsunittest/config.json index b2980353..5fe3ce38 100644 --- a/interfaces/test/unittest/continuous_task_jsunittest/config.json +++ b/interfaces/test/unittest/continuous_task_jsunittest/config.json @@ -8,7 +8,7 @@ }, "apiVersion": { "compatible": 7, - "target": 7 + "target": 8 } }, "deviceConfig": {}, diff --git a/services/BUILD.gn b/services/BUILD.gn index 58e1b78f..6abb3535 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -29,6 +29,7 @@ ohos_shared_library("bgtaskmgr_service") { "continuous_task/src/bg_continuous_task_mgr.cpp", "continuous_task/src/bundle_manager_helper.cpp", "continuous_task/src/continuous_task_record.cpp", + "continuous_task/src/os_account_observer.cpp", "continuous_task/src/system_event_observer.cpp", "continuous_task/src/task_notification_subscriber.cpp", "core/src/background_task_mgr_service.cpp", diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index 915834b7..d7c2e46b 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -32,6 +32,7 @@ #include "continuous_task_param.h" #include "continuous_task_record.h" #include "ibackground_task_subscriber.h" +#include "os_account_observer.h" #include "remote_death_recipient.h" #include "system_event_observer.h" @@ -58,6 +59,7 @@ public: ErrCode RemoveSubscriber(const sptr &subscriber); ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); bool StopContinuousTaskByUser(const std::string &mapKey); + void OnAccountsStateChanged(int id); void OnBundleInfoChanged(const std::string &action, const std::string &bundleName, uid_t uid); void OnProcessDied(int32_t pid); void OnRemoteSubscriberDied(const wptr &object); @@ -85,6 +87,7 @@ private: bool RegisterNotificationSubscriber(); bool RegisterSysCommEventListener(); bool RegisterAppStateObserver(); + bool RegisterOsAccountObserver(); bool GetContinuousTaskText(); bool SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName); void OnRemoteSubscriberDiedInner(const wptr &object); @@ -99,6 +102,7 @@ private: std::shared_ptr subscriber_ {nullptr}; std::shared_ptr systemEventListener_ {nullptr}; std::shared_ptr appStateObserver_ {nullptr}; + std::shared_ptr osAccountObserver_ {nullptr}; std::list> bgTaskSubscribers_ {}; std::map, sptr> subscriberRecipients_ {}; std::unordered_map cachedBundleInfos_ {}; diff --git a/services/continuous_task/include/os_account_observer.h b/services/continuous_task/include/os_account_observer.h new file mode 100644 index 00000000..8766d009 --- /dev/null +++ b/services/continuous_task/include/os_account_observer.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_OS_ACCOUNT_OBSERVER_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_OS_ACCOUNT_OBSERVER_H + +#include "event_handler.h" +#include "os_account_manager.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class BgContinuousTaskMgr; + +class OsAccountObserver final : public AccountSA::OsAccountSubscriber, + public std::enable_shared_from_this { +public: + OsAccountObserver() = default; + ~OsAccountObserver() = default; + explicit OsAccountObserver(const AccountSA::OsAccountSubscribeInfo &subscribeInfo); + + void OnAccountsChanged(const int &id) override; + void SetEventHandler(const std::shared_ptr &handler); + void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); + bool Subscribe(); + bool Unsubscribe(); + +private: + std::weak_ptr handler_; + std::weak_ptr bgContinuousTaskMgr_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 6692982d..4ae66e80 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -108,6 +108,7 @@ void BgContinuousTaskMgr::InitNecessaryState() || systemAbilityManager->CheckSystemAbility(APP_MGR_SERVICE_ID) == nullptr || systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr || systemAbilityManager->CheckSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID) == nullptr + || systemAbilityManager->CheckSystemAbility(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) == nullptr || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr) { BGTASK_LOGW("request system service is not ready yet!"); auto task = [this]() { this->InitNecessaryState(); }; @@ -128,6 +129,10 @@ void BgContinuousTaskMgr::InitNecessaryState() BGTASK_LOGE("RegisterSysCommEventListener failed"); isInitSucceed = false; } + if (!RegisterOsAccountObserver()) { + BGTASK_LOGE("RegisterOsAccountObserver failed"); + isInitSucceed = false; + } if (isInitSucceed) { auto getPromptTask = [this]() { this->InitNotificationPrompt(); }; handler_->PostTask(getPromptTask, DELAY_TIME); @@ -223,6 +228,21 @@ bool BgContinuousTaskMgr::RegisterSysCommEventListener() return res; } +bool BgContinuousTaskMgr::RegisterOsAccountObserver() +{ + bool res = true; + OHOS::AccountSA::OsAccountSubscribeInfo osAccountSubscribeInfo; + osAccountSubscribeInfo.SetOsAccountSubscribeType(OHOS::AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVED); + osAccountSubscribeInfo.SetName("background_task_manager_service"); + osAccountObserver_ = std::make_shared(osAccountSubscribeInfo); + if (osAccountObserver_ != nullptr) { + osAccountObserver_->SetEventHandler(handler_); + osAccountObserver_->SetBgContinuousTaskMgr(shared_from_this()); + res = osAccountObserver_->Subscribe(); + } + return res; +} + bool BgContinuousTaskMgr::SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName) { AppExecFwk::BundleInfo bundleInfo; @@ -377,7 +397,7 @@ ErrCode BgContinuousTaskMgr::StartBackgroundRunningInner(std::shared_ptruid_) + SEPARATOR + continuousTaskRecord->abilityName_ + SEPARATOR + abilityTokeLabel; if (continuousTaskInfosMap_.find(taskInfoMapKey) != continuousTaskInfosMap_.end()) { - BGTASK_LOGI("continuous task is already exist: %{public}s", taskInfoMapKey.c_str()); + BGTASK_LOGW("continuous task is already exist: %{public}s", taskInfoMapKey.c_str()); return ERR_BGTASK_OBJECT_EXISTS; } @@ -544,7 +564,7 @@ ErrCode BgContinuousTaskMgr::AddSubscriber(const sptr return ERR_BGTASK_SYS_NOT_READY; } if (subscriber == nullptr) { - BGTASK_LOGI("subscriber is null."); + BGTASK_LOGE("subscriber is null."); return ERR_BGTASK_INVALID_PARAM; } @@ -759,7 +779,7 @@ void BgContinuousTaskMgr::OnRemoteSubscriberDied(const wptr &obje return; } if (object == nullptr) { - BGTASK_LOGI("remote object is null."); + BGTASK_LOGE("remote object is null."); return; } @@ -859,5 +879,27 @@ void BgContinuousTaskMgr::OnBundleInfoChanged(const std::string &action, const s return; } } + +void BgContinuousTaskMgr::OnAccountsStateChanged(int id) +{ + std::vector activatedOsAccountIds; + + if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds) != ERR_OK) { + BGTASK_LOGE("query activated account failed"); + return; + } + auto iter = continuousTaskInfosMap_.begin(); + while (iter != continuousTaskInfosMap_.end()) { + auto idIter = find(activatedOsAccountIds.begin(), activatedOsAccountIds.end(), iter->second->GetUserId()); + if (idIter == activatedOsAccountIds.end()) { + OnContinuousTaskChanged(iter->second, ContinuousTaskEventTriggerType::TASK_CANCEL); + Notification::NotificationHelper::CancelContinuousTaskNotification( + iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); + iter = continuousTaskInfosMap_.erase(iter); + } else { + iter++; + } + } +} } } \ No newline at end of file diff --git a/services/continuous_task/src/os_account_observer.cpp b/services/continuous_task/src/os_account_observer.cpp new file mode 100644 index 00000000..a3c997ac --- /dev/null +++ b/services/continuous_task/src/os_account_observer.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "os_account_observer.h" + +#include "bg_continuous_task_mgr.h" +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +const std::string TASK_ON_OS_ACCOUNT_CHANGED = "OnOsAccountChanged"; +} + +OsAccountObserver::OsAccountObserver(const AccountSA::OsAccountSubscribeInfo &subscribeInfo) + : OsAccountSubscriber(subscribeInfo) {} + +bool OsAccountObserver::Subscribe() +{ + BGTASK_LOGI("Subscribe called"); + int ret = OHOS::AccountSA::OsAccountManager::SubscribeOsAccount(shared_from_this()); + if (ret != 0) { + BGTASK_LOGE("register os account failed ret %{public}d", ret); + return false; + } + return true; +} + +bool OsAccountObserver::Unsubscribe() +{ + BGTASK_LOGI("UnSubscribe called"); + int ret = OHOS::AccountSA::OsAccountManager::UnsubscribeOsAccount(shared_from_this()); + if (ret != 0) { + BGTASK_LOGE("register os account failed ret %{public}d", ret); + return false; + } + return true; +} + +void OsAccountObserver::SetEventHandler(const std::shared_ptr &handler) +{ + BGTASK_LOGI("set os account observer handler"); + handler_ = handler; +} + +void OsAccountObserver::SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr) +{ + BGTASK_LOGI("set os account oberver bgContinuousTaskMgr"); + bgContinuousTaskMgr_ = bgContinuousTaskMgr; +} + +void OsAccountObserver::OnAccountsChanged(const int &id) +{ + BGTASK_LOGI("on accounts state changed : %{public}d actived", id); + auto handler = handler_.lock(); + if (!handler) { + BGTASK_LOGE("handler is null"); + return; + } + auto bgContinuousTaskMgr = bgContinuousTaskMgr_.lock(); + if (!bgContinuousTaskMgr) { + BGTASK_LOGE("bgContinuousTaskMgr is null"); + return; + } + + auto task = [=]() { bgContinuousTaskMgr->OnAccountsStateChanged(id); }; + handler->PostTask(task, TASK_ON_OS_ACCOUNT_CHANGED); +} +} +} \ No newline at end of file -- Gitee From f8b2afd4019d5ac068637c8a92912ce92bb21ad6 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Mon, 14 Feb 2022 09:33:18 +0800 Subject: [PATCH 36/77] add test case missing so file Signed-off-by: zhangxin_T --- services/test/unittest/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index fa5f0ec4..6b9a48e8 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -60,6 +60,7 @@ ohos_unittest("bgtask_unit_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", + "os_account_standard:os_account_innerkits", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "utils_base:utils", -- Gitee From e28b82cb45f62a2a435582f97ce1cb3316acd814 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Mon, 14 Feb 2022 13:03:22 +0800 Subject: [PATCH 37/77] codeCheck bugfix Signed-off-by: zhangxin_T --- .../src/bg_continuous_task_mgr.cpp | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 4ae66e80..98f8c0bf 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -116,27 +116,24 @@ void BgContinuousTaskMgr::InitNecessaryState() return; } - bool isInitSucceed = true; if (!RegisterNotificationSubscriber()) { BGTASK_LOGE("RegisterNotificationSubscriber failed"); - isInitSucceed = false; + return; } if (!RegisterAppStateObserver()) { BGTASK_LOGE("RegisterAppStateObserver failed"); - isInitSucceed = false; + return; } if (!RegisterSysCommEventListener()) { BGTASK_LOGE("RegisterSysCommEventListener failed"); - isInitSucceed = false; + return; } if (!RegisterOsAccountObserver()) { BGTASK_LOGE("RegisterOsAccountObserver failed"); - isInitSucceed = false; - } - if (isInitSucceed) { - auto getPromptTask = [this]() { this->InitNotificationPrompt(); }; - handler_->PostTask(getPromptTask, DELAY_TIME); + return; } + auto getPromptTask = [this]() { this->InitNotificationPrompt(); }; + handler_->PostTask(getPromptTask, DELAY_TIME); } void BgContinuousTaskMgr::InitNotificationPrompt() -- Gitee From ebb2b656714200697df9fc634be5f386a26c5308 Mon Sep 17 00:00:00 2001 From: wplan1 Date: Mon, 14 Feb 2022 18:44:09 +0800 Subject: [PATCH 38/77] add overlay Signed-off-by: wplan1 --- services/test/unittest/mock/mock_resource_manager.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp index 383cdc0e..b0493fce 100644 --- a/services/test/unittest/mock/mock_resource_manager.cpp +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -35,6 +35,11 @@ bool ResourceManagerImpl::AddResource(const char *path) return true; } +bool ResourceManagerImpl::AddResource(const std::string &path, const std::vector &overlayPaths) +{ + return true; +} + RState ResourceManagerImpl::UpdateResConfig(ResConfig &resConfig) { return SUCCESS; -- Gitee From aa9dc2986bc5e3ab76ef6024c13288870a1dc6a2 Mon Sep 17 00:00:00 2001 From: wanchengzhen Date: Mon, 14 Feb 2022 14:15:06 +0000 Subject: [PATCH 39/77] Fix atomic ability bundle.json change Signed-off-by: wanchengzhen --- bundle.json | 1 + 1 file changed, 1 insertion(+) diff --git a/bundle.json b/bundle.json index 2a8e1896..1de884dc 100644 --- a/bundle.json +++ b/bundle.json @@ -26,6 +26,7 @@ "ram": "10240KB", "deps": { "components": [ + "ability_base", "ability_runtime", "appexecfwk_standard", "ces_standard", -- Gitee From be056cdecefdf9e0af8ca097c9e8039ef377f1cd Mon Sep 17 00:00:00 2001 From: liqiang Date: Mon, 14 Feb 2022 11:59:04 +0800 Subject: [PATCH 40/77] IssueNo:https://gitee.com/openharmony/notification_ans_standard/issues/I4T3TK?from=project-issue Description:adapt wantagent change Sig: SIG_ApplicationFramework Feature or Bugfix:Bugfix Binary Source:No Signed-off-by: liqiang Change-Id: I0d566336d3a7201861a74f9079803ea438a08d87 --- frameworks/BUILD.gn | 5 +---- interfaces/innerkits/BUILD.gn | 6 ++---- interfaces/innerkits/include/continuous_task_param.h | 4 ++-- interfaces/innerkits/src/continuous_task_param.cpp | 4 ++-- interfaces/kits/BUILD.gn | 2 +- interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp | 6 +++--- services/BUILD.gn | 2 +- services/continuous_task/include/continuous_task_record.h | 6 +++--- services/continuous_task/src/continuous_task_record.cpp | 4 ++-- services/test/unittest/BUILD.gn | 2 +- services/test/unittest/bg_continuous_task_mgr_test.cpp | 4 ++-- utils/bgtask_observer/BUILD.gn | 2 +- utils/dump/BUILD.gn | 1 + 13 files changed, 22 insertions(+), 26 deletions(-) diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn index de89fce6..6dcf438d 100644 --- a/frameworks/BUILD.gn +++ b/frameworks/BUILD.gn @@ -40,14 +40,11 @@ ohos_shared_library("bgtaskmgr_fwk") { "src/expired_callback_stub.cpp", ] - deps = [ - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", - ] - public_configs = [ ":bgtaskmgr_public_config" ] external_deps = [ "ability_base:want", + "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index 927239f1..445154c0 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -34,13 +34,11 @@ ohos_shared_library("bgtaskmgr_innerkits") { "//foundation/resourceschedule/background_task_mgr/frameworks:bgtaskmgr_public_config", ] - public_deps = [ - "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", - ] + public_deps = [ "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk" ] external_deps = [ "ability_base:want", + "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/interfaces/innerkits/include/continuous_task_param.h b/interfaces/innerkits/include/continuous_task_param.h index d5aa92f0..69b86024 100644 --- a/interfaces/innerkits/include/continuous_task_param.h +++ b/interfaces/innerkits/include/continuous_task_param.h @@ -25,13 +25,13 @@ namespace BackgroundTaskMgr { struct ContinuousTaskParam : public Parcelable { bool isNewApi_ {false}; uint32_t bgModeId_ {0}; - std::shared_ptr wantAgent_ {nullptr}; + std::shared_ptr wantAgent_ {nullptr}; std::string abilityName_ {""}; sptr abilityToken_ {nullptr}; ContinuousTaskParam() = default; ContinuousTaskParam(bool isNewApi, uint32_t bgModeId, - const std::shared_ptr wantAgent, const std::string abilityName, + const std::shared_ptr wantAgent, const std::string abilityName, const sptr abilityToken) : isNewApi_(isNewApi), bgModeId_(bgModeId), wantAgent_(wantAgent), abilityName_(abilityName), abilityToken_(abilityToken) {} diff --git a/interfaces/innerkits/src/continuous_task_param.cpp b/interfaces/innerkits/src/continuous_task_param.cpp index 973cfa1b..a888b03a 100644 --- a/interfaces/innerkits/src/continuous_task_param.cpp +++ b/interfaces/innerkits/src/continuous_task_param.cpp @@ -32,8 +32,8 @@ bool ContinuousTaskParam::ReadFromParcel(Parcel &parcel) bool valid = false; valid = parcel.ReadBool(); if (valid) { - wantAgent_ = std::shared_ptr( - parcel.ReadParcelable()); + wantAgent_ = std::shared_ptr( + parcel.ReadParcelable()); if (!wantAgent_) { BGTASK_LOGE("Failed to read wantAgent"); return false; diff --git a/interfaces/kits/BUILD.gn b/interfaces/kits/BUILD.gn index 296fe043..af3a4424 100644 --- a/interfaces/kits/BUILD.gn +++ b/interfaces/kits/BUILD.gn @@ -35,12 +35,12 @@ ohos_shared_library("backgroundtaskmanager") { deps = [ "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", ] external_deps = [ "ability_base:want", "ability_runtime:abilitykit_native", + "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp index b9687efc..f2887f77 100644 --- a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -40,7 +40,7 @@ struct AsyncCallbackInfo { napi_deferred deferred {nullptr}; AppExecFwk::Ability *ability {nullptr}; int32_t bgMode {0}; - Notification::WantAgent::WantAgent *wantAgent {nullptr}; + AbilityRuntime::WantAgent::WantAgent *wantAgent {nullptr}; int errCode {0}; }; @@ -158,7 +158,7 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) } ContinuousTaskParam taskParam = ContinuousTaskParam(true, asyncCallbackInfo->bgMode, - std::make_shared(*asyncCallbackInfo->wantAgent), info->name, token); + std::make_shared(*asyncCallbackInfo->wantAgent), info->name, token); asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam); BGTASK_LOGI("end"); @@ -279,7 +279,7 @@ napi_value GetBackgroundMode(const napi_env &env, const napi_value &value, int32 return WrapVoidToJS(env); } -napi_value GetWantAgent(const napi_env &env, const napi_value &value, Notification::WantAgent::WantAgent *&wantAgent) +napi_value GetWantAgent(const napi_env &env, const napi_value &value, AbilityRuntime::WantAgent::WantAgent *&wantAgent) { BGTASK_LOGI("begin"); napi_valuetype valuetype = napi_undefined; diff --git a/services/BUILD.gn b/services/BUILD.gn index 6abb3535..321cbae5 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -53,7 +53,6 @@ ohos_shared_library("bgtaskmgr_service") { "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", "//base/notification/ans_standard/frameworks/ans/native:ans_innerkits", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//foundation/appexecfwk/standard/common:libappexecfwk_common", ] @@ -62,6 +61,7 @@ ohos_shared_library("bgtaskmgr_service") { "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h index 90f87d15..ad1efce7 100644 --- a/services/continuous_task/include/continuous_task_record.h +++ b/services/continuous_task/include/continuous_task_record.h @@ -30,7 +30,7 @@ class ContinuousTaskRecord { public: ContinuousTaskRecord() = default; ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, - const std::shared_ptr &wantAgent, const sptr &abilityToken, + const std::shared_ptr &wantAgent, const sptr &abilityToken, int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi); std::string GetBundleName() const; std::string GetAbilityName() const; @@ -40,13 +40,13 @@ public: uid_t GetUid() const; pid_t GetPid() const; std::string GetNotificationLabel() const; - std::shared_ptr GetWantAgent() const; + std::shared_ptr GetWantAgent() const; sptr GetAbilityToken() const; private: std::string bundleName_ {""}; std::string abilityName_ {""}; - std::shared_ptr wantAgent_ {nullptr}; + std::shared_ptr wantAgent_ {nullptr}; sptr abilityToken_ {nullptr}; int32_t userId_ {0}; uid_t uid_ {0}; diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index dae7312d..a25d387c 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -33,7 +33,7 @@ const char *ContinuousTaskModeName[10] = { }; ContinuousTaskRecord::ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, - const std::shared_ptr &wantAgent, const sptr &abilityToken, + const std::shared_ptr &wantAgent, const sptr &abilityToken, int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi) : bundleName_(bundleName), abilityName_(abilityName), wantAgent_(wantAgent), abilityToken_(abilityToken), userId_(userId), uid_(uid), pid_(pid), bgModeId_(bgModeId), isNewApi_(isNewApi) {} @@ -78,7 +78,7 @@ std::string ContinuousTaskRecord::GetNotificationLabel() const return notificationLabel_; } -std::shared_ptr ContinuousTaskRecord::GetWantAgent() const +std::shared_ptr ContinuousTaskRecord::GetWantAgent() const { return wantAgent_; } diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 6b9a48e8..51bca472 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -45,13 +45,13 @@ ohos_unittest("bgtask_unit_test") { "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", "${bgtaskmgr_services_path}:bgtaskmgr_service", "//base/notification/ans_standard/frameworks/ans/core:ans_core", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//third_party/googletest:gtest_main", ] external_deps = [ "ability_base:want", "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp index 8cb18d16..e6bb7be2 100644 --- a/services/test/unittest/bg_continuous_task_mgr_test.cpp +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -93,7 +93,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_001, TestSize.Level1) sptr taskParam = new ContinuousTaskParam(); taskParam->isNewApi_ = true; EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); - taskParam->wantAgent_ = std::make_shared(); + taskParam->wantAgent_ = std::make_shared(); EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); taskParam->abilityName_ = ""; EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); @@ -134,7 +134,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) HWTEST_F(BgContinuousTaskMgrTest, StopBackgroundRunning_001, TestSize.Level1) { sptr taskParam = new ContinuousTaskParam(); - taskParam->wantAgent_ = std::make_shared(); + taskParam->wantAgent_ = std::make_shared(); taskParam->abilityName_ = "ability1"; taskParam->bgModeId_ = 1; EXPECT_EQ((int)bgContinuousTaskMgr_->StopBackgroundRunning("", nullptr), (int)ERR_BGTASK_INVALID_PARAM); diff --git a/utils/bgtask_observer/BUILD.gn b/utils/bgtask_observer/BUILD.gn index 0143e0a0..2ab2945e 100644 --- a/utils/bgtask_observer/BUILD.gn +++ b/utils/bgtask_observer/BUILD.gn @@ -34,13 +34,13 @@ ohos_executable("bgtask_observer") { deps = [ "${bgtaskmgr_frameworks_path}:bgtaskmgr_fwk", "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", ] configs = [] external_deps = [ "ability_base:want", + "ability_runtime:wantagent_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "samgr_standard:samgr_proxy", diff --git a/utils/dump/BUILD.gn b/utils/dump/BUILD.gn index af8ccb0e..27d94cf0 100644 --- a/utils/dump/BUILD.gn +++ b/utils/dump/BUILD.gn @@ -41,6 +41,7 @@ ohos_executable("bgtask") { external_deps = [ "ability_base:want", + "ability_runtime:wantagent_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "samgr_standard:samgr_proxy", -- Gitee From 7c930f0b9d2e3d0903c4e03decf3ad0dc4a64174 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Tue, 15 Feb 2022 11:21:46 +0800 Subject: [PATCH 41/77] add tdd SR AR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- services/test/unittest/background_task_mgr_service_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/test/unittest/background_task_mgr_service_test.cpp b/services/test/unittest/background_task_mgr_service_test.cpp index 6fa37b66..7d54a46a 100644 --- a/services/test/unittest/background_task_mgr_service_test.cpp +++ b/services/test/unittest/background_task_mgr_service_test.cpp @@ -37,7 +37,7 @@ public: * @tc.name: BackgroundTaskMgrServiceTest_001 * @tc.desc: Test BackgroundTaskMgrService service ready. * @tc.type: FUNC - * @tc.require: SR000GGTET AR000GH86O AR000GH86Q + * @tc.require: SR000GGTET SR000GMUG8 AR000GH86O AR000GH86Q AR000GMUIA AR000GMUHN */ HWTEST_F(BackgroundTaskMgrServiceTest, BackgroundTaskMgrServiceTest_001, TestSize.Level1) { -- Gitee From 4587d22b43d27936d2b96a9dccfad4a493dca4f9 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Tue, 15 Feb 2022 12:15:45 +0800 Subject: [PATCH 42/77] use common event to get user switch info Signed-off-by: zhangxin_T --- services/continuous_task/src/bg_continuous_task_mgr.cpp | 6 +----- services/continuous_task/src/system_event_observer.cpp | 8 ++++++++ 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 98f8c0bf..f56f3285 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -108,7 +108,6 @@ void BgContinuousTaskMgr::InitNecessaryState() || systemAbilityManager->CheckSystemAbility(APP_MGR_SERVICE_ID) == nullptr || systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr || systemAbilityManager->CheckSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID) == nullptr - || systemAbilityManager->CheckSystemAbility(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) == nullptr || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr) { BGTASK_LOGW("request system service is not ready yet!"); auto task = [this]() { this->InitNecessaryState(); }; @@ -128,10 +127,6 @@ void BgContinuousTaskMgr::InitNecessaryState() BGTASK_LOGE("RegisterSysCommEventListener failed"); return; } - if (!RegisterOsAccountObserver()) { - BGTASK_LOGE("RegisterOsAccountObserver failed"); - return; - } auto getPromptTask = [this]() { this->InitNotificationPrompt(); }; handler_->PostTask(getPromptTask, DELAY_TIME); } @@ -215,6 +210,7 @@ bool BgContinuousTaskMgr::RegisterSysCommEventListener() matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REPLACED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills); systemEventListener_ = std::make_shared(commonEventSubscribeInfo); if (systemEventListener_ != nullptr) { diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp index 87aafde6..9a5e36c2 100644 --- a/services/continuous_task/src/system_event_observer.cpp +++ b/services/continuous_task/src/system_event_observer.cpp @@ -26,6 +26,7 @@ namespace OHOS { namespace BackgroundTaskMgr { namespace { const std::string TASK_ON_BUNDLEINFO_CHANGED = "OnBundleInfoChanged"; +const std::string TASK_ON_OS_ACCOUNT_CHANGED = "OnOsAccountChanged"; } SystemEventObserver::SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo) @@ -79,6 +80,13 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &eventD } AAFwk::Want want = eventData.GetWant(); std::string action = want.GetAction(); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + int activatedUserId = eventData.GetCode(); + BGTASK_LOGI("user of id :%{public}d is activated", activatedUserId); + auto task = [=]() { bgContinuousTaskMgr->OnAccountsStateChanged(activatedUserId); }; + handler->PostTask(task, TASK_ON_OS_ACCOUNT_CHANGED); + return; + } std::string bundleName = want.GetElement().GetBundleName(); int uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); BGTASK_LOGI("OnReceiveEvent action = %{public}s, bundle = %{public}s", action.c_str(), bundleName.c_str()); -- Gitee From a8c71db2f3407890613ab409be6db0c8d380b570 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Tue, 15 Feb 2022 18:30:37 +0800 Subject: [PATCH 43/77] add missing common event Signed-off-by: zhangxin_T --- .../continuous_task/src/bg_continuous_task_mgr.cpp | 4 ++++ services/continuous_task/src/system_event_observer.cpp | 10 ++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index f56f3285..d0c37d4f 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -210,6 +210,9 @@ bool BgContinuousTaskMgr::RegisterSysCommEventListener() matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REPLACED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_ADDED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills); systemEventListener_ = std::make_shared(commonEventSubscribeInfo); @@ -865,6 +868,7 @@ void BgContinuousTaskMgr::OnBundleInfoChanged(const std::string &action, const s || action == EventFwk::CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED || action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REPLACED) { cachedBundleInfos_.erase(uid); } else { diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp index 9a5e36c2..8e6d2308 100644 --- a/services/continuous_task/src/system_event_observer.cpp +++ b/services/continuous_task/src/system_event_observer.cpp @@ -80,10 +80,12 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &eventD } AAFwk::Want want = eventData.GetWant(); std::string action = want.GetAction(); - if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - int activatedUserId = eventData.GetCode(); - BGTASK_LOGI("user of id :%{public}d is activated", activatedUserId); - auto task = [=]() { bgContinuousTaskMgr->OnAccountsStateChanged(activatedUserId); }; + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_ADDED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + int userId = eventData.GetCode(); + BGTASK_LOGI("user of id :%{public}d state is changed, action is : %{public}s", userId, action.c_str()); + auto task = [=]() { bgContinuousTaskMgr->OnAccountsStateChanged(userId); }; handler->PostTask(task, TASK_ON_OS_ACCOUNT_CHANGED); return; } -- Gitee From 1b02b85c6f6f9ec9b95640b1dbffd070312390f3 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Wed, 16 Feb 2022 17:24:53 +0800 Subject: [PATCH 44/77] bugfix for get different userId bundleinfo and bgtask event callback register problem Signed-off-by: zhangxin_T --- .../include/bundle_manager_helper.h | 2 +- .../src/bg_continuous_task_mgr.cpp | 11 ++--------- .../src/bundle_manager_helper.cpp | 4 ++-- .../core/src/background_task_mgr_service.cpp | 18 ++++++++++-------- 4 files changed, 15 insertions(+), 20 deletions(-) diff --git a/services/continuous_task/include/bundle_manager_helper.h b/services/continuous_task/include/bundle_manager_helper.h index 1c17c875..5a954a58 100644 --- a/services/continuous_task/include/bundle_manager_helper.h +++ b/services/continuous_task/include/bundle_manager_helper.h @@ -30,7 +30,7 @@ using OHOS::AppExecFwk::Constants::UNSPECIFIED_USERID; class BundleManagerHelper : public DelayedSingleton { public: std::string GetClientBundleName(uid_t uid); - bool CheckPermission(const std::string &bundleName, const std::string &permission); + bool CheckPermission(const std::string &bundleName, const std::string &permission, int userId); bool IsSystemApp(uid_t uid); bool GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, AppExecFwk::BundleInfo &bundleInfo, int32_t userId = UNSPECIFIED_USERID); diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index d0c37d4f..39e556a9 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -397,7 +397,8 @@ ErrCode BgContinuousTaskMgr::StartBackgroundRunningInner(std::shared_ptrCheckPermission(continuousTaskRecord->bundleName_, BGMODE_PERMISSION)) { + if (!BundleManagerHelper::GetInstance()->CheckPermission(continuousTaskRecord->bundleName_, BGMODE_PERMISSION, + continuousTaskRecord->userId_)) { BGTASK_LOGE("background mode permission is not passed"); return ERR_BGTASK_PERMISSION_DENIED; } @@ -555,10 +556,6 @@ ErrCode BgContinuousTaskMgr::StopBackgroundRunningInner(uid_t uid, const std::st ErrCode BgContinuousTaskMgr::AddSubscriber(const sptr &subscriber) { BGTASK_LOGI("begin"); - if (!isSysReady_.load()) { - BGTASK_LOGW("manager is not ready"); - return ERR_BGTASK_SYS_NOT_READY; - } if (subscriber == nullptr) { BGTASK_LOGE("subscriber is null."); return ERR_BGTASK_INVALID_PARAM; @@ -606,10 +603,6 @@ ErrCode BgContinuousTaskMgr::AddSubscriberInner(const sptr &subscriber) { BGTASK_LOGI("begin"); - if (!isSysReady_.load()) { - BGTASK_LOGW("manager is not ready"); - return ERR_BGTASK_SYS_NOT_READY; - } if (subscriber == nullptr) { BGTASK_LOGE("subscriber is null."); return ERR_BGTASK_INVALID_PARAM; diff --git a/services/continuous_task/src/bundle_manager_helper.cpp b/services/continuous_task/src/bundle_manager_helper.cpp index a2b838f9..2281fac9 100644 --- a/services/continuous_task/src/bundle_manager_helper.cpp +++ b/services/continuous_task/src/bundle_manager_helper.cpp @@ -49,12 +49,12 @@ std::string BundleManagerHelper::GetClientBundleName(uid_t uid) } bool BundleManagerHelper::CheckPermission(const std::string &bundleName, - const std::string &permission) + const std::string &permission, int userId) { std::lock_guard lock(connectionMutex_); Connect(); if (bundleMgr_ != nullptr) { - auto result = bundleMgr_->CheckPermission(bundleName, permission); + auto result = bundleMgr_->CheckPermissionByUid(bundleName, permission, userId); BGTASK_LOGI("permission check result: %{public}d", result); if (result == PERMISSION_GRANTED) { return true; diff --git a/services/core/src/background_task_mgr_service.cpp b/services/core/src/background_task_mgr_service.cpp index 5f5b985a..6afd6027 100644 --- a/services/core/src/background_task_mgr_service.cpp +++ b/services/core/src/background_task_mgr_service.cpp @@ -102,18 +102,20 @@ ErrCode BackgroundTaskMgrService::StopBackgroundRunning(const std::string &abili ErrCode BackgroundTaskMgrService::SubscribeBackgroundTask(const sptr& subscriber) { - ErrCode ret = ERR_OK; - ret = DelayedSingleton::GetInstance()->SubscribeBackgroundTask(subscriber); - ret = BgContinuousTaskMgr::GetInstance()->AddSubscriber(subscriber); - return ret; + if (DelayedSingleton::GetInstance()->SubscribeBackgroundTask(subscriber) == ERR_OK + && BgContinuousTaskMgr::GetInstance()->AddSubscriber(subscriber) == ERR_OK) { + return ERR_OK; + } + return ERR_BGTASK_SYS_NOT_READY; } ErrCode BackgroundTaskMgrService::UnsubscribeBackgroundTask(const sptr& subscriber) { - ErrCode ret = ERR_OK; - ret = DelayedSingleton::GetInstance()->UnsubscribeBackgroundTask(subscriber); - ret = BgContinuousTaskMgr::GetInstance()->RemoveSubscriber(subscriber); - return ret; + if (DelayedSingleton::GetInstance()->UnsubscribeBackgroundTask(subscriber) == ERR_OK + && BgContinuousTaskMgr::GetInstance()->RemoveSubscriber(subscriber) == ERR_OK) { + return ERR_OK; + } + return ERR_BGTASK_SYS_NOT_READY; } void BackgroundTaskMgrService::HandleRequestExpired(const int32_t requestId) -- Gitee From 95e73841a6f54552935bc9a97040a8ad01c27feb Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Wed, 16 Feb 2022 18:35:42 +0800 Subject: [PATCH 45/77] change mock file method param Signed-off-by: zhangxin_T --- services/test/unittest/mock/mock_bundle_manager_helper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/test/unittest/mock/mock_bundle_manager_helper.cpp index 77f444bd..d341c3eb 100644 --- a/services/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -35,7 +35,7 @@ std::string BundleManagerHelper::GetClientBundleName(uid_t uid) } bool BundleManagerHelper::CheckPermission(const std::string &bundleName, - const std::string &permission) + const std::string &permission, int userId) { return true; } -- Gitee From 3f944aa4da87fd91088f4dfe85d605fa9983ed22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Fri, 18 Feb 2022 11:35:02 +0800 Subject: [PATCH 46/77] add system ready MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- .../include/bg_transient_task_mgr.h | 3 + .../src/bg_transient_task_mgr.cpp | 80 +++++++++++++------ 2 files changed, 60 insertions(+), 23 deletions(-) diff --git a/services/transient_task/include/bg_transient_task_mgr.h b/services/transient_task/include/bg_transient_task_mgr.h index 61f286be..fcbd7c1e 100644 --- a/services/transient_task/include/bg_transient_task_mgr.h +++ b/services/transient_task/include/bg_transient_task_mgr.h @@ -66,6 +66,8 @@ public: void HandleRequestExpired(const int32_t requestId); private: + bool IsCallingInfoLegal(int32_t uid, int32_t pid, std::string &name, + const sptr& callback); bool GetBundleNamesForUid(int32_t uid, std::string &bundleName); bool VerifyCallingInfo(int32_t uid, int32_t pid); bool VerifyRequestIdLocked(const std::string& name, int32_t uid, int32_t requestId); @@ -78,6 +80,7 @@ private: void SendScreenOffEvent(std::vector &dumpInfo); void InitNecessaryState(); + std::atomic isReady_ {false}; std::mutex suscriberLock_; sptr susriberDeathRecipient_ {nullptr}; std::mutex expiredCallbackLock_; diff --git a/services/transient_task/src/bg_transient_task_mgr.cpp b/services/transient_task/src/bg_transient_task_mgr.cpp index 57f959d3..e03d78a5 100644 --- a/services/transient_task/src/bg_transient_task_mgr.cpp +++ b/services/transient_task/src/bg_transient_task_mgr.cpp @@ -66,6 +66,11 @@ void BgTransientTaskMgr::Init() if (!handler_) { BGTASK_LOGE("Failed to init due to create handler error"); } + callbackDeathRecipient_ = + new ExpiredCallbackDeathRecipient(DelayedSingleton::GetInstance().get()); + susriberDeathRecipient_ = + new SubscriberDeathRecipient(DelayedSingleton::GetInstance().get()); + InitNecessaryState(); } @@ -77,17 +82,13 @@ void BgTransientTaskMgr::InitNecessaryState() || systemAbilityManager->CheckSystemAbility(APP_MGR_SERVICE_ID) == nullptr || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr || systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr) { + isReady_.store(false); BGTASK_LOGI("request system service is not ready yet!"); std::function InitNecessaryStateFunc = std::bind(&BgTransientTaskMgr::InitNecessaryState, this); handler_->PostTask(InitNecessaryStateFunc, SERVICE_WAIT_TIME); return; } - callbackDeathRecipient_ = - new ExpiredCallbackDeathRecipient(DelayedSingleton::GetInstance().get()); - susriberDeathRecipient_ = - new SubscriberDeathRecipient(DelayedSingleton::GetInstance().get()); - deviceInfoManeger_ = make_shared(); timerManager_ = make_shared(DelayedSingleton::GetInstance().get()); decisionMaker_ = make_shared(timerManager_, deviceInfoManeger_); @@ -96,6 +97,7 @@ void BgTransientTaskMgr::InitNecessaryState() inputManager_ = make_shared(); inputManager_->RegisterEventListener(deviceInfoManeger_); inputManager_->RegisterEventListener(decisionMaker_); + isReady_.store(true); } bool BgTransientTaskMgr::GetBundleNamesForUid(int32_t uid, std::string &bundleName) @@ -125,35 +127,51 @@ bool BgTransientTaskMgr::GetBundleNamesForUid(int32_t uid, std::string &bundleNa return true; } -ErrCode BgTransientTaskMgr::RequestSuspendDelay(const std::u16string& reason, - const sptr& callback, std::shared_ptr &delayInfo) +bool BgTransientTaskMgr::IsCallingInfoLegal(int32_t uid, int32_t pid, std::string &name, + const sptr& callback) { - auto uid = IPCSkeleton::GetCallingUid(); - auto pid = IPCSkeleton::GetCallingPid(); - auto infoEx = make_shared(pid); - delayInfo = infoEx; if (!VerifyCallingInfo(uid, pid)) { - BGTASK_LOGE("request suspend delay failed, pid or uid is invalid."); - return ERR_BGTASK_INVALID_PARAM; + BGTASK_LOGE("pid or uid is invalid."); + return false; } - std::string name = ""; if (!GetBundleNamesForUid(uid, name)) { BGTASK_LOGE("GetBundleNamesForUid fail."); - return ERR_BGTASK_INVALID_PARAM; + return false; } - BGTASK_LOGI("request suspend delay pkg : %{public}s, reason : %{public}s, uid : %{public}d, pid : %{public}d", - name.c_str(), Str16ToStr8(reason).c_str(), uid, pid); if (callback == nullptr) { - BGTASK_LOGE("request suspend delay failed, callback is null."); - return ERR_BGTASK_NOT_ALLOWED; + BGTASK_LOGE("callback is null."); + return false; } - auto remote = callback->AsObject(); - if (remote == nullptr) { - BGTASK_LOGE("request suspend delay failed, remote in callback is null."); + + if (callback->AsObject() == nullptr) { + BGTASK_LOGE("remote in callback is null."); + return false; + } + return true; +} + +ErrCode BgTransientTaskMgr::RequestSuspendDelay(const std::u16string& reason, + const sptr& callback, std::shared_ptr &delayInfo) +{ + if (!isReady_.load()) { + BGTASK_LOGE("Transient task manager is not ready."); + return ERR_BGTASK_SERVICE_NOT_READY; + } + auto uid = IPCSkeleton::GetCallingUid(); + auto pid = IPCSkeleton::GetCallingPid(); + std::string name = ""; + if (!IsCallingInfoLegal(uid, pid, name, callback)) { + BGTASK_LOGE("Request suspend delay failed, calling info is illegal."); return ERR_BGTASK_INVALID_PARAM; } + BGTASK_LOGI("request suspend delay pkg : %{public}s, reason : %{public}s, uid : %{public}d, pid : %{public}d", + name.c_str(), Str16ToStr8(reason).c_str(), uid, pid); + + auto infoEx = make_shared(pid); + delayInfo = infoEx; + auto remote = callback->AsObject(); lock_guard lock(expiredCallbackLock_); auto findCallback = [&callback](const auto& callbackMap) { return callback->AsObject() == callbackMap.second->AsObject(); @@ -213,6 +231,10 @@ void BgTransientTaskMgr::NotifyTransientTaskSuscriber(shared_ptrAddDeathRecipient(susriberDeathRecipient_); + if (susriberDeathRecipient_ != nullptr) { + remote->AddDeathRecipient(susriberDeathRecipient_); + } subscriberList_.emplace_back(subscriber); + BGTASK_LOGI("subscribe transient task success."); }); return result; } @@ -455,12 +484,17 @@ ErrCode BgTransientTaskMgr::UnsubscribeBackgroundTask(const sptrRemoveDeathRecipient(susriberDeathRecipient_); subscriberList_.erase(subscriberIter); + BGTASK_LOGI("unsubscribe transient task success."); }); return result; } ErrCode BgTransientTaskMgr::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) { + if (!isReady_.load()) { + BGTASK_LOGE("Transient task manager is not ready."); + return ERR_BGTASK_SERVICE_NOT_READY; + } bool result = false; if (dumpOption[1] == All_BGTASKMGR_OPTION) { result = DumpAllRequestId(dumpInfo); -- Gitee From f9666f6b23e6aa2d88bb05af2f75be2cc28823d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Sat, 19 Feb 2022 17:11:43 +0800 Subject: [PATCH 47/77] remove sleep 5s MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- sa_profile/etc/bgtaskmgr_service.cfg | 1 - 1 file changed, 1 deletion(-) diff --git a/sa_profile/etc/bgtaskmgr_service.cfg b/sa_profile/etc/bgtaskmgr_service.cfg index cea2ef32..7375259c 100644 --- a/sa_profile/etc/bgtaskmgr_service.cfg +++ b/sa_profile/etc/bgtaskmgr_service.cfg @@ -2,7 +2,6 @@ "jobs" : [{ "name" : "boot", "cmds" : [ - "exec /system/bin/sleep 5", "start bgtaskmgr_service" ] } -- Gitee From 3f13cc2a6ff2bc648f32ef2d2eb8806c84f86237 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Mon, 21 Feb 2022 13:00:16 +0800 Subject: [PATCH 48/77] codex bugfix and add PACKAGE_DATA_CLEARED event Signed-off-by: zhangxin_T --- .../background_task_subscriber_proxy.h | 6 ++-- .../include/ibackground_task_subscriber.h | 6 ++-- .../src/background_task_subscriber_proxy.cpp | 8 ++--- .../src/background_task_subscriber_stub.cpp | 6 ++-- .../include/background_task_subscriber.h | 6 ++-- .../include/continuous_task_callback_info.h | 12 +++---- .../src/background_task_subscriber.cpp | 8 ++--- .../src/continuous_task_callback_info.cpp | 6 ++-- .../include/bg_continuous_task_mgr.h | 12 +++---- .../include/bundle_manager_helper.h | 4 +-- .../include/continuous_task_record.h | 6 ++-- .../src/bg_continuous_task_mgr.cpp | 36 ++++++++++++------- .../src/bundle_manager_helper.cpp | 4 +-- .../src/continuous_task_record.cpp | 4 +-- .../src/system_event_observer.cpp | 3 +- .../mock/mock_bundle_manager_helper.cpp | 4 +-- utils/bgtask_observer/src/bgtask_observer.cpp | 4 +-- 17 files changed, 78 insertions(+), 57 deletions(-) diff --git a/frameworks/include/background_task_subscriber_proxy.h b/frameworks/include/background_task_subscriber_proxy.h index 0f5ffd04..392a41d5 100644 --- a/frameworks/include/background_task_subscriber_proxy.h +++ b/frameworks/include/background_task_subscriber_proxy.h @@ -33,8 +33,10 @@ public: void OnDisconnected() override; void OnTransientTaskStart(const std::shared_ptr& info) override; void OnTransientTaskEnd(const std::shared_ptr& info) override; - void OnContinuousTaskStart(const sptr &continuousTaskCallbackInfo) override; - void OnContinuousTaskStop(const sptr &continuousTaskCallbackInfo) override; + void OnContinuousTaskStart( + const std::shared_ptr &continuousTaskCallbackInfo) override; + void OnContinuousTaskStop( + const std::shared_ptr &continuousTaskCallbackInfo) override; private: static inline BrokerDelegator delegator_; diff --git a/frameworks/include/ibackground_task_subscriber.h b/frameworks/include/ibackground_task_subscriber.h index 265e376b..de58960e 100644 --- a/frameworks/include/ibackground_task_subscriber.h +++ b/frameworks/include/ibackground_task_subscriber.h @@ -35,8 +35,10 @@ public: virtual void OnDisconnected() = 0; virtual void OnTransientTaskStart(const std::shared_ptr& info) = 0; virtual void OnTransientTaskEnd(const std::shared_ptr& info) = 0; - virtual void OnContinuousTaskStart(const sptr &continuousTaskCallbackInfo) = 0; - virtual void OnContinuousTaskStop(const sptr &continuousTaskCallbackInfo) = 0; + virtual void OnContinuousTaskStart( + const std::shared_ptr &continuousTaskCallbackInfo) = 0; + virtual void OnContinuousTaskStop( + const std::shared_ptr &continuousTaskCallbackInfo) = 0; public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.resourceschedule.IBackgroundTaskSubscriber"); diff --git a/frameworks/src/background_task_subscriber_proxy.cpp b/frameworks/src/background_task_subscriber_proxy.cpp index 3fe7d5e5..b3401a62 100644 --- a/frameworks/src/background_task_subscriber_proxy.cpp +++ b/frameworks/src/background_task_subscriber_proxy.cpp @@ -120,7 +120,7 @@ void BackgroundTaskSubscriberProxy::OnTransientTaskEnd(const std::shared_ptr &continuousTaskCallbackInfo) + const std::shared_ptr &continuousTaskCallbackInfo) { BGTASK_LOGI("begin"); sptr remote = Remote(); @@ -139,7 +139,7 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStart( return; } - if (!data.WriteParcelable(continuousTaskCallbackInfo)) { + if (!data.WriteParcelable(continuousTaskCallbackInfo.get())) { BGTASK_LOGE("write continuousTaskCallbackInfo failed."); return; } @@ -153,7 +153,7 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStart( } void BackgroundTaskSubscriberProxy::OnContinuousTaskStop( - const sptr &continuousTaskCallbackInfo) + const std::shared_ptr &continuousTaskCallbackInfo) { BGTASK_LOGI("begin"); sptr remote = Remote(); @@ -172,7 +172,7 @@ void BackgroundTaskSubscriberProxy::OnContinuousTaskStop( return; } - if (!data.WriteParcelable(continuousTaskCallbackInfo)) { + if (!data.WriteParcelable(continuousTaskCallbackInfo.get())) { BGTASK_LOGE("write notification failed."); return; } diff --git a/frameworks/src/background_task_subscriber_stub.cpp b/frameworks/src/background_task_subscriber_stub.cpp index c3328bf6..6c9e602a 100644 --- a/frameworks/src/background_task_subscriber_stub.cpp +++ b/frameworks/src/background_task_subscriber_stub.cpp @@ -107,7 +107,8 @@ ErrCode BackgroundTaskSubscriberStub::HandleOnTransientTaskEnd(MessageParcel& da ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskStart(MessageParcel &data) { BGTASK_LOGI("begin"); - sptr continuousTaskCallbackInfo = data.ReadParcelable(); + std::shared_ptr continuousTaskCallbackInfo + = std::shared_ptr(data.ReadParcelable()); if (!continuousTaskCallbackInfo) { BGTASK_LOGE("ContinuousTaskCallbackInfo ReadParcelable failed"); return ERR_BGTASK_PARCELABLE_FAILED; @@ -120,7 +121,8 @@ ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskStart(MessageParcel ErrCode BackgroundTaskSubscriberStub::HandleOnContinuousTaskCancel(MessageParcel &data) { BGTASK_LOGI("begin"); - sptr continuousTaskCallbackInfo = data.ReadParcelable(); + std::shared_ptr continuousTaskCallbackInfo + = std::shared_ptr(data.ReadParcelable()); if (!continuousTaskCallbackInfo) { BGTASK_LOGE("ContinuousTaskCallbackInfo ReadParcelable failed"); return ERR_BGTASK_PARCELABLE_FAILED; diff --git a/interfaces/innerkits/include/background_task_subscriber.h b/interfaces/innerkits/include/background_task_subscriber.h index 701f7407..aaa5e10a 100644 --- a/interfaces/innerkits/include/background_task_subscriber.h +++ b/interfaces/innerkits/include/background_task_subscriber.h @@ -100,8 +100,10 @@ private: void OnDisconnected() override; void OnTransientTaskStart(const std::shared_ptr& info) override; void OnTransientTaskEnd(const std::shared_ptr& info) override; - void OnContinuousTaskStart(const sptr &continuousTaskCallbackInfo) override; - void OnContinuousTaskStop(const sptr &continuousTaskCallbackInfo) override; + void OnContinuousTaskStart( + const std::shared_ptr &continuousTaskCallbackInfo) override; + void OnContinuousTaskStop( + const std::shared_ptr &continuousTaskCallbackInfo) override; bool GetBackgroundTaskMgrProxy(); public: diff --git a/interfaces/innerkits/include/continuous_task_callback_info.h b/interfaces/innerkits/include/continuous_task_callback_info.h index 1aa13997..46f91afb 100644 --- a/interfaces/innerkits/include/continuous_task_callback_info.h +++ b/interfaces/innerkits/include/continuous_task_callback_info.h @@ -25,10 +25,10 @@ namespace BackgroundTaskMgr { class ContinuousTaskCallbackInfo : public Parcelable { public: ContinuousTaskCallbackInfo(); - ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, pid_t creatorPid, std::string abilityName); + ContinuousTaskCallbackInfo(int32_t typeId, int32_t creatorUid, pid_t creatorPid, std::string abilityName); int32_t GetTypeId() const; - uid_t GetCreatorUid() const; + int32_t GetCreatorUid() const; pid_t GetCreatorPid() const; std::string GetAbilityName() const; bool Marshalling(Parcel &parcel) const; @@ -38,10 +38,10 @@ private: bool ReadFromParcel(Parcel &parcel); private: - int32_t typeId_ ; - uid_t creatorUid_ ; - pid_t creatorPid_ ; - std::string abilityName_ ; + int32_t typeId_ {0}; + int32_t creatorUid_ {0}; + pid_t creatorPid_ {0}; + std::string abilityName_ {""}; }; } } diff --git a/interfaces/innerkits/src/background_task_subscriber.cpp b/interfaces/innerkits/src/background_task_subscriber.cpp index ad56a6f9..00ab325f 100644 --- a/interfaces/innerkits/src/background_task_subscriber.cpp +++ b/interfaces/innerkits/src/background_task_subscriber.cpp @@ -83,15 +83,15 @@ void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnTransientTaskEnd( } void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnContinuousTaskStart( - const sptr &continuousTaskCallbackInfo) + const std::shared_ptr &continuousTaskCallbackInfo) { - subscriber_.OnContinuousTaskStart(std::make_shared(*continuousTaskCallbackInfo)); + subscriber_.OnContinuousTaskStart(continuousTaskCallbackInfo); } void BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::OnContinuousTaskStop( - const sptr &continuousTaskCallbackInfo) + const std::shared_ptr &continuousTaskCallbackInfo) { - subscriber_.OnContinuousTaskStop(std::make_shared(*continuousTaskCallbackInfo)); + subscriber_.OnContinuousTaskStop(continuousTaskCallbackInfo); } bool BackgroundTaskSubscriber::BackgroundTaskSubscriberImpl::GetBackgroundTaskMgrProxy() diff --git a/interfaces/innerkits/src/continuous_task_callback_info.cpp b/interfaces/innerkits/src/continuous_task_callback_info.cpp index 72379b23..ac3aee2d 100644 --- a/interfaces/innerkits/src/continuous_task_callback_info.cpp +++ b/interfaces/innerkits/src/continuous_task_callback_info.cpp @@ -20,7 +20,7 @@ namespace OHOS { namespace BackgroundTaskMgr { ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo() {} -ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo(int32_t typeId, uid_t creatorUid, +ContinuousTaskCallbackInfo::ContinuousTaskCallbackInfo(int32_t typeId, int32_t creatorUid, pid_t creatorPid, std::string abilityName) : typeId_(typeId), creatorUid_(creatorUid), creatorPid_(creatorPid), abilityName_(abilityName) {} @@ -29,7 +29,7 @@ int32_t ContinuousTaskCallbackInfo::GetTypeId() const return typeId_; } -uid_t ContinuousTaskCallbackInfo::GetCreatorUid() const +int32_t ContinuousTaskCallbackInfo::GetCreatorUid() const { return creatorUid_; } @@ -83,7 +83,7 @@ bool ContinuousTaskCallbackInfo::ReadFromParcel(Parcel &parcel) { typeId_ = parcel.ReadInt32(); - creatorUid_ = static_cast(parcel.ReadInt32()); + creatorUid_ = static_cast(parcel.ReadInt32()); creatorPid_ = static_cast(parcel.ReadInt32()); if (!parcel.ReadString(abilityName_)) { diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index d7c2e46b..d44d3912 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -60,7 +60,7 @@ public: ErrCode ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); bool StopContinuousTaskByUser(const std::string &mapKey); void OnAccountsStateChanged(int id); - void OnBundleInfoChanged(const std::string &action, const std::string &bundleName, uid_t uid); + void OnBundleInfoChanged(const std::string &action, const std::string &bundleName, int32_t uid); void OnProcessDied(int32_t pid); void OnRemoteSubscriberDied(const wptr &object); bool Init(); @@ -70,7 +70,7 @@ public: private: ErrCode StartBackgroundRunningInner(std::shared_ptr &continuousTaskRecordPtr); - ErrCode StopBackgroundRunningInner(uid_t uid, const std::string &abilityName, + ErrCode StopBackgroundRunningInner(int32_t uid, const std::string &abilityName, const sptr &abilityToken); ErrCode AddSubscriberInner(const sptr &subscriber); ErrCode RemoveSubscriberInner(const sptr &subscriber); @@ -80,16 +80,16 @@ private: void DumpCancelTask(const std::vector &dumpOption, bool cleanAll); bool RemoveContinuousTaskRecord(const std::string &mapKey); bool AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); - std::string CreateNotificationLabel(uid_t uid, const std::string &bundleName, + std::string CreateNotificationLabel(int32_t uid, const std::string &bundleName, const std::string &abilityName, sptr abilityToken); - uint32_t GetBackgroundModeInfo(uid_t uid, std::string &abilityName); + uint32_t GetBackgroundModeInfo(int32_t uid, std::string &abilityName); bool AddAbilityBgModeInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); bool RegisterNotificationSubscriber(); bool RegisterSysCommEventListener(); bool RegisterAppStateObserver(); bool RegisterOsAccountObserver(); bool GetContinuousTaskText(); - bool SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName); + bool SetCachedBundleInfo(int32_t uid, int32_t userId, std::string &bundleName); void OnRemoteSubscriberDiedInner(const wptr &object); void OnContinuousTaskChanged(const std::shared_ptr continuousTaskInfo, ContinuousTaskEventTriggerType changeEventType); @@ -105,7 +105,7 @@ private: std::shared_ptr osAccountObserver_ {nullptr}; std::list> bgTaskSubscribers_ {}; std::map, sptr> subscriberRecipients_ {}; - std::unordered_map cachedBundleInfos_ {}; + std::unordered_map cachedBundleInfos_ {}; std::vector continuousTaskText_ {}; DECLARE_DELAYED_SINGLETON(BgContinuousTaskMgr); diff --git a/services/continuous_task/include/bundle_manager_helper.h b/services/continuous_task/include/bundle_manager_helper.h index 5a954a58..7be2323d 100644 --- a/services/continuous_task/include/bundle_manager_helper.h +++ b/services/continuous_task/include/bundle_manager_helper.h @@ -29,9 +29,9 @@ namespace BackgroundTaskMgr { using OHOS::AppExecFwk::Constants::UNSPECIFIED_USERID; class BundleManagerHelper : public DelayedSingleton { public: - std::string GetClientBundleName(uid_t uid); + std::string GetClientBundleName(int32_t uid); bool CheckPermission(const std::string &bundleName, const std::string &permission, int userId); - bool IsSystemApp(uid_t uid); + bool IsSystemApp(int32_t uid); bool GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, AppExecFwk::BundleInfo &bundleInfo, int32_t userId = UNSPECIFIED_USERID); diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h index ad1efce7..17c54c81 100644 --- a/services/continuous_task/include/continuous_task_record.h +++ b/services/continuous_task/include/continuous_task_record.h @@ -31,13 +31,13 @@ public: ContinuousTaskRecord() = default; ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, const std::shared_ptr &wantAgent, const sptr &abilityToken, - int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi); + int32_t userId, int32_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi); std::string GetBundleName() const; std::string GetAbilityName() const; bool IsNewApi() const; uint32_t GetBgModeId() const; int32_t GetUserId() const; - uid_t GetUid() const; + int32_t GetUid() const; pid_t GetPid() const; std::string GetNotificationLabel() const; std::shared_ptr GetWantAgent() const; @@ -49,7 +49,7 @@ private: std::shared_ptr wantAgent_ {nullptr}; sptr abilityToken_ {nullptr}; int32_t userId_ {0}; - uid_t uid_ {0}; + int32_t uid_ {0}; pid_t pid_ {0}; uint32_t bgModeId_ {0}; bool isNewApi_ {false}; diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 39e556a9..6af7dd8e 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -239,7 +239,7 @@ bool BgContinuousTaskMgr::RegisterOsAccountObserver() return res; } -bool BgContinuousTaskMgr::SetCachedBundleInfo(uid_t uid, int32_t userId, std::string &bundleName) +bool BgContinuousTaskMgr::SetCachedBundleInfo(int32_t uid, int32_t userId, std::string &bundleName) { AppExecFwk::BundleInfo bundleInfo; if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, @@ -299,7 +299,7 @@ bool BgContinuousTaskMgr::AddAppNameInfos(const AppExecFwk::BundleInfo &bundleIn return true; } -bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool isNewApi, uid_t uid) +bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool isNewApi, int32_t uid) { if (!isNewApi) { if (configuredBgMode == INVALID_BGMODE) { @@ -324,7 +324,7 @@ bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool return true; } -uint32_t BgContinuousTaskMgr::GetBackgroundModeInfo(uid_t uid, std::string &abilityName) +uint32_t BgContinuousTaskMgr::GetBackgroundModeInfo(int32_t uid, std::string &abilityName) { if (cachedBundleInfos_.find(uid) != cachedBundleInfos_.end()) { auto cachedBundleInfo = cachedBundleInfos_.at(uid); @@ -363,7 +363,7 @@ ErrCode BgContinuousTaskMgr::StartBackgroundRunning(const sptrGetClientBundleName(callingUid); int32_t userId = -1; @@ -494,7 +494,7 @@ ErrCode BgContinuousTaskMgr::SendContinuousTaskNotification( return ERR_OK; } -std::string BgContinuousTaskMgr::CreateNotificationLabel(uid_t uid, const std::string &bundleName, +std::string BgContinuousTaskMgr::CreateNotificationLabel(int32_t uid, const std::string &bundleName, const std::string &abilityName, const sptr abilityToken) { std::stringstream stream; @@ -519,7 +519,7 @@ ErrCode BgContinuousTaskMgr::StopBackgroundRunning(const std::string &abilityNam BGTASK_LOGE("abilityName is empty!"); return ERR_BGTASK_INVALID_PARAM; } - uid_t callingUid = IPCSkeleton::GetCallingUid(); + int32_t callingUid = IPCSkeleton::GetCallingUid(); ErrCode result = ERR_OK; @@ -530,7 +530,7 @@ ErrCode BgContinuousTaskMgr::StopBackgroundRunning(const std::string &abilityNam return result; } -ErrCode BgContinuousTaskMgr::StopBackgroundRunningInner(uid_t uid, const std::string &abilityName, +ErrCode BgContinuousTaskMgr::StopBackgroundRunningInner(int32_t uid, const std::string &abilityName, const sptr &abilityToken) { BGTASK_LOGI("begin"); @@ -829,9 +829,9 @@ void BgContinuousTaskMgr::OnContinuousTaskChanged(const std::shared_ptr continuousTaskCallbackInfo = new ContinuousTaskCallbackInfo( - continuousTaskInfo->GetBgModeId(), continuousTaskInfo->GetUid(), - continuousTaskInfo->GetPid(), continuousTaskInfo->GetAbilityName()); + std::shared_ptr continuousTaskCallbackInfo + = std::make_shared(continuousTaskInfo->GetBgModeId(), + continuousTaskInfo->GetUid(), continuousTaskInfo->GetPid(), continuousTaskInfo->GetAbilityName()); switch (changeEventType) { case ContinuousTaskEventTriggerType::TASK_START: @@ -849,7 +849,7 @@ void BgContinuousTaskMgr::OnContinuousTaskChanged(const std::shared_ptrsecond->GetUid() == uid) { + OnContinuousTaskChanged(iter->second, ContinuousTaskEventTriggerType::TASK_CANCEL); + Notification::NotificationHelper::CancelContinuousTaskNotification( + iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); + iter = continuousTaskInfosMap_.erase(iter); + } else { + iter++; + } + } } else { BGTASK_LOGW("get unregister common event!"); return; diff --git a/services/continuous_task/src/bundle_manager_helper.cpp b/services/continuous_task/src/bundle_manager_helper.cpp index 2281fac9..431f7b7a 100644 --- a/services/continuous_task/src/bundle_manager_helper.cpp +++ b/services/continuous_task/src/bundle_manager_helper.cpp @@ -36,7 +36,7 @@ BundleManagerHelper::~BundleManagerHelper() Disconnect(); } -std::string BundleManagerHelper::GetClientBundleName(uid_t uid) +std::string BundleManagerHelper::GetClientBundleName(int32_t uid) { std::string bundle {""}; std::lock_guard lock(connectionMutex_); @@ -63,7 +63,7 @@ bool BundleManagerHelper::CheckPermission(const std::string &bundleName, return false; } -bool BundleManagerHelper::IsSystemApp(uid_t uid) +bool BundleManagerHelper::IsSystemApp(int32_t uid) { bool isSystemApp = false; std::lock_guard lock(connectionMutex_); diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index a25d387c..163e27c3 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -34,7 +34,7 @@ const char *ContinuousTaskModeName[10] = { ContinuousTaskRecord::ContinuousTaskRecord(const std::string &bundleName, const std::string &abilityName, const std::shared_ptr &wantAgent, const sptr &abilityToken, - int32_t userId, uid_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi) + int32_t userId, int32_t uid, pid_t pid, uint32_t bgModeId, bool isNewApi) : bundleName_(bundleName), abilityName_(abilityName), wantAgent_(wantAgent), abilityToken_(abilityToken), userId_(userId), uid_(uid), pid_(pid), bgModeId_(bgModeId), isNewApi_(isNewApi) {} @@ -63,7 +63,7 @@ int32_t ContinuousTaskRecord::GetUserId() const return userId_; } -uid_t ContinuousTaskRecord::GetUid() const +int32_t ContinuousTaskRecord::GetUid() const { return uid_; } diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp index 8e6d2308..6fa84c3f 100644 --- a/services/continuous_task/src/system_event_observer.cpp +++ b/services/continuous_task/src/system_event_observer.cpp @@ -91,7 +91,8 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &eventD } std::string bundleName = want.GetElement().GetBundleName(); int uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); - BGTASK_LOGI("OnReceiveEvent action = %{public}s, bundle = %{public}s", action.c_str(), bundleName.c_str()); + BGTASK_LOGI("get common event action = %{public}s, bundleName = %{public}s, uid = %{public}d", + action.c_str(), bundleName.c_str(), uid); auto task = [=]() { bgContinuousTaskMgr->OnBundleInfoChanged(action, bundleName, uid); }; handler->PostTask(task, TASK_ON_BUNDLEINFO_CHANGED); } diff --git a/services/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/test/unittest/mock/mock_bundle_manager_helper.cpp index d341c3eb..32a25e1d 100644 --- a/services/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -29,7 +29,7 @@ BundleManagerHelper::BundleManagerHelper() {} BundleManagerHelper::~BundleManagerHelper() {} -std::string BundleManagerHelper::GetClientBundleName(uid_t uid) +std::string BundleManagerHelper::GetClientBundleName(int32_t uid) { return TEST_DEFAULT_BUNDLE; } @@ -40,7 +40,7 @@ bool BundleManagerHelper::CheckPermission(const std::string &bundleName, return true; } -bool BundleManagerHelper::IsSystemApp(uid_t uid) +bool BundleManagerHelper::IsSystemApp(int32_t uid) { return true; } diff --git a/utils/bgtask_observer/src/bgtask_observer.cpp b/utils/bgtask_observer/src/bgtask_observer.cpp index 8e0d594d..91cfc8f6 100644 --- a/utils/bgtask_observer/src/bgtask_observer.cpp +++ b/utils/bgtask_observer/src/bgtask_observer.cpp @@ -27,7 +27,7 @@ void BgTaskObserver::OnContinuousTaskStart(const std::shared_ptrGetTypeId(); - uid_t uid = continuousTaskCallbackInfo->GetCreatorUid(); + int32_t uid = continuousTaskCallbackInfo->GetCreatorUid(); pid_t pid = continuousTaskCallbackInfo->GetCreatorPid(); std::string abiliytName = continuousTaskCallbackInfo->GetAbilityName(); stream.str(""); @@ -47,7 +47,7 @@ void BgTaskObserver::OnContinuousTaskStop(const std::shared_ptrGetTypeId(); - uid_t uid = continuousTaskCallbackInfo->GetCreatorUid(); + int32_t uid = continuousTaskCallbackInfo->GetCreatorUid(); pid_t pid = continuousTaskCallbackInfo->GetCreatorPid(); std::string abiliytName = continuousTaskCallbackInfo->GetAbilityName(); stream.str(""); -- Gitee From 7d4876bb191ff1ea32694715ddc88574dd2a71fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Mon, 21 Feb 2022 19:59:54 +0800 Subject: [PATCH 49/77] modify code dex MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- interfaces/kits/napi/src/common.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/napi/src/common.cpp b/interfaces/kits/napi/src/common.cpp index 9846f9e3..fe7d07cd 100644 --- a/interfaces/kits/napi/src/common.cpp +++ b/interfaces/kits/napi/src/common.cpp @@ -146,7 +146,7 @@ napi_value Common::GetU16StringValue(const napi_env &env, const napi_value &valu size_t strLen = 0; NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); - result = Str8ToStr16(str); + result = Str8ToStr16((std::string)str); BGTASK_LOGI("string result: %{public}s", Str16ToStr8(result).c_str()); } else { return nullptr; -- Gitee From 2eb976f34c1d953f0d53856bedb26794ac3cb0fc Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Tue, 22 Feb 2022 10:22:46 +0800 Subject: [PATCH 50/77] modify readme Signed-off-by: zhangxin_T --- README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ README_ZH.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) diff --git a/README.md b/README.md index 1b5cfa3b..129713e7 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,10 @@ - [Available APIs](#section114564657874) - [Usage Guidelines](#section129654513264) - [Restrictions on Using Transient Tasks](#section1551164914237) +- [Continuous Tasks](#section18532577761) + - [Available APIs](#section19389218787) + - [Usage Guidelines](#section17228995140) + - [Restrictions on Using Continuous Tasks](#section18958419455) - [Repositories Involved](#section1371113476307) @@ -52,12 +56,53 @@ As mentioned above, applications and service modules with transient tasks have t - **When to cancel**:The requesting application shall cancel the request when the transient task is complete. If the request is forcibly canceled by the system, the time frame allowed for the application to run in the background will be affected. - **Quota mechanism**:To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.) +## Continuous Tasks + +### Available APIs + +| API | Description | +|------------------------------------------------------------------------------------------|-------------| +| function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void; | When the service is started, apply to the system for continuousterm tasks so that the service keeps running in the background (callback). | +| function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>; | When the service is started, apply to the system for continuous tasks so that the service keeps running in the background (promise). | +| function stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void; | Stopping continuous tasks running in background(callback) | +| function stopBackgroundRunning(context: Context): Promise<void>; | Stopping continuous tasks running in background(promise) | + +### Usage Guidelines + +Continuous tasks guarantee the life cycle of services that users can intuitively feel and need to run in the background. For example, services need to play sound and continuously navigate in the background. Users can intuitively perceive the background service behaviors and use the background mode corresponding to continuous tasks to ensure the running of services in the background and support applications to complete operation in the background. + +OpenHarmony offers 9 kinds of background modes for businesses that need to do continuous tasks in the background + +| BackgroundMode | interface parameters | Instructions | The prompt in notification bar | note | +| -------- | ------- | -------- | -------- | -------- | +| dataTransfer | DATA_TRANSFER | Download, back up, share, and transfer data through the network or peer device etc | Running data transfer task | | +| audioPlayback | AUDIO_PLAYBACK | Audio output | Running audio playback task | | +| audioRecording | AUDIO_RECORDING | Audio input | Running recording task | | +| location | LOCATION | Positioning and navigation | Running location task | | +| bluetoothInteraction | BLUETOOTH_INTERACTION | Bluetooth transmission | Running bluetooth related task | | +| multiDeviceConnection | MULTI_DEVICE_CONNECTION | Distributed interconnection task | Running distributed task | | +| wifiInteraction | WIFI_INTERACTION | WLAN transmission | Running WLAN related task | SystemApi,only supported for system app | +| voip | VOIP | Voice over Internet Phone | Running voip task | SystemApi,only supported for system app | +| taskKeeping | TASK_KEEPING | Computing tasks | Running computing task | PC specialty only supported in pc device | + +#### Restrictions on Using Continuous Tasks + +- If user selects aware services (such as broadcasting, navigation, and uploading and downloading), the background mode is triggered. When a task is started, the system forcibly displays a notification to remind the user. +- If the task ends, the application should actively exit background mode. If the system detects that an application does not use resources in the corresponding background mode during background running, it suspends. +- Do not apply for continuous tasks improperly. The type of the continuous tasks must match the service type of the application. If a task is executed that does not match the requested type, the system detects it and suspends it. +- A continuous task is intended to be executed in the background for a long time. If an application applies for a continuous task but does not actually run or execute such a task, the system detects and suspends it. +- A ability can only apply to run one continuous task at a time. + ## Repositories Involved Resource Schedule subsystem **background\_task\_mgr** +notification_ans_standard + notification_ces_standard appexecfwk_standard + +account_os_account \ No newline at end of file diff --git a/README_ZH.md b/README_ZH.md index ab54d4e2..6bf7b298 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -6,6 +6,10 @@ - [接口说明](#section114564657874) - [使用说明](#section129654513264) - [短时任务使用约束](#section1551164914237) +- [长时任务](#section18532577761) + - [接口说明](#section19389218787) + - [使用说明](#section17228995140) + - [长时任务使用约束](#section18958419455) - [相关仓](#section1371113476307) @@ -52,12 +56,53 @@ - **取消时机**:任务完成后申请方应用主动取消延时申请,不要等到超时后被系统取消,否则会影响该应用的后台允许运行时长配额。 - **配额机制**:为了防止应用滥用保活,或者申请后不取消,每个应用每天都会有一定配额(会根据用户的使用习惯动态调整),配额消耗完就不再允许申请短时任务,所以应用完成短时任务后立刻取消延时申请,避免消耗配额。(注,这个配额指的是申请的时长,系统默认应用在后台运行的时间不计算在内。) +## 长时任务 + +### 接口说明 + +| 接口名 | 接口描述 | +|------------------------------------------------------------------------------------------|-------------| +| function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void; | 服务启动后,向系统申请长时任务,使服务一直保持后台运行(callback形式) | +| function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>; | 服务启动后,向系统申请长时任务,使服务一直保持后台运行(promise形式) | +| function stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void; | 停止后台长时任务的运行(callback形式) | +| function stopBackgroundRunning(context: Context): Promise<void>; | 停止后台长时任务的运行(promise形式) | + +### 使用说明 + +长时任务给用户能够直观感受到的且需要一直在后台运行的业务提供后台运行生命周期的保障。比如:业务需要在后台播放声音、需要在后台持续导航定位等。此类用户可以直观感知到的后台业务行为,可以通过使用长时任务对应的后台模式保障业务在后台的运行,支撑应用完成在后台的业务。 + +OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业务使用 + +| BackgroundMode | 接口参数 | 说明 | 通知栏显示提示 | 备注 | +| -------- | -------- | -------- | -------- | -------- | +| dataTransfer | DATA_TRANSFER | 通过网络/对端设备进行数据下载、备份、分享、传输等 | 正在运行数据传输任务 | | +| audioPlayback | AUDIO_PLAYBACK | 音频输出 | 正在运行音频播放任务 | | +| audioRecording | AUDIO_RECORDING | 音频输入 | 正在运行录音任务 | | +| location | LOCATION | 定位、导航 | 正在运行定位任务 | | +| bluetoothInteraction | BLUETOOTH_INTERACTION | 蓝牙传输 | 正在运行蓝牙相关任务 | | +| multiDeviceConnection | MULTI_DEVICE_CONNECTION | 分布式互联任务 | 正在运行分布式任务 | | +| wifiInteraction | WIFI_INTERACTION | WLAN传输 | 正在运行WLAN相关任务 | SystemApi,仅对System权限应用开放 | +| voip | VOIP | 音视频电话、VOIP | 正在运行通话相关任务 | SystemApi,仅对System权限应用开放 | +| taskKeeping | TASK_KEEPING | 计算任务 | 正在运行计算任务 | PC特有,仅在PC申请生效 | + +#### 长时任务使用约束 + +- 如果用户选择可感知业务(如播音、导航、上传下载等),触发对应后台模式,在任务启动时,系统会强制弹出通知提醒用户。 +- 如果任务结束,应用应主动退出后台模式。若在后台运行期间,系统检测到应用并未使用对应后台模式的资源,则会被挂起(Suspend)。 +- 避免不合理地申请后台长时任务,长时任务类型要与应用的业务类型匹配。如果执行的任务和申请的类型不匹配,也会被系统检测到并被挂起(Suspend)。 +- 长时任务是为了真正在后台长时间执行某个任务,如果一个应用申请了长时任务,但在实际运行过程中,并未真正运行或执行此类任务时,也会被系统检测到并被挂起(Suspend)。 +- 每个Ability同一时刻只能申请运行一个长时任务。 + ## 相关仓 资源调度子系统 **background\_task\_mgr** +notification_ans_standard + notification_ces_standard appexecfwk_standard + +account_os_account \ No newline at end of file -- Gitee From eec16575b45c6833d925b5c533470317b9604010 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Thu, 24 Feb 2022 11:31:43 +0800 Subject: [PATCH 51/77] napi interface adapt stage model Signed-off-by: zhangxin_T --- interfaces/kits/BUILD.gn | 2 + .../src/bg_continuous_task_napi_module.cpp | 140 +++++++++--------- 2 files changed, 74 insertions(+), 68 deletions(-) diff --git a/interfaces/kits/BUILD.gn b/interfaces/kits/BUILD.gn index af3a4424..609dbf04 100644 --- a/interfaces/kits/BUILD.gn +++ b/interfaces/kits/BUILD.gn @@ -39,7 +39,9 @@ ohos_shared_library("backgroundtaskmanager") { external_deps = [ "ability_base:want", + "ability_runtime:ability_context_native", "ability_runtime:abilitykit_native", + "ability_runtime:napi_base_context", "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "dmsfwk_standard:zuri", diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp index f2887f77..71353988 100644 --- a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -14,14 +14,16 @@ */ #include "bg_continuous_task_napi_module.h" + +#include "ability.h" +#include "want_agent.h" +#include "napi_base_context.h" + +#include "background_mode.h" +#include "background_task_mgr_helper.h" #include "bgtaskmgr_inner_errors.h" #include "continuous_task_log.h" -#include "background_mode.h" #include "continuous_task_param.h" -#include "ability.h" -#include "background_task_mgr_helper.h" -#include "fcntl.h" -#include "want_agent.h" namespace OHOS { namespace BackgroundTaskMgr { @@ -38,7 +40,7 @@ struct AsyncCallbackInfo { napi_ref callback {nullptr}; napi_async_work asyncWork {nullptr}; napi_deferred deferred {nullptr}; - AppExecFwk::Ability *ability {nullptr}; + std::shared_ptr abilityContext {nullptr}; int32_t bgMode {0}; AbilityRuntime::WantAgent::WantAgent *wantAgent {nullptr}; int errCode {0}; @@ -68,50 +70,40 @@ napi_value GetCallbackErrorValue(napi_env env, int errCode) return jsObject; } -AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env) +napi_value GetAbilityContext(const napi_env &env, const napi_value &value, + std::shared_ptr &abilityContext) { - BGTASK_LOGI("begin"); - if (env == nullptr) { - BGTASK_LOGE("env is nullptr."); - return nullptr; - } - - napi_status ret; - napi_value global = 0; - const napi_extended_error_info *errorInfo = nullptr; - ret = napi_get_global(env, &global); - if (ret != napi_ok) { - napi_get_last_error_info(env, &errorInfo); - BGTASK_LOGE("get_global=%{public}d err:%{public}s", ret, errorInfo->error_message); - } - - napi_value abilityObj = 0; - ret = napi_get_named_property(env, global, "ability", &abilityObj); - if (ret != napi_ok) { - napi_get_last_error_info(env, &errorInfo); - BGTASK_LOGE("get_named_property=%{public}d err:%{public}s", ret, errorInfo->error_message); - } - - OHOS::AppExecFwk::Ability *ability = nullptr; - ret = napi_get_value_external(env, abilityObj, (void **)&ability); - if (ret != napi_ok) { - napi_get_last_error_info(env, &errorInfo); - BGTASK_LOGE("get_value_external=%{public}d err:%{public}s", ret, errorInfo->error_message); - } - - AsyncCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo; - if (asyncCallbackInfo == nullptr) { - BGTASK_LOGE("asyncCallbackInfo is nullptr"); - return nullptr; + bool stageMode = false; + napi_status status = OHOS::AbilityRuntime::IsStageContext(env, value, stageMode); + BGTASK_LOGI("is stage mode: %{public}s", stageMode ? "true" : "false"); + + if (status != napi_ok || !stageMode) { + BGTASK_LOGI("Getting context with FA model"); + auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env); + if (!ability) { + BGTASK_LOGE("Failed to get native ability instance"); + return nullptr; + } + abilityContext = ability->GetAbilityContext(); + if (!abilityContext) { + BGTASK_LOGE("get FA model ability context failed"); + return nullptr; + } + return WrapVoidToJS(env); + } else { + BGTASK_LOGI("Getting context with stage model"); + auto context = AbilityRuntime::GetStageModeContext(env, value); + if (!context) { + BGTASK_LOGE("get context failed"); + return nullptr; + } + abilityContext = AbilityRuntime::Context::ConvertTo(context); + if (!abilityContext) { + BGTASK_LOGE("get Stage model ability context failed"); + return nullptr; + } + return WrapVoidToJS(env); } - asyncCallbackInfo->env = env; - asyncCallbackInfo->asyncWork = nullptr; - asyncCallbackInfo->deferred = nullptr; - asyncCallbackInfo->ability = ability; - asyncCallbackInfo->errCode = ERR_OK; - - BGTASK_LOGI("end"); - return asyncCallbackInfo; } void StartBackgroundRunningExecuteCB(napi_env env, void *data) @@ -126,14 +118,14 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) BGTASK_LOGE("input params parse failed"); return; } - if (asyncCallbackInfo->ability == nullptr) { + if (asyncCallbackInfo->abilityContext == nullptr) { asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; - BGTASK_LOGE("ability is nullptr"); + BGTASK_LOGE("abilityContext is null"); return; } - const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); + const std::shared_ptr info = asyncCallbackInfo->abilityContext->GetAbilityInfo(); if (info == nullptr) { - BGTASK_LOGE("info is nullptr"); + BGTASK_LOGE("ability info is null"); asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; return; } @@ -144,11 +136,11 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) return; } - sptr token {nullptr}; - auto abilityContext = asyncCallbackInfo->ability->GetAbilityContext(); - if (abilityContext) { - BGTASK_LOGI("get ability context succeed"); - token = abilityContext->GetToken(); + sptr token = asyncCallbackInfo->abilityContext->GetToken(); + if (!token) { + BGTASK_LOGE("get ability token info failed"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; } if (asyncCallbackInfo->bgMode < BG_MODE_ID_BEGIN || asyncCallbackInfo->bgMode > BG_MODE_ID_END) { @@ -294,7 +286,7 @@ napi_value GetWantAgent(const napi_env &env, const napi_value &value, AbilityRun napi_value StartBackgroundRunning(napi_env env, napi_callback_info info) { BGTASK_LOGI("begin"); - AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + AsyncCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo {.env = env}; if (asyncCallbackInfo == nullptr) { BGTASK_LOGE("asyncCallbackInfo == nullpter"); return WrapVoidToJS(env); @@ -310,6 +302,12 @@ napi_value StartBackgroundRunning(napi_env env, napi_callback_info info) return nullptr; } + // argv[0] : context : AbilityContext + if (GetAbilityContext(env, argv[0], asyncCallbackInfo->abilityContext) == nullptr) { + BGTASK_LOGE("Get ability context failed"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + } + // argv[1] : bgMode : BackgroundMode if (GetBackgroundMode(env, argv[1], asyncCallbackInfo->bgMode) == nullptr) { BGTASK_LOGE("input bgmode param not number"); @@ -350,23 +348,23 @@ void StopBackgroundRunningExecuteCB(napi_env env, void *data) BGTASK_LOGE("asyncCallbackInfo is nullptr"); return; } - if (asyncCallbackInfo->ability == nullptr) { + if (asyncCallbackInfo->abilityContext == nullptr) { asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; - BGTASK_LOGE("ability is nullptr"); + BGTASK_LOGE("ability context is null"); return; } - const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); + const std::shared_ptr info = asyncCallbackInfo->abilityContext->GetAbilityInfo(); if (info == nullptr) { - BGTASK_LOGE("abilityInfo is nullptr"); + BGTASK_LOGE("abilityInfo is null"); asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; return; } - sptr token {nullptr}; - auto abilityContext = asyncCallbackInfo->ability->GetAbilityContext(); - if (abilityContext) { - BGTASK_LOGI("get ability context succeed"); - token = abilityContext->GetToken(); + sptr token = asyncCallbackInfo->abilityContext->GetToken(); + if (!token) { + BGTASK_LOGE("get ability token info failed"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + return; } asyncCallbackInfo->errCode = BackgroundTaskMgrHelper::RequestStopBackgroundRunning(info->name, token); } @@ -431,7 +429,7 @@ napi_value StopBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCa napi_value StopBackgroundRunning(napi_env env, napi_callback_info info) { BGTASK_LOGI("begin"); - AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + AsyncCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo {.env = env}; if (asyncCallbackInfo == nullptr) { BGTASK_LOGE("asyncCallbackInfo is nullpter"); return WrapVoidToJS(env); @@ -448,6 +446,12 @@ napi_value StopBackgroundRunning(napi_env env, napi_callback_info info) return nullptr; } + // argv[0] : context : AbilityContext + if (GetAbilityContext(env, argv[0], asyncCallbackInfo->abilityContext) == nullptr) { + BGTASK_LOGE("Get ability context failed"); + asyncCallbackInfo->errCode = ERR_BGTASK_INVALID_PARAM; + } + napi_value ret = 0; if (argc == MAX_STOP_BG_RUNNING_PARAMS) { ret = StopBackgroundRunningAsync(env, argv, MAX_STOP_BG_RUNNING_PARAMS - 1, asyncCallbackInfo); -- Gitee From 6ff5a1c9b482fb6a13dabd019d3393320175bf40 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Thu, 24 Feb 2022 12:50:56 +0800 Subject: [PATCH 52/77] codeCheck bugfix Signed-off-by: zhangxin_T --- interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp index 71353988..47b96c94 100644 --- a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -71,7 +71,7 @@ napi_value GetCallbackErrorValue(napi_env env, int errCode) } napi_value GetAbilityContext(const napi_env &env, const napi_value &value, - std::shared_ptr &abilityContext) + std::shared_ptr &abilityContext) { bool stageMode = false; napi_status status = OHOS::AbilityRuntime::IsStageContext(env, value, stageMode); -- Gitee From 652993c63c05ffcd6661e9dc3222705331834950 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 24 Feb 2022 19:42:19 +0800 Subject: [PATCH 53/77] add uv queue work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- .../kits/napi/src/request_suspend_delay.cpp | 66 ++++++++++++++++++- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/interfaces/kits/napi/src/request_suspend_delay.cpp b/interfaces/kits/napi/src/request_suspend_delay.cpp index ab7ae7dd..829028e3 100644 --- a/interfaces/kits/napi/src/request_suspend_delay.cpp +++ b/interfaces/kits/napi/src/request_suspend_delay.cpp @@ -19,11 +19,17 @@ #include "background_task_manager.h" #include "transient_task_log.h" +#include namespace OHOS { namespace BackgroundTaskMgr { static const int32_t REQUEST_SUSPEND_DELAY_PARAMS = 2; +struct CallbackReceiveDataWorker { + napi_env env = nullptr; + napi_ref ref = nullptr; +}; + CallbackInstance::CallbackInstance() {} CallbackInstance::~CallbackInstance() @@ -33,6 +39,31 @@ CallbackInstance::~CallbackInstance() } } +void UvQueueWorkOnExpired(uv_work_t *work, int status) +{ + BGTASK_LOGI("OnExpired uv_work_t start"); + + if (work == nullptr) { + BGTASK_LOGE("work is null"); + return; + } + + CallbackReceiveDataWorker *dataWorkerData = (CallbackReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + BGTASK_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; + return; + } + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; +} + void CallbackInstance::OnExpired() { BGTASK_LOGI("enter"); @@ -42,8 +73,39 @@ void CallbackInstance::OnExpired() return; } - Common::SetCallback(expiredCallbackInfo_.env, expiredCallbackInfo_.ref, - Common::NapiGetNull(expiredCallbackInfo_.env)); + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(expiredCallbackInfo_.env, &loop); + if (loop == nullptr) { + BGTASK_LOGE("loop instance is nullptr"); + return; + } + + CallbackReceiveDataWorker *dataWorker = new (std::nothrow) CallbackReceiveDataWorker(); + if (dataWorker == nullptr) { + BGTASK_LOGE("new dataWorker failed"); + return; + } + + dataWorker->env = expiredCallbackInfo_.env; + dataWorker->ref = expiredCallbackInfo_.ref; + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + BGTASK_LOGE("new work failed"); + delete dataWorker; + dataWorker = nullptr; + return; + } + + work->data = (void *)dataWorker; + + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnExpired); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } } void CallbackInstance::SetCallbackInfo(const napi_env &env, const napi_ref &ref) -- Gitee From 4e1cd2e970bc9cd6989e62270d28c3b5924c48f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 24 Feb 2022 19:54:25 +0800 Subject: [PATCH 54/77] add uv queue work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- interfaces/kits/napi/src/request_suspend_delay.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/napi/src/request_suspend_delay.cpp b/interfaces/kits/napi/src/request_suspend_delay.cpp index 829028e3..89b3c30b 100644 --- a/interfaces/kits/napi/src/request_suspend_delay.cpp +++ b/interfaces/kits/napi/src/request_suspend_delay.cpp @@ -16,10 +16,10 @@ #include "request_suspend_delay.h" #include "singleton.h" +#include #include "background_task_manager.h" #include "transient_task_log.h" -#include namespace OHOS { namespace BackgroundTaskMgr { -- Gitee From b0fbcab3bff032adfb9781234747dced65851f20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Thu, 24 Feb 2022 20:01:23 +0800 Subject: [PATCH 55/77] add uv queue work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- interfaces/kits/napi/src/request_suspend_delay.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/napi/src/request_suspend_delay.cpp b/interfaces/kits/napi/src/request_suspend_delay.cpp index 89b3c30b..5ab8d988 100644 --- a/interfaces/kits/napi/src/request_suspend_delay.cpp +++ b/interfaces/kits/napi/src/request_suspend_delay.cpp @@ -15,9 +15,10 @@ #include "request_suspend_delay.h" -#include "singleton.h" #include +#include "singleton.h" + #include "background_task_manager.h" #include "transient_task_log.h" -- Gitee From a73b03bd266484646da2f30097c6ad62bfd4e56e Mon Sep 17 00:00:00 2001 From: wplan1 Date: Mon, 28 Feb 2022 16:31:43 +0800 Subject: [PATCH 56/77] add rawfd Signed-off-by: wplan1 --- services/test/unittest/mock/mock_resource_manager.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp index b0493fce..eafdc2a3 100644 --- a/services/test/unittest/mock/mock_resource_manager.cpp +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -203,6 +203,11 @@ RState ResourceManagerImpl::GetRawFilePathByName(const std::string &name, std::s { return SUCCESS; } + +RState ResourceManagerImpl::GetRawFileDescriptor(const std::string &name, RawFileDescriptor &descriptor) +{ + return SUCCESS; +} } } } \ No newline at end of file -- Gitee From 580e930bd8ea5e7ce6fc5ef897fe1e2de327bfdd Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Mon, 28 Feb 2022 17:08:22 +0800 Subject: [PATCH 57/77] codex bugfix Signed-off-by: zhangxin_T --- .../src/continuous_task_callback_info.cpp | 2 +- .../napi/src/bg_continuous_task_napi_module.cpp | 3 ++- .../continuous_task/src/app_state_observer.cpp | 2 +- .../src/bg_continuous_task_mgr.cpp | 8 ++++++-- .../continuous_task/src/bundle_manager_helper.cpp | 6 +++--- .../test/unittest/bg_continuous_task_mgr_test.cpp | 15 ++++++++++----- 6 files changed, 23 insertions(+), 13 deletions(-) diff --git a/interfaces/innerkits/src/continuous_task_callback_info.cpp b/interfaces/innerkits/src/continuous_task_callback_info.cpp index ac3aee2d..9be2f68f 100644 --- a/interfaces/innerkits/src/continuous_task_callback_info.cpp +++ b/interfaces/innerkits/src/continuous_task_callback_info.cpp @@ -70,7 +70,7 @@ bool ContinuousTaskCallbackInfo::Marshalling(Parcel &parcel) const ContinuousTaskCallbackInfo *ContinuousTaskCallbackInfo::Unmarshalling(Parcel &parcel) { - auto object = new ContinuousTaskCallbackInfo(); + auto object = new (std::nothrow) ContinuousTaskCallbackInfo(); if ((object != nullptr) && !object->ReadFromParcel(parcel)) { delete object; object = nullptr; diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp index 47b96c94..b9a5b029 100644 --- a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -199,8 +199,9 @@ void PromiseCompletedCB(napi_env env, napi_status status, void *data) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - BGTASK_LOGI("end"); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + BGTASK_LOGI("end"); } napi_value StartBackgroundRunningAsync( diff --git a/services/continuous_task/src/app_state_observer.cpp b/services/continuous_task/src/app_state_observer.cpp index b9d050c5..ad2d2951 100644 --- a/services/continuous_task/src/app_state_observer.cpp +++ b/services/continuous_task/src/app_state_observer.cpp @@ -28,7 +28,7 @@ const std::string TASK_ON_PROCESS_DIED = "OnProcessDiedTask"; AppStateObserver::AppStateObserver() { - appMgrDeathRecipient_ = new RemoteDeathRecipient(std::bind(&AppStateObserver::OnRemoteDied, + appMgrDeathRecipient_ = new (std::nothrow) RemoteDeathRecipient(std::bind(&AppStateObserver::OnRemoteDied, this, std::placeholders::_1)); } diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 6af7dd8e..49219d10 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -591,8 +591,12 @@ ErrCode BgContinuousTaskMgr::AddSubscriberInner(const sptrAsObject()) != subscriberRecipients_.end()) { return ERR_BGTASK_OBJECT_EXISTS; } - sptr deathRecipient = - new RemoteDeathRecipient([this](const wptr &remote) { this->OnRemoteSubscriberDied(remote); }); + sptr deathRecipient = new (std::nothrow) RemoteDeathRecipient( + [this](const wptr &remote) { this->OnRemoteSubscriberDied(remote); }); + if (!deathRecipient) { + BGTASK_LOGE("create death recipient failed"); + return ERR_BGTASK_INVALID_PARAM; + } subscriber->AsObject()->AddDeathRecipient(deathRecipient); subscriberRecipients_.emplace(subscriber->AsObject(), deathRecipient); subscriber->OnConnected(); diff --git a/services/continuous_task/src/bundle_manager_helper.cpp b/services/continuous_task/src/bundle_manager_helper.cpp index 431f7b7a..0b144d40 100644 --- a/services/continuous_task/src/bundle_manager_helper.cpp +++ b/services/continuous_task/src/bundle_manager_helper.cpp @@ -26,7 +26,7 @@ using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED; BundleManagerHelper::BundleManagerHelper() { - bundleMgrDeathRecipient_ = new RemoteDeathRecipient( + bundleMgrDeathRecipient_ = new (std::nothrow) RemoteDeathRecipient( [this](const wptr &object) { this->OnRemoteDied(object); }); } @@ -107,7 +107,7 @@ bool BundleManagerHelper::Connect() } bundleMgr_ = iface_cast(remoteObject); - if (bundleMgr_ != nullptr) { + if (bundleMgr_ != nullptr && bundleMgrDeathRecipient_ != nullptr) { bundleMgr_->AsObject()->AddDeathRecipient(bundleMgrDeathRecipient_); return true; } @@ -117,7 +117,7 @@ bool BundleManagerHelper::Connect() void BundleManagerHelper::Disconnect() { - if (bundleMgr_ != nullptr) { + if (bundleMgr_ != nullptr && bundleMgrDeathRecipient_ != nullptr) { bundleMgr_->AsObject()->RemoveDeathRecipient(bundleMgrDeathRecipient_); bundleMgr_ = nullptr; } diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp index e6bb7be2..12e9c5fc 100644 --- a/services/test/unittest/bg_continuous_task_mgr_test.cpp +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -90,7 +90,8 @@ public: HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_001, TestSize.Level1) { EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(nullptr), (int)ERR_BGTASK_INVALID_PARAM); - sptr taskParam = new ContinuousTaskParam(); + sptr taskParam = new (std::nothrow) ContinuousTaskParam(); + EXPECT_NE(taskParam, nullptr); taskParam->isNewApi_ = true; EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(taskParam), (int)ERR_BGTASK_INVALID_PARAM); taskParam->wantAgent_ = std::make_shared(); @@ -116,7 +117,8 @@ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_001, TestSize.Level1) HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) { EXPECT_EQ((int)bgContinuousTaskMgr_->StartBackgroundRunning(nullptr), (int)ERR_BGTASK_INVALID_PARAM); - sptr taskParam = new ContinuousTaskParam(); + sptr taskParam = new (std::nothrow) ContinuousTaskParam(); + EXPECT_NE(taskParam, nullptr); taskParam->isNewApi_ = false; taskParam->bgModeId_ = 0; taskParam->abilityName_ = ""; @@ -133,7 +135,8 @@ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) */ HWTEST_F(BgContinuousTaskMgrTest, StopBackgroundRunning_001, TestSize.Level1) { - sptr taskParam = new ContinuousTaskParam(); + sptr taskParam = new (std::nothrow) ContinuousTaskParam(); + EXPECT_NE(taskParam, nullptr); taskParam->wantAgent_ = std::make_shared(); taskParam->abilityName_ = "ability1"; taskParam->bgModeId_ = 1; @@ -156,7 +159,8 @@ HWTEST_F(BgContinuousTaskMgrTest, SubscribeContinuousTask_001, TestSize.Level1) { EXPECT_EQ((int)bgContinuousTaskMgr_->AddSubscriber(nullptr), (int)ERR_BGTASK_INVALID_PARAM); SleepForFC(); - auto subscriber = new TestBackgroundTaskSubscriber(); + auto subscriber = new (std::nothrow) TestBackgroundTaskSubscriber(); + EXPECT_NE(subscriber, nullptr); EXPECT_EQ((int)bgContinuousTaskMgr_->AddSubscriber(subscriber->GetImpl()), (int)ERR_OK); SleepForFC(); EXPECT_EQ((int)bgContinuousTaskMgr_->AddSubscriber(subscriber->GetImpl()), (int)ERR_BGTASK_OBJECT_EXISTS); @@ -172,7 +176,8 @@ HWTEST_F(BgContinuousTaskMgrTest, UnsubscribeContinuousTask_001, TestSize.Level1 { EXPECT_EQ((int)bgContinuousTaskMgr_->RemoveSubscriber(nullptr), (int)ERR_BGTASK_INVALID_PARAM); SleepForFC(); - auto subscriber = new TestBackgroundTaskSubscriber(); + auto subscriber = new (std::nothrow) TestBackgroundTaskSubscriber(); + EXPECT_NE(subscriber, nullptr); bgContinuousTaskMgr_->AddSubscriber(subscriber->GetImpl()); SleepForFC(); EXPECT_EQ((int)bgContinuousTaskMgr_->RemoveSubscriber(subscriber->GetImpl()), (int)ERR_OK); -- Gitee From a9823c0ade1a83ad3b9a7e0234af4f3aaa7dab1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Mon, 28 Feb 2022 20:13:07 +0800 Subject: [PATCH 58/77] add nothrow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- frameworks/src/background_task_manager.cpp | 2 +- interfaces/innerkits/src/background_task_subscriber.cpp | 2 +- interfaces/innerkits/src/expired_callback.cpp | 2 +- services/transient_task/src/bg_transient_task_mgr.cpp | 8 ++++---- services/transient_task/src/decision_maker.cpp | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/frameworks/src/background_task_manager.cpp b/frameworks/src/background_task_manager.cpp index ded9427f..8c96b916 100644 --- a/frameworks/src/background_task_manager.cpp +++ b/frameworks/src/background_task_manager.cpp @@ -145,7 +145,7 @@ bool BackgroundTaskManager::GetBackgroundTaskManagerProxy() return false; } - recipient_ = new BgTaskMgrDeathRecipient(*this); + recipient_ = new (std::nothrow) BgTaskMgrDeathRecipient(*this); if (recipient_ == nullptr) { return false; } diff --git a/interfaces/innerkits/src/background_task_subscriber.cpp b/interfaces/innerkits/src/background_task_subscriber.cpp index ad56a6f9..568a9f82 100644 --- a/interfaces/innerkits/src/background_task_subscriber.cpp +++ b/interfaces/innerkits/src/background_task_subscriber.cpp @@ -22,7 +22,7 @@ namespace OHOS { namespace BackgroundTaskMgr { BackgroundTaskSubscriber::BackgroundTaskSubscriber() { - impl_ = new BackgroundTaskSubscriberImpl(*this); + impl_ = new (std::nothrow) BackgroundTaskSubscriberImpl(*this); }; BackgroundTaskSubscriber::~BackgroundTaskSubscriber() {} diff --git a/interfaces/innerkits/src/expired_callback.cpp b/interfaces/innerkits/src/expired_callback.cpp index 239f158d..ee097d70 100644 --- a/interfaces/innerkits/src/expired_callback.cpp +++ b/interfaces/innerkits/src/expired_callback.cpp @@ -19,7 +19,7 @@ namespace OHOS { namespace BackgroundTaskMgr { ExpiredCallback::ExpiredCallback() { - impl_ = new ExpiredCallbackImpl(*this); + impl_ = new (std::nothrow) ExpiredCallbackImpl(*this); }; ExpiredCallback::~ExpiredCallback() {} diff --git a/services/transient_task/src/bg_transient_task_mgr.cpp b/services/transient_task/src/bg_transient_task_mgr.cpp index e03d78a5..5a9045f1 100644 --- a/services/transient_task/src/bg_transient_task_mgr.cpp +++ b/services/transient_task/src/bg_transient_task_mgr.cpp @@ -66,10 +66,10 @@ void BgTransientTaskMgr::Init() if (!handler_) { BGTASK_LOGE("Failed to init due to create handler error"); } - callbackDeathRecipient_ = - new ExpiredCallbackDeathRecipient(DelayedSingleton::GetInstance().get()); - susriberDeathRecipient_ = - new SubscriberDeathRecipient(DelayedSingleton::GetInstance().get()); + callbackDeathRecipient_ = new (std::nothrow) + ExpiredCallbackDeathRecipient(DelayedSingleton::GetInstance().get()); + susriberDeathRecipient_ = new (std::nothrow) + SubscriberDeathRecipient(DelayedSingleton::GetInstance().get()); InitNecessaryState(); } diff --git a/services/transient_task/src/decision_maker.cpp b/services/transient_task/src/decision_maker.cpp index 7d16d212..10287080 100644 --- a/services/transient_task/src/decision_maker.cpp +++ b/services/transient_task/src/decision_maker.cpp @@ -75,7 +75,7 @@ bool DecisionMaker::GetAppMgrProxy() observer_ = new (std::nothrow) ApplicationStateObserver(*this); appMgrProxy_->RegisterApplicationStateObserver(iface_cast(observer_)); - recipient_ = new AppMgrDeathRecipient(*this); + recipient_ = new (std::nothrow) AppMgrDeathRecipient(*this); if (recipient_ == nullptr) { return false; } -- Gitee From 19e25fa59ba4454dcdb21df61e2bfd5d8dfcaed1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Mon, 28 Feb 2022 20:26:03 +0800 Subject: [PATCH 59/77] add nothrow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- services/transient_task/src/decision_maker.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/transient_task/src/decision_maker.cpp b/services/transient_task/src/decision_maker.cpp index 10287080..08aaf941 100644 --- a/services/transient_task/src/decision_maker.cpp +++ b/services/transient_task/src/decision_maker.cpp @@ -73,6 +73,9 @@ bool DecisionMaker::GetAppMgrProxy() return false; } observer_ = new (std::nothrow) ApplicationStateObserver(*this); + if (observer_ == nullptr) { + return false; + } appMgrProxy_->RegisterApplicationStateObserver(iface_cast(observer_)); recipient_ = new (std::nothrow) AppMgrDeathRecipient(*this); -- Gitee From d7a52c61b229c6da4b5a825ab612096c061a99c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Tue, 1 Mar 2022 09:58:31 +0800 Subject: [PATCH 60/77] initialize param MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- interfaces/kits/napi/src/get_remaining_delay_time.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/interfaces/kits/napi/src/get_remaining_delay_time.cpp b/interfaces/kits/napi/src/get_remaining_delay_time.cpp index 88c2deeb..927f9032 100644 --- a/interfaces/kits/napi/src/get_remaining_delay_time.cpp +++ b/interfaces/kits/napi/src/get_remaining_delay_time.cpp @@ -28,13 +28,13 @@ static const int32_t GET_REMAINING_DELAY_TIME_PARAMS = 2; struct AsyncCallbackInfoGetRemainingDelayTime { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - int32_t requestId; - int32_t delayTime; + int32_t requestId = 0; + int32_t delayTime = 0; CallbackPromiseInfo info; }; struct GetRemainingDelayTimeParamsInfo { - int32_t requestId; + int32_t requestId = 0; napi_ref callback = nullptr; }; -- Gitee From a03124f215a2a4879278aade6b4a7c8328f4c48b Mon Sep 17 00:00:00 2001 From: wplan1 Date: Wed, 2 Mar 2022 18:06:07 +0800 Subject: [PATCH 61/77] add closerawfd Signed-off-by: wplan1 --- services/test/unittest/mock/mock_resource_manager.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp index eafdc2a3..7b92c5a7 100644 --- a/services/test/unittest/mock/mock_resource_manager.cpp +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -208,6 +208,11 @@ RState ResourceManagerImpl::GetRawFileDescriptor(const std::string &name, RawFil { return SUCCESS; } + +RState ResourceManagerImpl::CloseRawFileDescriptor(const std::string &name) +{ + return SUCCESS; +} } } } \ No newline at end of file -- Gitee From b3b8becc52efa3ef5b7ede60c9e7dc45f34e3fca Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Thu, 3 Mar 2022 11:34:56 +0800 Subject: [PATCH 62/77] observe ability life cycle state and check current device type Signed-off-by: zhangxin_T --- .../innerkits/src/continuous_task_param.cpp | 4 +- services/BUILD.gn | 1 - .../include/app_state_observer.h | 1 + .../include/bg_continuous_task_mgr.h | 10 +-- .../include/os_account_observer.h | 45 ---------- .../src/app_state_observer.cpp | 27 ++++++ .../src/bg_continuous_task_mgr.cpp | 65 +++++++++------ .../src/os_account_observer.cpp | 82 ------------------- .../transient_task/src/decision_maker.cpp | 4 +- 9 files changed, 78 insertions(+), 161 deletions(-) delete mode 100644 services/continuous_task/include/os_account_observer.h delete mode 100644 services/continuous_task/src/os_account_observer.cpp diff --git a/interfaces/innerkits/src/continuous_task_param.cpp b/interfaces/innerkits/src/continuous_task_param.cpp index a888b03a..6b79d16c 100644 --- a/interfaces/innerkits/src/continuous_task_param.cpp +++ b/interfaces/innerkits/src/continuous_task_param.cpp @@ -79,7 +79,7 @@ bool ContinuousTaskParam::Marshalling(Parcel &parcel) const return false; } bool valid = false; - valid = wantAgent_ ? true : false; + valid = wantAgent_ != nullptr; if (!parcel.WriteBool(valid)) { BGTASK_LOGE("Failed to write the flag which indicate whether wantAgent is null"); return false; @@ -96,7 +96,7 @@ bool ContinuousTaskParam::Marshalling(Parcel &parcel) const return false; } - valid = abilityToken_ ? true : false; + valid = abilityToken_ != nullptr; if (!parcel.WriteBool(valid)) { BGTASK_LOGE("Failed to write the flag which indicate whether ability token is null"); return false; diff --git a/services/BUILD.gn b/services/BUILD.gn index 321cbae5..97d82e2a 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -29,7 +29,6 @@ ohos_shared_library("bgtaskmgr_service") { "continuous_task/src/bg_continuous_task_mgr.cpp", "continuous_task/src/bundle_manager_helper.cpp", "continuous_task/src/continuous_task_record.cpp", - "continuous_task/src/os_account_observer.cpp", "continuous_task/src/system_event_observer.cpp", "continuous_task/src/task_notification_subscriber.cpp", "core/src/background_task_mgr_service.cpp", diff --git a/services/continuous_task/include/app_state_observer.h b/services/continuous_task/include/app_state_observer.h index 672ef69b..bd985ad2 100644 --- a/services/continuous_task/include/app_state_observer.h +++ b/services/continuous_task/include/app_state_observer.h @@ -31,6 +31,7 @@ class AppStateObserver : public AppExecFwk::ApplicationStateObserverStub { public: AppStateObserver(); ~AppStateObserver(); + void OnAbilityStateChanged(const AppExecFwk::AbilityStateData &abilityStateData) override; void OnProcessDied(const AppExecFwk::ProcessData &processData) override; void SetEventHandler(const std::shared_ptr &handler); void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index d44d3912..e6204e45 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -32,7 +32,6 @@ #include "continuous_task_param.h" #include "continuous_task_record.h" #include "ibackground_task_subscriber.h" -#include "os_account_observer.h" #include "remote_death_recipient.h" #include "system_event_observer.h" @@ -61,11 +60,12 @@ public: bool StopContinuousTaskByUser(const std::string &mapKey); void OnAccountsStateChanged(int id); void OnBundleInfoChanged(const std::string &action, const std::string &bundleName, int32_t uid); + void OnAbilityStateChanged(const sptr &token); void OnProcessDied(int32_t pid); void OnRemoteSubscriberDied(const wptr &object); bool Init(); void InitNecessaryState(); - void InitNotificationPrompt(); + void InitRequiredResourceInfo(); void Clear(); private: @@ -87,22 +87,22 @@ private: bool RegisterNotificationSubscriber(); bool RegisterSysCommEventListener(); bool RegisterAppStateObserver(); - bool RegisterOsAccountObserver(); - bool GetContinuousTaskText(); + bool GetNotificationPrompt(); bool SetCachedBundleInfo(int32_t uid, int32_t userId, std::string &bundleName); void OnRemoteSubscriberDiedInner(const wptr &object); void OnContinuousTaskChanged(const std::shared_ptr continuousTaskInfo, ContinuousTaskEventTriggerType changeEventType); + bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool isNewApi, int32_t uid); private: std::atomic isSysReady_ {false}; + std::string deviceType_ {""}; std::shared_ptr runner_ {nullptr}; std::shared_ptr handler_ {nullptr}; std::unordered_map> continuousTaskInfosMap_ {}; std::shared_ptr subscriber_ {nullptr}; std::shared_ptr systemEventListener_ {nullptr}; std::shared_ptr appStateObserver_ {nullptr}; - std::shared_ptr osAccountObserver_ {nullptr}; std::list> bgTaskSubscribers_ {}; std::map, sptr> subscriberRecipients_ {}; std::unordered_map cachedBundleInfos_ {}; diff --git a/services/continuous_task/include/os_account_observer.h b/services/continuous_task/include/os_account_observer.h deleted file mode 100644 index 8766d009..00000000 --- a/services/continuous_task/include/os_account_observer.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_OS_ACCOUNT_OBSERVER_H -#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_OS_ACCOUNT_OBSERVER_H - -#include "event_handler.h" -#include "os_account_manager.h" - -namespace OHOS { -namespace BackgroundTaskMgr { -class BgContinuousTaskMgr; - -class OsAccountObserver final : public AccountSA::OsAccountSubscriber, - public std::enable_shared_from_this { -public: - OsAccountObserver() = default; - ~OsAccountObserver() = default; - explicit OsAccountObserver(const AccountSA::OsAccountSubscribeInfo &subscribeInfo); - - void OnAccountsChanged(const int &id) override; - void SetEventHandler(const std::shared_ptr &handler); - void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); - bool Subscribe(); - bool Unsubscribe(); - -private: - std::weak_ptr handler_; - std::weak_ptr bgContinuousTaskMgr_; -}; -} -} -#endif \ No newline at end of file diff --git a/services/continuous_task/src/app_state_observer.cpp b/services/continuous_task/src/app_state_observer.cpp index ad2d2951..179066ca 100644 --- a/services/continuous_task/src/app_state_observer.cpp +++ b/services/continuous_task/src/app_state_observer.cpp @@ -15,6 +15,7 @@ #include "app_state_observer.h" +#include "app_mgr_constants.h" #include "iservice_registry.h" #include "system_ability_definition.h" @@ -24,6 +25,7 @@ namespace OHOS { namespace BackgroundTaskMgr { namespace { const std::string TASK_ON_PROCESS_DIED = "OnProcessDiedTask"; +const std::string TASK_ON_ABILITY_STATE_CHANGED = "OnAbilityStateChangedTask"; } AppStateObserver::AppStateObserver() @@ -38,6 +40,31 @@ AppStateObserver::~AppStateObserver() Disconnect(); } +void AppStateObserver::OnAbilityStateChanged(const AppExecFwk::AbilityStateData &abilityStateData) +{ + BGTASK_LOGI("ability state changed, abilityName: %{public}s, abilityState: %{public}d", + abilityStateData.abilityName.c_str(), abilityStateData.abilityState); + if ((int32_t) AppExecFwk::AbilityState::ABILITY_STATE_TERMINATED != abilityStateData.abilityState) { + return; + } + if (!abilityStateData.token) { + BGTASK_LOGE("ability token is null"); + return; + } + auto handler = handler_.lock(); + if (!handler) { + BGTASK_LOGE("handler is null"); + return; + } + auto bgContinuousTaskMgr = bgContinuousTaskMgr_.lock(); + if (!bgContinuousTaskMgr) { + BGTASK_LOGE("bgContinuousTaskMgr is null"); + return; + } + auto task = [=]() { bgContinuousTaskMgr->OnAbilityStateChanged(abilityStateData.token); }; + handler->PostTask(task, TASK_ON_ABILITY_STATE_CHANGED); +} + void AppStateObserver::OnProcessDied(const AppExecFwk::ProcessData &processData) { BGTASK_LOGI("process died, pid : %{public}d", processData.pid); diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 49219d10..e7b478b6 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -27,6 +27,7 @@ #include "iservice_registry.h" #include "ohos/aafwk/base/string_wrapper.h" #include "os_account_manager.h" +#include "parameters.h" #include "system_ability_definition.h" #include "bgtaskmgr_inner_errors.h" @@ -58,8 +59,10 @@ static constexpr char DUMP_PARAM_CANCEL[] = "--cancel"; static constexpr char NOTIFICATION_PREFIX[] = "bgmode"; static constexpr char BGMODE_PERMISSION[] = "ohos.permission.KEEP_BACKGROUND_RUNNING"; static constexpr char BG_TASK_RES_BUNDLE_NAME[] = "ohos.global.backgroundtaskres"; +static constexpr char DEVICE_TYPE_PC[] = "pc"; static constexpr uint32_t SYSTEM_APP_BGMODE_WIFI_INTERACTION = 64; static constexpr uint32_t SYSTEM_APP_BGMODE_VOIP = 128; +static constexpr uint32_t PC_BGMODE_TASK_KEEPING = 256; static constexpr unsigned int SYSTEM_UID = 1000; static constexpr int32_t DEFAULT_NOTIFICATION_ID = 0; static constexpr int DELAY_TIME = 2000; @@ -127,16 +130,18 @@ void BgContinuousTaskMgr::InitNecessaryState() BGTASK_LOGE("RegisterSysCommEventListener failed"); return; } - auto getPromptTask = [this]() { this->InitNotificationPrompt(); }; - handler_->PostTask(getPromptTask, DELAY_TIME); + deviceType_ = OHOS::system::GetParameter("const.build.characteristics", ""); + BGTASK_LOGI("current device type is: %{public}s", deviceType_.c_str()); + auto getResInfoTask = [this]() { this->InitRequiredResourceInfo(); }; + handler_->PostTask(getResInfoTask, DELAY_TIME); } -void BgContinuousTaskMgr::InitNotificationPrompt() +void BgContinuousTaskMgr::InitRequiredResourceInfo() { - if (!GetContinuousTaskText()) { - BGTASK_LOGW("init continuous task notification prompt failed. will try again"); + if (!GetNotificationPrompt()) { + BGTASK_LOGW("init required resource info failed. will try again"); isSysReady_.store(false); - auto task = [this]() { this->InitNotificationPrompt(); }; + auto task = [this]() { this->InitRequiredResourceInfo(); }; handler_->PostTask(task, DELAY_TIME); return; } @@ -167,7 +172,7 @@ bool BgContinuousTaskMgr::RegisterAppStateObserver() return res; } -bool BgContinuousTaskMgr::GetContinuousTaskText() +bool BgContinuousTaskMgr::GetNotificationPrompt() { AppExecFwk::BundleInfo bundleInfo; if (!BundleManagerHelper::GetInstance()->GetBundleInfo(BG_TASK_RES_BUNDLE_NAME, @@ -224,21 +229,6 @@ bool BgContinuousTaskMgr::RegisterSysCommEventListener() return res; } -bool BgContinuousTaskMgr::RegisterOsAccountObserver() -{ - bool res = true; - OHOS::AccountSA::OsAccountSubscribeInfo osAccountSubscribeInfo; - osAccountSubscribeInfo.SetOsAccountSubscribeType(OHOS::AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVED); - osAccountSubscribeInfo.SetName("background_task_manager_service"); - osAccountObserver_ = std::make_shared(osAccountSubscribeInfo); - if (osAccountObserver_ != nullptr) { - osAccountObserver_->SetEventHandler(handler_); - osAccountObserver_->SetBgContinuousTaskMgr(shared_from_this()); - res = osAccountObserver_->Subscribe(); - } - return res; -} - bool BgContinuousTaskMgr::SetCachedBundleInfo(int32_t uid, int32_t userId, std::string &bundleName) { AppExecFwk::BundleInfo bundleInfo; @@ -274,7 +264,8 @@ bool BgContinuousTaskMgr::AddAbilityBgModeInfos(const AppExecFwk::BundleInfo &bu return true; } -bool BgContinuousTaskMgr::AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo) +bool BgContinuousTaskMgr::AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, + CachedBundleInfo &cachedBundleInfo) { std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); if (resourceManager == nullptr) { @@ -299,7 +290,8 @@ bool BgContinuousTaskMgr::AddAppNameInfos(const AppExecFwk::BundleInfo &bundleIn return true; } -bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool isNewApi, int32_t uid) +bool BgContinuousTaskMgr::checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, + bool isNewApi, int32_t uid) { if (!isNewApi) { if (configuredBgMode == INVALID_BGMODE) { @@ -315,6 +307,11 @@ bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool BGTASK_LOGE("voip and wifiInteraction background mode only support for system app"); return false; } + if (recordedBgMode == PC_BGMODE_TASK_KEEPING + && deviceType_ != DEVICE_TYPE_PC) { + BGTASK_LOGE("task keeping background mode only support for pc device"); + return false; + } if (requestedBgModeId == INVALID_BGMODE || (configuredBgMode & (BG_MODE_INDEX_HEAD << (requestedBgModeId - 1))) == 0) { BGTASK_LOGE("requested background mode is not declared in config file!"); @@ -798,6 +795,26 @@ void BgContinuousTaskMgr::OnRemoteSubscriberDiedInner(const wptr subscriberRecipients_.erase(objectProxy); } +void BgContinuousTaskMgr::OnAbilityStateChanged(const sptr &token) +{ + BGTASK_LOGI("begin"); + if (!isSysReady_.load()) { + BGTASK_LOGW("manager is not ready"); + return; + } + auto iter = continuousTaskInfosMap_.begin(); + while (iter != continuousTaskInfosMap_.end()) { + if (iter->second->GetAbilityToken() == token) { + OnContinuousTaskChanged(iter->second, ContinuousTaskEventTriggerType::TASK_CANCEL); + Notification::NotificationHelper::CancelContinuousTaskNotification( + iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); + iter = continuousTaskInfosMap_.erase(iter); + } else { + iter++; + } + } +} + void BgContinuousTaskMgr::OnProcessDied(int32_t pid) { BGTASK_LOGI("begin"); diff --git a/services/continuous_task/src/os_account_observer.cpp b/services/continuous_task/src/os_account_observer.cpp deleted file mode 100644 index a3c997ac..00000000 --- a/services/continuous_task/src/os_account_observer.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "os_account_observer.h" - -#include "bg_continuous_task_mgr.h" -#include "continuous_task_log.h" - -namespace OHOS { -namespace BackgroundTaskMgr { -namespace { -const std::string TASK_ON_OS_ACCOUNT_CHANGED = "OnOsAccountChanged"; -} - -OsAccountObserver::OsAccountObserver(const AccountSA::OsAccountSubscribeInfo &subscribeInfo) - : OsAccountSubscriber(subscribeInfo) {} - -bool OsAccountObserver::Subscribe() -{ - BGTASK_LOGI("Subscribe called"); - int ret = OHOS::AccountSA::OsAccountManager::SubscribeOsAccount(shared_from_this()); - if (ret != 0) { - BGTASK_LOGE("register os account failed ret %{public}d", ret); - return false; - } - return true; -} - -bool OsAccountObserver::Unsubscribe() -{ - BGTASK_LOGI("UnSubscribe called"); - int ret = OHOS::AccountSA::OsAccountManager::UnsubscribeOsAccount(shared_from_this()); - if (ret != 0) { - BGTASK_LOGE("register os account failed ret %{public}d", ret); - return false; - } - return true; -} - -void OsAccountObserver::SetEventHandler(const std::shared_ptr &handler) -{ - BGTASK_LOGI("set os account observer handler"); - handler_ = handler; -} - -void OsAccountObserver::SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr) -{ - BGTASK_LOGI("set os account oberver bgContinuousTaskMgr"); - bgContinuousTaskMgr_ = bgContinuousTaskMgr; -} - -void OsAccountObserver::OnAccountsChanged(const int &id) -{ - BGTASK_LOGI("on accounts state changed : %{public}d actived", id); - auto handler = handler_.lock(); - if (!handler) { - BGTASK_LOGE("handler is null"); - return; - } - auto bgContinuousTaskMgr = bgContinuousTaskMgr_.lock(); - if (!bgContinuousTaskMgr) { - BGTASK_LOGE("bgContinuousTaskMgr is null"); - return; - } - - auto task = [=]() { bgContinuousTaskMgr->OnAccountsStateChanged(id); }; - handler->PostTask(task, TASK_ON_OS_ACCOUNT_CHANGED); -} -} -} \ No newline at end of file diff --git a/services/transient_task/src/decision_maker.cpp b/services/transient_task/src/decision_maker.cpp index 08aaf941..58b9a26c 100644 --- a/services/transient_task/src/decision_maker.cpp +++ b/services/transient_task/src/decision_maker.cpp @@ -134,7 +134,7 @@ bool DecisionMaker::Decide(const std::shared_ptr& key, const std::share BGTASK_LOGI("enter"); lock_guard lock(lock_); if (key == nullptr) { - BGTASK_LOGE("Invaild key"); + BGTASK_LOGE("Invalid key"); return false; } @@ -180,7 +180,7 @@ void DecisionMaker::RemoveRequest(const std::shared_ptr& key, const int { lock_guard lock(lock_); if (key == nullptr) { - BGTASK_LOGE("Invaild key"); + BGTASK_LOGE("Invalid key"); return; } -- Gitee From b46e1561d9691059f839c0cbae29a2f9ea480df0 Mon Sep 17 00:00:00 2001 From: derek Date: Thu, 3 Mar 2022 16:58:56 +0800 Subject: [PATCH 63/77] fix compile error Signed-off-by: derek Change-Id: I71b002ea985282a5bf927b2212baf61201cbc38c --- services/test/unittest/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 51bca472..987335f2 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -60,6 +60,7 @@ ohos_unittest("bgtask_unit_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", + "native_appdatamgr:native_rdb", "os_account_standard:os_account_innerkits", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", -- Gitee From 41766a6ed862e8fa860615efb7c83789f25d9cb2 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Sat, 5 Mar 2022 15:21:54 +0800 Subject: [PATCH 64/77] bugfix for js unittest compile problem in hi3516 Signed-off-by: zhangxin_T --- bundle.json | 3 ++- .../{ => continuous_task_jsunittest}/BUILD.gn | 13 ++-------- .../transient_task_jsunittest/BUILD.gn | 26 +++++++++++++++++++ 3 files changed, 30 insertions(+), 12 deletions(-) rename interfaces/test/unittest/{ => continuous_task_jsunittest}/BUILD.gn (71%) create mode 100644 interfaces/test/unittest/transient_task_jsunittest/BUILD.gn diff --git a/bundle.json b/bundle.json index 1de884dc..dbaeccd2 100644 --- a/bundle.json +++ b/bundle.json @@ -66,7 +66,8 @@ } ], "test": [ - "//foundation/resourceschedule/background_task_mgr/interfaces/test/unittest:js_unittest", + "//foundation/resourceschedule/background_task_mgr/interfaces/test/unittest/continuous_task_jsunittest:js_unittest", + "//foundation/resourceschedule/background_task_mgr/interfaces/test/unittest/transient_task_jsunittest:js_unittest", "//foundation/resourceschedule/background_task_mgr/services/test/unittest:unittest", "//foundation/resourceschedule/background_task_mgr/test/systemtest:systemtest" ] diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/continuous_task_jsunittest/BUILD.gn similarity index 71% rename from interfaces/test/unittest/BUILD.gn rename to interfaces/test/unittest/continuous_task_jsunittest/BUILD.gn index 40c48381..10043abc 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/continuous_task_jsunittest/BUILD.gn @@ -16,20 +16,11 @@ module_output_path = "background_task_mgr/interfaces" ohos_js_unittest("ContinuousTaskJsTest") { module_out_path = module_output_path - hap_profile = "./continuous_task_jsunittest/config.json" - certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" -} - -ohos_js_unittest("TransientTaskJsTest") { - module_out_path = module_output_path - hap_profile = "./transient_task_jsunittest/config.json" + hap_profile = "./config.json" certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" } group("js_unittest") { testonly = true - deps = [ - ":ContinuousTaskJsTest", - ":TransientTaskJsTest", - ] + deps = [ ":ContinuousTaskJsTest" ] } diff --git a/interfaces/test/unittest/transient_task_jsunittest/BUILD.gn b/interfaces/test/unittest/transient_task_jsunittest/BUILD.gn new file mode 100644 index 00000000..6b95d771 --- /dev/null +++ b/interfaces/test/unittest/transient_task_jsunittest/BUILD.gn @@ -0,0 +1,26 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +module_output_path = "background_task_mgr/interfaces" + +ohos_js_unittest("TransientTaskJsTest") { + module_out_path = module_output_path + hap_profile = "./config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" +} + +group("js_unittest") { + testonly = true + deps = [ ":TransientTaskJsTest" ] +} -- Gitee From 3175def3e00cbc3d45210f2d48c08c7ef47621b9 Mon Sep 17 00:00:00 2001 From: ql Date: Tue, 8 Mar 2022 11:14:43 +0800 Subject: [PATCH 65/77] remove dependency of dmsfwk Signed-off-by: ql Change-Id: I2da01043723ad6e372d7b0eb4facce818c889114 --- interfaces/kits/BUILD.gn | 1 - services/BUILD.gn | 2 +- services/test/unittest/BUILD.gn | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/interfaces/kits/BUILD.gn b/interfaces/kits/BUILD.gn index 609dbf04..fb435dc1 100644 --- a/interfaces/kits/BUILD.gn +++ b/interfaces/kits/BUILD.gn @@ -44,7 +44,6 @@ ohos_shared_library("backgroundtaskmanager") { "ability_runtime:napi_base_context", "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", - "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", diff --git a/services/BUILD.gn b/services/BUILD.gn index 97d82e2a..5d238ef3 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -58,13 +58,13 @@ ohos_shared_library("bgtaskmgr_service") { external_deps = [ "ability_base:base", "ability_base:want", + "ability_base:zuri", "ability_runtime:ability_manager", "ability_runtime:app_manager", "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/test/unittest/BUILD.gn b/services/test/unittest/BUILD.gn index 51bca472..3d3e4756 100644 --- a/services/test/unittest/BUILD.gn +++ b/services/test/unittest/BUILD.gn @@ -50,12 +50,12 @@ ohos_unittest("bgtask_unit_test") { external_deps = [ "ability_base:want", + "ability_base:zuri", "ability_runtime:app_manager", "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", -- Gitee From 51cf4875b192c3f649619ed58c611878db2b84ee Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Wed, 9 Mar 2022 11:34:00 +0800 Subject: [PATCH 66/77] modify for code review Signed-off-by: zhangxin_T --- .../continuous_task/src/task_notification_subscriber.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index 89c2d8a4..0aa34cdf 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -112,12 +112,12 @@ void TaskNotificationSubscriber::OnEnabledNotificationChanged( std::vector TaskNotificationSubscriber::StringSplit(const std::string &str, const char *delim) { std::vector strlist; - char *saveptr = NULL; + char *saveptr = nullptr; char *p = const_cast(str.c_str()); char *input = strdup(p); - while ((input = strtok_r(input, delim, &saveptr)) != NULL) { + while ((input = strtok_r(input, delim, &saveptr)) != nullptr) { strlist.emplace_back(input); - input = NULL; + input = nullptr; } free(input); return strlist; -- Gitee From 0b2304ebd15670ff57798fc46bd2c5326e9651a7 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Fri, 11 Mar 2022 22:02:57 +0800 Subject: [PATCH 67/77] continuous task data persistence Signed-off-by: zhangxin_T --- .../common/include/bgtaskmgr_inner_errors.h | 1 + sa_profile/etc/bgtaskmgr_service.cfg | 1 + services/BUILD.gn | 2 + .../include/app_state_observer.h | 2 +- .../include/bg_continuous_task_mgr.h | 10 +- .../include/continuous_task_record.h | 9 ++ .../continuous_task/include/data_storage.h | 34 ++++ .../src/app_state_observer.cpp | 12 +- .../src/bg_continuous_task_mgr.cpp | 146 ++++++++++++++---- .../src/continuous_task_record.cpp | 50 ++++++ services/continuous_task/src/data_storage.cpp | 138 +++++++++++++++++ .../src/task_notification_subscriber.cpp | 8 +- 12 files changed, 367 insertions(+), 46 deletions(-) create mode 100644 services/continuous_task/include/data_storage.h create mode 100644 services/continuous_task/src/data_storage.cpp diff --git a/frameworks/common/include/bgtaskmgr_inner_errors.h b/frameworks/common/include/bgtaskmgr_inner_errors.h index 7ebc4b8d..4f963c4c 100644 --- a/frameworks/common/include/bgtaskmgr_inner_errors.h +++ b/frameworks/common/include/bgtaskmgr_inner_errors.h @@ -55,6 +55,7 @@ enum : int { ERR_BGTASK_NOTIFICATION_ERR, ERR_BGTASK_INVALID_BGMODE, ERR_BGTASK_NO_MEMORY, + ERR_BGTASK_DATA_STORAGE_ERR, }; } // namespace BackgroundTaskMgr } // namespace OHOS diff --git a/sa_profile/etc/bgtaskmgr_service.cfg b/sa_profile/etc/bgtaskmgr_service.cfg index 7375259c..be272942 100644 --- a/sa_profile/etc/bgtaskmgr_service.cfg +++ b/sa_profile/etc/bgtaskmgr_service.cfg @@ -2,6 +2,7 @@ "jobs" : [{ "name" : "boot", "cmds" : [ + "mkdir /data/service/el1/public/background_task_mgr 0711 system system", "start bgtaskmgr_service" ] } diff --git a/services/BUILD.gn b/services/BUILD.gn index 5d238ef3..06894662 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -29,6 +29,7 @@ ohos_shared_library("bgtaskmgr_service") { "continuous_task/src/bg_continuous_task_mgr.cpp", "continuous_task/src/bundle_manager_helper.cpp", "continuous_task/src/continuous_task_record.cpp", + "continuous_task/src/data_storage.cpp", "continuous_task/src/system_event_observer.cpp", "continuous_task/src/task_notification_subscriber.cpp", "core/src/background_task_mgr_service.cpp", @@ -53,6 +54,7 @@ ohos_shared_library("bgtaskmgr_service") { "${bgtaskmgr_interfaces_path}/innerkits:bgtaskmgr_innerkits", "//base/notification/ans_standard/frameworks/ans/native:ans_innerkits", "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//third_party/jsoncpp", ] external_deps = [ diff --git a/services/continuous_task/include/app_state_observer.h b/services/continuous_task/include/app_state_observer.h index bd985ad2..b0a3d97a 100644 --- a/services/continuous_task/include/app_state_observer.h +++ b/services/continuous_task/include/app_state_observer.h @@ -34,7 +34,7 @@ public: void OnAbilityStateChanged(const AppExecFwk::AbilityStateData &abilityStateData) override; void OnProcessDied(const AppExecFwk::ProcessData &processData) override; void SetEventHandler(const std::shared_ptr &handler); - void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr_); + void SetBgContinuousTaskMgr(const std::shared_ptr &bgContinuousTaskMgr); bool Subscribe(); bool Unsubscribe(); diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index e6204e45..dacdb939 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -28,6 +28,7 @@ #include "bgtaskmgr_inner_errors.h" #include "bundle_info.h" #include "continuous_task_callback_info.h" +#include "data_storage.h" #include "task_notification_subscriber.h" #include "continuous_task_param.h" #include "continuous_task_record.h" @@ -60,7 +61,7 @@ public: bool StopContinuousTaskByUser(const std::string &mapKey); void OnAccountsStateChanged(int id); void OnBundleInfoChanged(const std::string &action, const std::string &bundleName, int32_t uid); - void OnAbilityStateChanged(const sptr &token); + void OnAbilityStateChanged(int32_t uid, const std::string &abilityName); void OnProcessDied(int32_t pid); void OnRemoteSubscriberDied(const wptr &object); bool Init(); @@ -76,12 +77,15 @@ private: ErrCode RemoveSubscriberInner(const sptr &subscriber); ErrCode ShellDumpInner(const std::vector &dumpOption, std::vector &dumpInfo); ErrCode SendContinuousTaskNotification(std::shared_ptr &ContinuousTaskRecordPtr); + void HandlePersistenceData(); + void CheckPersistenceData(const std::vector &allProcesses, + const std::vector> &allNotifications); void DumpAllTaskInfo(std::vector &dumpInfo); void DumpCancelTask(const std::vector &dumpOption, bool cleanAll); bool RemoveContinuousTaskRecord(const std::string &mapKey); bool AddAppNameInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); std::string CreateNotificationLabel(int32_t uid, const std::string &bundleName, - const std::string &abilityName, sptr abilityToken); + const std::string &abilityName); uint32_t GetBackgroundModeInfo(int32_t uid, std::string &abilityName); bool AddAbilityBgModeInfos(const AppExecFwk::BundleInfo &bundleInfo, CachedBundleInfo &cachedBundleInfo); bool RegisterNotificationSubscriber(); @@ -93,6 +97,7 @@ private: void OnContinuousTaskChanged(const std::shared_ptr continuousTaskInfo, ContinuousTaskEventTriggerType changeEventType); bool checkBgmodeType(uint32_t configuredBgMode, uint32_t requestedBgModeId, bool isNewApi, int32_t uid); + int32_t RefreshTaskRecord(); private: std::atomic isSysReady_ {false}; @@ -107,6 +112,7 @@ private: std::map, sptr> subscriberRecipients_ {}; std::unordered_map cachedBundleInfos_ {}; std::vector continuousTaskText_ {}; + std::shared_ptr dataStorage_ {nullptr}; DECLARE_DELAYED_SINGLETON(BgContinuousTaskMgr); }; diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h index 17c54c81..1eb3acaf 100644 --- a/services/continuous_task/include/continuous_task_record.h +++ b/services/continuous_task/include/continuous_task_record.h @@ -18,6 +18,7 @@ #include "iremote_object.h" #include "parcel.h" +#include "json/json.h" #include "want_agent.h" #include "task_notification_subscriber.h" @@ -26,6 +27,11 @@ namespace OHOS { namespace BackgroundTaskMgr { extern const char *ContinuousTaskModeName[10]; +struct WantAgentInfo { + std::string bundleName_ {""}; + std::string abilityName_ {""}; +}; + class ContinuousTaskRecord { public: ContinuousTaskRecord() = default; @@ -42,6 +48,8 @@ public: std::string GetNotificationLabel() const; std::shared_ptr GetWantAgent() const; sptr GetAbilityToken() const; + std::string ParseToJsonStr(); + bool ParseFromJson(const Json::Value value); private: std::string bundleName_ {""}; @@ -54,6 +62,7 @@ private: uint32_t bgModeId_ {0}; bool isNewApi_ {false}; std::string notificationLabel_ {""}; + std::shared_ptr wantAgentInfo_ {nullptr}; friend class BgContinuousTaskMgr; }; diff --git a/services/continuous_task/include/data_storage.h b/services/continuous_task/include/data_storage.h new file mode 100644 index 00000000..c76e3667 --- /dev/null +++ b/services/continuous_task/include/data_storage.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_DATA_STORAGE_H +#define FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_DATA_STORAGE_H + +#include "continuous_task_record.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +class DataStorage { +public: + int32_t RefreshTaskRecord(const std::unordered_map> &allRecord); + int32_t RestoreTaskRecord(std::unordered_map> &allRecord); + +private: + int32_t CreateNodeFile(const std::string &filePath); + bool ConvertFullPath(const std::string &partialPath, std::string &fullPath); +}; +} +} +#endif \ No newline at end of file diff --git a/services/continuous_task/src/app_state_observer.cpp b/services/continuous_task/src/app_state_observer.cpp index 179066ca..3494fd94 100644 --- a/services/continuous_task/src/app_state_observer.cpp +++ b/services/continuous_task/src/app_state_observer.cpp @@ -42,15 +42,11 @@ AppStateObserver::~AppStateObserver() void AppStateObserver::OnAbilityStateChanged(const AppExecFwk::AbilityStateData &abilityStateData) { - BGTASK_LOGI("ability state changed, abilityName: %{public}s, abilityState: %{public}d", - abilityStateData.abilityName.c_str(), abilityStateData.abilityState); if ((int32_t) AppExecFwk::AbilityState::ABILITY_STATE_TERMINATED != abilityStateData.abilityState) { return; } - if (!abilityStateData.token) { - BGTASK_LOGE("ability token is null"); - return; - } + BGTASK_LOGI("ability state changed, uid: %{public}d abilityName: %{public}s, abilityState: %{public}d", + abilityStateData.uid, abilityStateData.abilityName.c_str(), abilityStateData.abilityState); auto handler = handler_.lock(); if (!handler) { BGTASK_LOGE("handler is null"); @@ -61,7 +57,9 @@ void AppStateObserver::OnAbilityStateChanged(const AppExecFwk::AbilityStateData BGTASK_LOGE("bgContinuousTaskMgr is null"); return; } - auto task = [=]() { bgContinuousTaskMgr->OnAbilityStateChanged(abilityStateData.token); }; + auto task = [=]() { + bgContinuousTaskMgr->OnAbilityStateChanged(abilityStateData.uid, abilityStateData.abilityName); + }; handler->PostTask(task, TASK_ON_ABILITY_STATE_CHANGED); } diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index e7b478b6..fa2daaae 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -17,6 +17,7 @@ #include +#include "app_mgr_client.h" #include "bundle_constants.h" #include "bundle_manager_helper.h" #include "common_event_support.h" @@ -28,6 +29,7 @@ #include "ohos/aafwk/base/string_wrapper.h" #include "os_account_manager.h" #include "parameters.h" +#include "running_process_info.h" #include "system_ability_definition.h" #include "bgtaskmgr_inner_errors.h" @@ -65,7 +67,7 @@ static constexpr uint32_t SYSTEM_APP_BGMODE_VOIP = 128; static constexpr uint32_t PC_BGMODE_TASK_KEEPING = 256; static constexpr unsigned int SYSTEM_UID = 1000; static constexpr int32_t DEFAULT_NOTIFICATION_ID = 0; -static constexpr int DELAY_TIME = 2000; +static constexpr int32_t DELAY_TIME_INTERVAL = 500; static constexpr uint32_t INVALID_BGMODE = 0; static constexpr uint32_t BG_MODE_INDEX_HEAD = 1; static constexpr int BGMODE_NUMS = 10; @@ -114,7 +116,7 @@ void BgContinuousTaskMgr::InitNecessaryState() || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr) { BGTASK_LOGW("request system service is not ready yet!"); auto task = [this]() { this->InitNecessaryState(); }; - handler_->PostTask(task, DELAY_TIME); + handler_->PostTask(task, DELAY_TIME_INTERVAL * 4); return; } @@ -132,8 +134,72 @@ void BgContinuousTaskMgr::InitNecessaryState() } deviceType_ = OHOS::system::GetParameter("const.build.characteristics", ""); BGTASK_LOGI("current device type is: %{public}s", deviceType_.c_str()); - auto getResInfoTask = [this]() { this->InitRequiredResourceInfo(); }; - handler_->PostTask(getResInfoTask, DELAY_TIME); + InitRequiredResourceInfo(); +} + +void BgContinuousTaskMgr::HandlePersistenceData() +{ + dataStorage_ = std::make_shared(); + if (dataStorage_ == nullptr) { + BGTASK_LOGE("get data storage failed"); + return; + } + BGTASK_LOGI("service restart, restore data"); + dataStorage_->RestoreTaskRecord(continuousTaskInfosMap_); + auto appMgrClient = std::make_shared(); + std::vector allAppProcessInfos; + if (appMgrClient == nullptr || appMgrClient->ConnectAppMgrService() != ERR_OK) { + BGTASK_LOGW("connect to app mgr service failed"); + return; + } + appMgrClient->GetAllRunningProcesses(allAppProcessInfos); + std::vector> notifications; + Notification::NotificationHelper::GetAllActiveNotifications(notifications); + CheckPersistenceData(allAppProcessInfos, notifications); + dataStorage_->RefreshTaskRecord(continuousTaskInfosMap_); +} + +void BgContinuousTaskMgr::CheckPersistenceData(const std::vector &allProcesses, + const std::vector> &allNotifications) +{ + auto iter = continuousTaskInfosMap_.begin(); + while (iter != continuousTaskInfosMap_.end()) { + int32_t recordPid = iter->second->GetPid(); + auto findPid = [recordPid](const auto &target) { + return recordPid == target.pid_; + }; + auto findPidIter = find_if(allProcesses.begin(), allProcesses.end(), findPid); + + std::string recordLabel = iter->second->GetNotificationLabel(); + auto findLabel = [recordLabel](const auto &target) { + return target != nullptr ? recordLabel == target->GetLabel() : false; + }; + auto findLabelIter = find_if(allNotifications.begin(), allNotifications.end(), findLabel); + if (findPidIter != allProcesses.end() && findLabelIter != allNotifications.end()) { + BGTASK_LOGI("target continuous task exist"); + iter++; + continue; + } + + if (findPidIter == allProcesses.end() && findLabelIter != allNotifications.end()) { + BGTASK_LOGI("pid: %{public}d not exist, label: %{public}s exist", recordPid, recordLabel.c_str()); + Notification::NotificationHelper::CancelContinuousTaskNotification(recordLabel, DEFAULT_NOTIFICATION_ID); + iter = continuousTaskInfosMap_.erase(iter); + continue; + } + + if (findPidIter != allProcesses.end() && findLabelIter == allNotifications.end()) { + BGTASK_LOGI("pid: %{public}d exist, label: %{public}s not exist", recordPid, recordLabel.c_str()); + iter = continuousTaskInfosMap_.erase(iter); + continue; + } + + if (findPidIter == allProcesses.end() && findLabelIter == allNotifications.end()) { + BGTASK_LOGI("pid: %{public}d not exist, label: %{public}s not exist", recordPid, recordLabel.c_str()); + iter = continuousTaskInfosMap_.erase(iter); + continue; + } + } } void BgContinuousTaskMgr::InitRequiredResourceInfo() @@ -142,9 +208,10 @@ void BgContinuousTaskMgr::InitRequiredResourceInfo() BGTASK_LOGW("init required resource info failed. will try again"); isSysReady_.store(false); auto task = [this]() { this->InitRequiredResourceInfo(); }; - handler_->PostTask(task, DELAY_TIME); + handler_->PostTask(task, DELAY_TIME_INTERVAL); return; } + HandlePersistenceData(); isSysReady_.store(true); } @@ -370,6 +437,17 @@ ErrCode BgContinuousTaskMgr::StartBackgroundRunning(const sptrabilityName_, taskParam->wantAgent_, taskParam->abilityToken_, userId, callingUid, callingPid, taskParam->bgModeId_, taskParam->isNewApi_); + if (taskParam->wantAgent_ != nullptr && taskParam->wantAgent_->GetPendingWant() != nullptr) { + auto target = taskParam->wantAgent_->GetPendingWant()->GetTarget(); + auto want = taskParam->wantAgent_->GetPendingWant()->GetWant(target); + if (want != nullptr) { + std::shared_ptr info = std::make_shared(); + info->bundleName_ = want->GetOperation().GetBundleName(); + info->abilityName_ = want->GetOperation().GetAbilityName(); + continuousTaskRecord->wantAgentInfo_ = info; + } + } + handler_->PostSyncTask([this, continuousTaskRecord, &result]() mutable { result = this->StartBackgroundRunningInner(continuousTaskRecord); }, AppExecFwk::EventQueue::Priority::HIGH); @@ -381,14 +459,8 @@ ErrCode BgContinuousTaskMgr::StartBackgroundRunning(const sptr &continuousTaskRecord) { BGTASK_LOGI("begin"); - - std::stringstream stream; - stream.clear(); - stream.str(""); - continuousTaskRecord->abilityToken_ ? stream << continuousTaskRecord->abilityToken_ : stream << 0; - std::string abilityTokeLabel = stream.str(); std::string taskInfoMapKey = std::to_string(continuousTaskRecord->uid_) + SEPARATOR - + continuousTaskRecord->abilityName_ + SEPARATOR + abilityTokeLabel; + + continuousTaskRecord->abilityName_; if (continuousTaskInfosMap_.find(taskInfoMapKey) != continuousTaskInfosMap_.end()) { BGTASK_LOGW("continuous task is already exist: %{public}s", taskInfoMapKey.c_str()); return ERR_BGTASK_OBJECT_EXISTS; @@ -419,6 +491,9 @@ ErrCode BgContinuousTaskMgr::StartBackgroundRunningInner(std::shared_ptrSetParam("abilityName", AAFwk::String::Box(continuousTaskRecord->abilityName_)); std::string notificationLabel = CreateNotificationLabel(continuousTaskRecord->uid_, - continuousTaskRecord->bundleName_, continuousTaskRecord->abilityName_, continuousTaskRecord->abilityToken_); + continuousTaskRecord->bundleName_, continuousTaskRecord->abilityName_); // set extraInfo to save abilityname Info. notificationRequest.SetAdditionalData(extraInfo); @@ -492,13 +567,12 @@ ErrCode BgContinuousTaskMgr::SendContinuousTaskNotification( } std::string BgContinuousTaskMgr::CreateNotificationLabel(int32_t uid, const std::string &bundleName, - const std::string &abilityName, const sptr abilityToken) + const std::string &abilityName) { std::stringstream stream; stream.clear(); stream.str(""); - stream << NOTIFICATION_PREFIX << SEPARATOR << uid << SEPARATOR << std::hash()(abilityName) - << SEPARATOR << (abilityToken ? (abilityToken) : 0); + stream << NOTIFICATION_PREFIX << SEPARATOR << uid << SEPARATOR << std::hash()(abilityName); std::string label = stream.str(); BGTASK_LOGI("notification label: %{public}s", label.c_str()); return label; @@ -531,12 +605,7 @@ ErrCode BgContinuousTaskMgr::StopBackgroundRunningInner(int32_t uid, const std:: const sptr &abilityToken) { BGTASK_LOGI("begin"); - std::stringstream stream; - stream.clear(); - stream.str(""); - abilityToken ? stream << abilityToken : stream << 0; - std::string abilityTokeLabel = stream.str(); - std::string mapKey = std::to_string(uid) + SEPARATOR + abilityName + SEPARATOR + abilityTokeLabel; + std::string mapKey = std::to_string(uid) + SEPARATOR + abilityName; auto iter = continuousTaskInfosMap_.find(mapKey); if (iter == continuousTaskInfosMap_.end()) { @@ -695,13 +764,9 @@ void BgContinuousTaskMgr::DumpAllTaskInfo(std::vector &dumpInfo) stream << "\t\tuserId: " << iter->second->GetUserId() << "\n"; stream << "\t\tpid: " << iter->second->GetPid() << "\n"; stream << "\t\tnotificationLabel: " << iter->second->GetNotificationLabel() << "\n"; - auto wantAgent = iter->second->GetWantAgent(); - if (wantAgent != nullptr && wantAgent->GetPendingWant() != nullptr) { - auto want = wantAgent->GetPendingWant()->GetWant(wantAgent->GetPendingWant()->GetTarget()); - if (want != nullptr) { - stream << "\t\twantAgentBundleName: " << want->GetOperation().GetBundleName() << "\n"; - stream << "\t\twantAgentAbilityName: " << want->GetOperation().GetAbilityName() << "\n"; - } + if (iter->second->wantAgentInfo_ != nullptr) { + stream << "\t\twantAgentBundleName: " << iter->second->wantAgentInfo_->bundleName_ << "\n"; + stream << "\t\twantAgentAbilityName: " << iter->second->wantAgentInfo_->abilityName_ << "\n"; } else { stream << "\t\twantAgentBundleName: " << "NULL" << "\n"; stream << "\t\twantAgentAbilityName: " << "NULL" << "\n"; @@ -722,6 +787,7 @@ void BgContinuousTaskMgr::DumpCancelTask(const std::vector &dumpOpt OnContinuousTaskChanged(item.second, ContinuousTaskEventTriggerType::TASK_CANCEL); } continuousTaskInfosMap_.clear(); + RefreshTaskRecord(); } else { std::string taskKey = dumpOption[2]; auto iter = continuousTaskInfosMap_.find(taskKey); @@ -743,6 +809,7 @@ bool BgContinuousTaskMgr::RemoveContinuousTaskRecord(const std::string &mapKey) } OnContinuousTaskChanged(continuousTaskInfosMap_.at(mapKey), ContinuousTaskEventTriggerType::TASK_CANCEL); continuousTaskInfosMap_.erase(mapKey); + RefreshTaskRecord(); BGTASK_LOGI("end"); return true; } @@ -795,7 +862,7 @@ void BgContinuousTaskMgr::OnRemoteSubscriberDiedInner(const wptr subscriberRecipients_.erase(objectProxy); } -void BgContinuousTaskMgr::OnAbilityStateChanged(const sptr &token) +void BgContinuousTaskMgr::OnAbilityStateChanged(int32_t uid, const std::string &abilityName) { BGTASK_LOGI("begin"); if (!isSysReady_.load()) { @@ -804,11 +871,12 @@ void BgContinuousTaskMgr::OnAbilityStateChanged(const sptr &token } auto iter = continuousTaskInfosMap_.begin(); while (iter != continuousTaskInfosMap_.end()) { - if (iter->second->GetAbilityToken() == token) { + if (iter->second->uid_ == uid && iter->second->abilityName_ == abilityName) { OnContinuousTaskChanged(iter->second, ContinuousTaskEventTriggerType::TASK_CANCEL); Notification::NotificationHelper::CancelContinuousTaskNotification( iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); iter = continuousTaskInfosMap_.erase(iter); + RefreshTaskRecord(); } else { iter++; } @@ -830,6 +898,7 @@ void BgContinuousTaskMgr::OnProcessDied(int32_t pid) Notification::NotificationHelper::CancelContinuousTaskNotification( iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); iter = continuousTaskInfosMap_.erase(iter); + RefreshTaskRecord(); } else { iter++; } @@ -893,6 +962,7 @@ void BgContinuousTaskMgr::OnBundleInfoChanged(const std::string &action, const s Notification::NotificationHelper::CancelContinuousTaskNotification( iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); iter = continuousTaskInfosMap_.erase(iter); + RefreshTaskRecord(); } else { iter++; } @@ -919,10 +989,24 @@ void BgContinuousTaskMgr::OnAccountsStateChanged(int id) Notification::NotificationHelper::CancelContinuousTaskNotification( iter->second->GetNotificationLabel(), DEFAULT_NOTIFICATION_ID); iter = continuousTaskInfosMap_.erase(iter); + RefreshTaskRecord(); } else { iter++; } } } + +int32_t BgContinuousTaskMgr::RefreshTaskRecord() +{ + if (dataStorage_ == nullptr) { + BGTASK_LOGE("data storage object is null"); + return ERR_BGTASK_DATA_STORAGE_ERR; + } + if (dataStorage_->RefreshTaskRecord(continuousTaskInfosMap_) != ERR_OK) { + BGTASK_LOGE("refresh data failed"); + return ERR_BGTASK_DATA_STORAGE_ERR; + } + return ERR_OK; +} } } \ No newline at end of file diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index 163e27c3..e3403b40 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -16,6 +16,7 @@ #include "continuous_task_record.h" #include "iremote_object.h" +#include "json/value.h" namespace OHOS { namespace BackgroundTaskMgr { @@ -87,5 +88,54 @@ sptr ContinuousTaskRecord::GetAbilityToken() const { return abilityToken_; } + +std::string ContinuousTaskRecord::ParseToJsonStr() +{ + Json::Value root; + root["bundleName"] = bundleName_; + root["abilityName"] = abilityName_; + root["userId"] = userId_; + root["uid"] = uid_; + root["pid"] = pid_; + root["bgModeId"] = bgModeId_; + root["isNewApi"] = isNewApi_; + root["notificationLabel"] = notificationLabel_; + if (wantAgentInfo_ != nullptr) { + Json::Value info; + info["bundleName"] = wantAgentInfo_->bundleName_; + info["abilityName"] = wantAgentInfo_->abilityName_; + root["wantAgentInfo"] = info; + } + Json::StreamWriterBuilder writerBuilder; + std::ostringstream os; + std::unique_ptr jsonWriter(writerBuilder.newStreamWriter()); + jsonWriter->write(root, &os); + std::string result = os.str(); + return result; + +} +bool ContinuousTaskRecord::ParseFromJson(const Json::Value value) +{ + if (value.empty()) { + return false; + } + this->bundleName_ = value["bundleName"].asString(); + this->abilityName_ = value["abilityName"].asString(); + this->userId_ = value["userId"].asInt(); + this->uid_ = value["uid"].asInt(); + this->pid_ = value["pid"].asInt(); + this->bgModeId_ = value["bgModeId"].asInt(); + this->isNewApi_ = value["isNewApi"].asBool(); + this->notificationLabel_ = value["notificationLabel"].asString(); + + if (value.isMember("wantAgentInfo")) { + Json::Value infoVal = value["wantAgentInfo"]; + std::shared_ptr info = std::make_shared(); + info->bundleName_ = infoVal["bundleName"].asString(); + info->abilityName_ = infoVal["abilityName"].asString(); + this->wantAgentInfo_ = info; + } + return true; +} } } \ No newline at end of file diff --git a/services/continuous_task/src/data_storage.cpp b/services/continuous_task/src/data_storage.cpp new file mode 100644 index 00000000..b88f3f97 --- /dev/null +++ b/services/continuous_task/src/data_storage.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_storage.h" + +#include +#include +#include +#include + +#include "errors.h" +#include "json/json.h" + +#include "bgtaskmgr_inner_errors.h" +#include "bundle_manager_helper.h" +#include "continuous_task_log.h" + +namespace OHOS { +namespace BackgroundTaskMgr { +namespace { +static constexpr char TASK_RECORD_FILE_PATH[] = "/data/service/el1/public/background_task_mgr/running_task"; +static constexpr int32_t MAX_BUFFER = 512; +} + +int32_t DataStorage::RefreshTaskRecord(const std::unordered_map> &allRecord) +{ + Json::Value root; + for (auto &iter : allRecord) { + auto record = iter.second; + std::string data = record->ParseToJsonStr(); + JSONCPP_STRING errs; + Json::Value recordJson; + Json::CharReaderBuilder readerBuilder; + const std::unique_ptr jsonReader(readerBuilder.newCharReader()); + bool res = jsonReader->parse(data.c_str(), data.c_str() + data.length(), &recordJson, &errs); + if (res && errs.empty()) { + root[iter.first] = recordJson; + } + } + Json::StreamWriterBuilder writerBuilder; + std::ostringstream os; + std::unique_ptr jsonWriter(writerBuilder.newStreamWriter()); + jsonWriter->write(root, &os); + std::string result = os.str(); + CreateNodeFile(TASK_RECORD_FILE_PATH); + std::ofstream fout; + std::string realPath; + if (!ConvertFullPath(TASK_RECORD_FILE_PATH, realPath)) { + BGTASK_LOGE("Get real path failed"); + return ERR_BGTASK_DATA_STORAGE_ERR; + } + BGTASK_LOGI("Refresh path %{public}s", realPath.c_str()); + fout.open(realPath, std::ios::out); + fout << result.c_str() << std::endl; + fout.close(); + return ERR_OK; +} +int32_t DataStorage::RestoreTaskRecord(std::unordered_map> &allRecord) +{ + std::ifstream fin; + std::string realPath; + if (!ConvertFullPath(TASK_RECORD_FILE_PATH, realPath)) { + BGTASK_LOGE("Get real path failed"); + return ERR_BGTASK_DATA_STORAGE_ERR; + } + fin.open(realPath, std::ios::in); + if (!fin.is_open()) { + BGTASK_LOGE("cannot open file %{public}s", realPath.c_str()); + return ERR_BGTASK_DATA_STORAGE_ERR; + } + char buffer[MAX_BUFFER]; + std::ostringstream os; + while (!fin.eof()) { + fin.getline(buffer, MAX_BUFFER); + os << buffer; + } + std::string data = os.str(); + JSONCPP_STRING errs; + Json::Value root; + Json::CharReaderBuilder readerBuilder; + const std::unique_ptr jsonReader(readerBuilder.newCharReader()); + bool res = jsonReader->parse(data.c_str(), data.c_str() + data.length(), &root, &errs); + if (!res || !errs.empty()) { + BGTASK_LOGE("parse json file failed!"); + return ERR_BGTASK_DATA_STORAGE_ERR; + } + for (auto it : root.getMemberNames()) { + Json::Value recordJson = root[it]; + std::shared_ptr record = std::make_shared(); + if (record->ParseFromJson(recordJson)) { + allRecord.emplace(it, record); + } + } + BGTASK_LOGI("end"); + return ERR_OK; +} + +int32_t DataStorage::CreateNodeFile(const std::string &filePath) +{ + int32_t fd = -1; + if (access(filePath.c_str(), 0) != 0) { + fd = open(filePath.c_str(), O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); + if (fd < ERR_OK) { + BGTASK_LOGE("failed to open file: %{public}s", TASK_RECORD_FILE_PATH); + return fd; + } + } else { + BGTASK_LOGI("the file: %{public}s already exists.", TASK_RECORD_FILE_PATH); + } + return ERR_OK; +} + +bool DataStorage::ConvertFullPath(const std::string& partialPath, std::string& fullPath) +{ + if (partialPath.empty() || partialPath.length() >= PATH_MAX) { + return false; + } + char tmpPath[PATH_MAX] = {0}; + if (realpath(partialPath.c_str(), tmpPath) == nullptr) { + return false; + } + fullPath = tmpPath; + return true; +} +} +} diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index 0aa34cdf..d20bd5b0 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -32,8 +32,7 @@ static constexpr char NOTIFICATION_PREFIX[] = "bgmode"; static constexpr uint32_t SYSTEM_UID = 1000; static constexpr uint32_t LABEL_BGMODE_PREFIX_POS = 0; static constexpr uint32_t LABEL_APP_UID_POS = 1; -static constexpr uint32_t LABEL_ABILITY_TOKEN_POS = 3; -static constexpr uint32_t LABEL_SIZE = 4; +static constexpr uint32_t LABEL_SIZE = 3; } std::shared_ptr TaskNotificationSubscriber::continuousTaskMgr_ @@ -62,7 +61,7 @@ void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr labelSplits = StringSplit(notificationLabel, LABEL_SPLITER); @@ -85,8 +84,7 @@ void TaskNotificationSubscriber::OnCanceled(const std::shared_ptrGetParam("abilityName"))); - std::string taskInfoMapKey = labelSplits[LABEL_APP_UID_POS] + LABEL_SPLITER + abilityName - + LABEL_SPLITER + labelSplits[LABEL_ABILITY_TOKEN_POS]; + std::string taskInfoMapKey = labelSplits[LABEL_APP_UID_POS] + LABEL_SPLITER + abilityName; if (continuousTaskMgr_->StopContinuousTaskByUser(taskInfoMapKey)) { BGTASK_LOGI("remove continuous task record Key: %{public}s", taskInfoMapKey.c_str()); -- Gitee From bd534150804995dd5078266c3112d61e1b66e60d Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Mon, 14 Mar 2022 08:05:18 +0800 Subject: [PATCH 68/77] codecheck bugfix Signed-off-by: zhangxin_T --- services/continuous_task/src/bg_continuous_task_mgr.cpp | 6 +++--- services/continuous_task/src/continuous_task_record.cpp | 2 +- services/continuous_task/src/data_storage.cpp | 7 +++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index fa2daaae..79762600 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -67,7 +67,7 @@ static constexpr uint32_t SYSTEM_APP_BGMODE_VOIP = 128; static constexpr uint32_t PC_BGMODE_TASK_KEEPING = 256; static constexpr unsigned int SYSTEM_UID = 1000; static constexpr int32_t DEFAULT_NOTIFICATION_ID = 0; -static constexpr int32_t DELAY_TIME_INTERVAL = 500; +static constexpr int32_t DELAY_TIME = 2000; static constexpr uint32_t INVALID_BGMODE = 0; static constexpr uint32_t BG_MODE_INDEX_HEAD = 1; static constexpr int BGMODE_NUMS = 10; @@ -116,7 +116,7 @@ void BgContinuousTaskMgr::InitNecessaryState() || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr) { BGTASK_LOGW("request system service is not ready yet!"); auto task = [this]() { this->InitNecessaryState(); }; - handler_->PostTask(task, DELAY_TIME_INTERVAL * 4); + handler_->PostTask(task, DELAY_TIME); return; } @@ -208,7 +208,7 @@ void BgContinuousTaskMgr::InitRequiredResourceInfo() BGTASK_LOGW("init required resource info failed. will try again"); isSysReady_.store(false); auto task = [this]() { this->InitRequiredResourceInfo(); }; - handler_->PostTask(task, DELAY_TIME_INTERVAL); + handler_->PostTask(task, DDELAY_TIME); return; } HandlePersistenceData(); diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index e3403b40..96e0d058 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -112,8 +112,8 @@ std::string ContinuousTaskRecord::ParseToJsonStr() jsonWriter->write(root, &os); std::string result = os.str(); return result; - } + bool ContinuousTaskRecord::ParseFromJson(const Json::Value value) { if (value.empty()) { diff --git a/services/continuous_task/src/data_storage.cpp b/services/continuous_task/src/data_storage.cpp index b88f3f97..ccf435b9 100644 --- a/services/continuous_task/src/data_storage.cpp +++ b/services/continuous_task/src/data_storage.cpp @@ -34,7 +34,8 @@ static constexpr char TASK_RECORD_FILE_PATH[] = "/data/service/el1/public/backgr static constexpr int32_t MAX_BUFFER = 512; } -int32_t DataStorage::RefreshTaskRecord(const std::unordered_map> &allRecord) +int32_t DataStorage::RefreshTaskRecord(const std::unordered_map> &allRecord) { Json::Value root; for (auto &iter : allRecord) { @@ -67,7 +68,9 @@ int32_t DataStorage::RefreshTaskRecord(const std::unordered_map> &allRecord) + +int32_t DataStorage::RestoreTaskRecord(std::unordered_map> &allRecord) { std::ifstream fin; std::string realPath; -- Gitee From 8ec5cfa559acb088e7ea413885bf500314ccabf8 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Mon, 14 Mar 2022 09:13:36 +0800 Subject: [PATCH 69/77] codecheck bugfix Signed-off-by: zhangxin_T --- services/continuous_task/src/bg_continuous_task_mgr.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 79762600..63719507 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -208,7 +208,7 @@ void BgContinuousTaskMgr::InitRequiredResourceInfo() BGTASK_LOGW("init required resource info failed. will try again"); isSysReady_.store(false); auto task = [this]() { this->InitRequiredResourceInfo(); }; - handler_->PostTask(task, DDELAY_TIME); + handler_->PostTask(task, DELAY_TIME); return; } HandlePersistenceData(); -- Gitee From f6c52fefb79e56e7d2ce0d6dc9441724157fbe89 Mon Sep 17 00:00:00 2001 From: wangqing Date: Tue, 15 Mar 2022 15:41:02 +0800 Subject: [PATCH 70/77] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E6=80=A7=E8=83=BD=E6=B5=8B=E8=AF=95=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangqing --- .../continuous_task_jsunit.test.js | 274 ++++++++++++++---- .../transient_task_jsunit.test.js | 144 ++++++++- 2 files changed, 351 insertions(+), 67 deletions(-) diff --git a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js index 15cc39a4..340dc082 100644 --- a/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js +++ b/interfaces/test/unittest/continuous_task_jsunittest/continuous_task_jsunit.test.js @@ -19,39 +19,39 @@ import particleAbility from '@ohos.ability.particleAbility' import backgroundTaskManager from '@ohos.backgroundTaskManager' import featureAbility from '@ohos.ability.featureAbility' -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' describe("ContinuousTaskJsTest", function () { beforeAll(function() { /* * @tc.setup: setup invoked before all testcases */ - console.info('beforeAll called') + console.info('beforeAll called') }) - + afterAll(function() { /* * @tc.teardown: teardown invoked after all testcases */ - console.info('afterAll called') + console.info('afterAll called') }) - + beforeEach(function() { /* * @tc.setup: setup invoked before each testcases */ - console.info('beforeEach called') + console.info('beforeEach called') }) - + afterEach(function() { /* * @tc.teardown: teardown invoked after each testcases */ - console.info('afterEach called') - particleAbility.cancelBackgroundRunning(); - setTimeout(() => {}, 500); - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()); - setTimeout(() => {}, 500); + console.info('afterEach called') + particleAbility.cancelBackgroundRunning(); + setTimeout(() => { }, 500); + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()); + setTimeout(() => { }, 500); }) /* @@ -75,18 +75,18 @@ describe("ContinuousTaskJsTest", function () { wantAgent.getWantAgent(wantAgentInfo).then((data) => { backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then(() => { - console.log("ContinuousTaskJsTest001 startBackgroundRunning success"); - expect(true).assertTrue(); - setTimeout(() => { - done(); - }, 500); - }).catch((err) => { - expect(false).assertTrue(); - console.log("ContinuousTaskJsTest001 startBackgroundRunning failure"); - setTimeout(() => { - done(); - }, 500); - }); + console.log("ContinuousTaskJsTest001 startBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest001 startBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); }); }) @@ -105,7 +105,7 @@ describe("ContinuousTaskJsTest", function () { console.info('ContinuousTaskJsTest002 startBackgroundRunning succeed'); expect(true).assertTrue(); } - setTimeout(()=>{ + setTimeout(() => { done(); }, 500); } @@ -193,7 +193,7 @@ describe("ContinuousTaskJsTest", function () { console.info('ContinuousTaskJsTest004 startBackgroundRunning success'); expect(true).assertTrue(); } - setTimeout(()=>{ + setTimeout(() => { done(); }, 500); } @@ -251,29 +251,29 @@ describe("ContinuousTaskJsTest", function () { wantAgent.getWantAgent(wantAgentInfo).then((data) => { backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then((data) => { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then((data) => { - console.log("ContinuousTaskJsTest005 cancelBackgroundRunning success"); - expect(true).assertTrue(); - setTimeout(() => { - done(); - }, 500); - }).catch((err) => { - expect(false).assertTrue(); - console.log("ContinuousTaskJsTest005 cancelBackgroundRunning failure"); - setTimeout(() => { - done(); - }, 500); - }); - }) + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then((data) => { + console.log("ContinuousTaskJsTest005 cancelBackgroundRunning success"); + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + expect(false).assertTrue(); + console.log("ContinuousTaskJsTest005 cancelBackgroundRunning failure"); + setTimeout(() => { + done(); + }, 500); + }); + }) }); }) /* - * @tc.name:ContinuousTaskJsTest006 - * @tc.desc:verify new api stopBackgroundrunning interface callback mode work properly - * @tc.type: FUNC - * @tc.require: SR000GGT7T AR000GH6ES AR000GH6EP AR000GJ9PR AR000GH6G8 - */ + * @tc.name:ContinuousTaskJsTest006 + * @tc.desc:verify new api stopBackgroundrunning interface callback mode work properly + * @tc.type: FUNC + * @tc.require: SR000GGT7T AR000GH6ES AR000GH6EP AR000GJ9PR AR000GH6G8 + */ it("ContinuousTaskJsTest006", 0, async function (done) { function conTaskCallback(err, data) { if (err) { @@ -283,7 +283,7 @@ describe("ContinuousTaskJsTest", function () { console.info('ContinuousTaskJsTest006 startBackgroundRunning success'); expect(true).assertTrue(); } - setTimeout(()=>{ + setTimeout(() => { done(); }, 500); } @@ -301,8 +301,8 @@ describe("ContinuousTaskJsTest", function () { wantAgent.getWantAgent(wantAgentInfo).then((data) => { backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then((data) => { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), conTaskCallback); - }) + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), conTaskCallback); + }) }); }) @@ -326,7 +326,7 @@ describe("ContinuousTaskJsTest", function () { }; await wantAgent.getWantAgent(wantAgentInfo).then((data) => { particleAbility.startBackgroundRunning(data); - setTimeout(()=>{ + setTimeout(() => { }, 500); }); @@ -336,7 +336,7 @@ describe("ContinuousTaskJsTest", function () { setTimeout(() => { done(); }, 500); - }).catch( (err) => { + }).catch((err) => { expect(false).assertTrue(); console.log("ContinuousTaskJsTest007 cancelBackgroundRunning failure"); setTimeout(() => { @@ -360,7 +360,7 @@ describe("ContinuousTaskJsTest", function () { console.info('ContinuousTaskJsTest008 startBackgroundRunning success'); expect(true).assertTrue(); } - setTimeout(()=>{ + setTimeout(() => { done(); }, 500); } @@ -377,10 +377,180 @@ describe("ContinuousTaskJsTest", function () { }; await wantAgent.getWantAgent(wantAgentInfo).then((data) => { particleAbility.startBackgroundRunning(data); - setTimeout(()=>{ + setTimeout(() => { }, 500); }); particleAbility.cancelBackgroundRunning(conTaskCallback); }) + + /* + * @tc.name:ContinuousTaskJsTest009 + * @tc.desc:verify startBackgroundRunning promise workTime + * @tc.type: FUNC + */ + it("ContinuousTaskJsTest009", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + let startTime = (new Date()).valueOf() + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then(() => { + let endTime = (new Date()).valueOf() + let workTime = endTime - startTime + if (workTime < 50) { + expect(true).assertTrue() + } else { + expect(false).assertTrue() + } + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + expect(false).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }); + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest010 + * @tc.desc:verify startBackgroundRunning callback workTime + * @tc.type: FUNC + */ + it("ContinuousTaskJsTest010", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest010 startBackgroundRunning failed'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest010 startBackgroundRunning succeed'); + expect(true).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + let startTime = (new Date()).valueOf() + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data, conTaskCallback); + let endTime = (new Date()).valueOf() + let workTime = endTime - startTime + if (workTime < 50) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue() + } + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest011 + * @tc.desc:verify stopBackgroundRunning promise workTime + * @tc.type: FUNC + */ + it("ContinuousTaskJsTest011", 0, async function (done) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then((data) => { + let startTime = (new Date()).valueOf() + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then((data) => { + let endTime = (new Date()).valueOf() + let workTime = endTime - startTime + if (workTime < 50) { + expect(true).assertTrue() + } else { + expect(false).assertTrue() + } + setTimeout(() => { + done(); + }, 500); + }).catch((err) => { + setTimeout(() => { + done(); + }, 500); + }); + }) + }); + }) + + /* + * @tc.name:ContinuousTaskJsTest012 + * @tc.desc:verify stopBackgroundRunning callback workTime + * @tc.type: FUNC + */ + it("ContinuousTaskJsTest012", 0, async function (done) { + function conTaskCallback(err, data) { + if (err) { + console.info('ContinuousTaskJsTest012 startBackgroundRunning failure'); + expect(false).assertTrue(); + } else { + console.info('ContinuousTaskJsTest012 startBackgroundRunning success'); + expect(true).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + let wantAgentInfo = { + wants: [ + { + bundleName: "com.continuoustask.test", + abilityName: "com.continuoustask.test.MainAbility" + } + ], + operationType: 2, + requestCode: 0, + wantAgentFlags: [3] + }; + wantAgent.getWantAgent(wantAgentInfo).then((data) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data).then((data) => { + let startTime = (new Date()).valueOf() + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), conTaskCallback); + let endTime = (new Date()).valueOf() + let workTime = endTime - startTime + if (workTime < 50) { + expect(true).assertTrue() + } else { + expect(false).assertTrue() + } + }) + }); + }) }) \ No newline at end of file diff --git a/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js b/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js index bb5e8d71..224ebcb7 100644 --- a/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js +++ b/interfaces/test/unittest/transient_task_jsunittest/transient_task_jsunit.test.js @@ -14,35 +14,35 @@ */ import backgroundTaskManager from '@ohos.backgroundTaskManager' -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' describe("TransientTaskJsTest", function () { beforeAll(function() { /* * @tc.setup: setup invoked before all testcases */ - console.info('beforeAll caled') + console.info('beforeAll caled') }) afterAll(function() { /* * @tc.teardown: teardown invoked after all testcases */ - console.info('afterAll caled') + console.info('afterAll caled') }) beforeEach(function() { /* * @tc.setup: setup invoked before each testcases */ - console.info('beforeEach caled') + console.info('beforeEach caled') }) afterEach(function() { /* * @tc.teardown: teardown invoked after each testcases */ - console.info('afterEach caled') + console.info('afterEach caled') }) /* @@ -53,7 +53,7 @@ describe("TransientTaskJsTest", function () { */ it("TransientTaskJsTest001", 0, async function (done) { console.info('----------------------TransientTaskJsTest001---------------------------'); - function callback() {} + function callback() { } var info = backgroundTaskManager.requestSuspendDelay("test", callback); if (info.requestId != -1) { console.info('TransientTaskJsTest001 backgroundTaskManager success, requestId:' + info.requestId); @@ -73,11 +73,11 @@ describe("TransientTaskJsTest", function () { */ it("TransientTaskJsTest002", 0, async function (done) { console.info('----------------------TransientTaskJsTest002---------------------------'); - function callback() {} - var info1 = backgroundTaskManager.requestSuspendDelay("test", callback); - var info2 = backgroundTaskManager.requestSuspendDelay("test", callback); - var info3 = backgroundTaskManager.requestSuspendDelay("test", callback); - var info4 = backgroundTaskManager.requestSuspendDelay("test", callback); + function callback() { } + var info1 = backgroundTaskManager.requestSuspendDelay("test", callback); + var info2 = backgroundTaskManager.requestSuspendDelay("test", callback); + var info3 = backgroundTaskManager.requestSuspendDelay("test", callback); + var info4 = backgroundTaskManager.requestSuspendDelay("test", callback); if (info4.requestId == -1) { console.info('TransientTaskJsTest002 backgroundTaskManager more than three'); expect(true).assertTrue(); @@ -97,7 +97,7 @@ describe("TransientTaskJsTest", function () { * @tc.require: SR000GGTJV AR000GH86M AR000GH860 AR000GH86L */ it("TransientTaskJsTest003", 0, async function (done) { - function callback() {} + function callback() { } var info = backgroundTaskManager.requestSuspendDelay("test", callback); if (info.requestId != -1) { console.info('TransientTaskJsTest003 backgroundTaskManager success, requestId:' + info.requestId); @@ -117,7 +117,7 @@ describe("TransientTaskJsTest", function () { expect(false).assertTrue(); }); - setTimeout(()=>{ + setTimeout(() => { done(); }, 500); }) @@ -129,7 +129,7 @@ describe("TransientTaskJsTest", function () { * @tc.require: SR000GGTJV AR000GH86M AR000GH860 AR000GH86L */ it("TransientTaskJsTest004", 0, async function (done) { - function callback() {} + function callback() { } var info = backgroundTaskManager.requestSuspendDelay("test", callback); if (info.requestId != -1) { console.info('TransientTaskJsTest004 backgroundTaskManager success, requestId:' + info.requestId); @@ -151,9 +151,123 @@ describe("TransientTaskJsTest", function () { backgroundTaskManager.cancelSuspendDelay(info.requestId) }); - setTimeout(()=>{ + setTimeout(() => { done(); }, 500); }) + /* + * @tc.name: TransientTaskJsTest005 + * @tc.desc: test requestSuspendDelay workTime + * @tc.type: FUNC + */ + it("TransientTaskJsTest005", 0, async function (done) { + function callback() { } + let startTime = (new Date()).valueOf() + var info = backgroundTaskManager.requestSuspendDelay("test", callback); + if (info.requestId != -1) { + let endTime = (new Date()).valueOf() + let workTime = endTime - startTime + if (workTime < 50) { + expect(true).assertTrue() + } else { + expect(false).assertTrue() + } + backgroundTaskManager.cancelSuspendDelay(info.requestId) + } else { + expect(false).assertTrue(); + } + done(); + }) + + /* + * @tc.name: TransientTaskJsTest006 + * @tc.desc: test getRemainingDelayTime Promise workTime + * @tc.type: FUNC + */ + it("TransientTaskJsTest006 ", 0, async function (done) { + function callback() { } + var info = backgroundTaskManager.requestSuspendDelay("test", callback); + if (info.requestId != -1) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + done(); + } + let endTime = 0 + let startTime = (new Date()).valueOf() + backgroundTaskManager.getRemainingDelayTime(info.requestId) + .then(data => { + endTime = (new Date()).valueOf() + let workTime = endTime - startTime + if (workTime < 50) { + expect(true).assertTrue() + } else { + expect(false).assertTrue() + } + backgroundTaskManager.cancelSuspendDelay(info.requestId); + }) + .catch(error => { + expect(false).assertTrue(); + }); + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: TransientTaskJsTest007 + * @tc.desc: test getRemainingDelayTime callback workTime + * @tc.type: FUNC + */ + it("TransientTaskJsTest007", 0, async function (done) { + function callback() { } + var info = backgroundTaskManager.requestSuspendDelay("test", callback); + if (info.requestId != -1) { + console.info('TransientTaskJsTest007 backgroundTaskManager success, requestId:' + info.requestId); + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + done(); + } + let startTime = (new Date()).valueOf() + backgroundTaskManager.getRemainingDelayTime(info.requestId, (err, res) => { + let endTime = (new Date()).valueOf() + let workTime = endTime - startTime + if (workTime < 50) { + expect(true).assertTrue() + } else { + expect(false).assertTrue() + } + backgroundTaskManager.cancelSuspendDelay(info.requestId) + }); + setTimeout(() => { + done(); + }, 500); + }) + + /* + * @tc.name: TransientTaskJsTest008 + * @tc.desc: test cancelSuspendDelay workTime + * @tc.type: FUNC + */ + it("TransientTaskJsTest008", 0, async function (done) { + function callback() { } + var info = backgroundTaskManager.requestSuspendDelay("test", callback); + if (info.requestId != -1) { + let startTime = (new Date()).valueOf() + backgroundTaskManager.cancelSuspendDelay(info.requestId) + let endTime = (new Date()).valueOf() + let workTime = endTime - startTime + if (workTime < 50) { + expect(true).assertTrue() + } else { + expect(false).assertTrue() + } + } else { + expect(false).assertTrue() + } + done(); + }) + }) -- Gitee From 3f37d066347edb72783a78fbf12f2c65a864b321 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Wed, 16 Mar 2022 08:38:04 +0800 Subject: [PATCH 71/77] codex bugfix Signed-off-by: zhangxin_T --- frameworks/src/background_task_mgr_proxy.cpp | 2 +- frameworks/src/background_task_mgr_stub.cpp | 2 +- interfaces/innerkits/src/continuous_task_param.cpp | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/frameworks/src/background_task_mgr_proxy.cpp b/frameworks/src/background_task_mgr_proxy.cpp index a5d88bf4..726df3f9 100644 --- a/frameworks/src/background_task_mgr_proxy.cpp +++ b/frameworks/src/background_task_mgr_proxy.cpp @@ -171,7 +171,7 @@ ErrCode BackgroundTaskMgrProxy::StopBackgroundRunning(const std::string &ability return ERR_BGTASK_PARCELABLE_FAILED; } - if (!data.WriteParcelable(abilityToken)) { + if (!data.WriteRemoteObject(abilityToken)) { BGTASK_LOGE("parcel ability token failed"); return ERR_BGTASK_PARCELABLE_FAILED; } diff --git a/frameworks/src/background_task_mgr_stub.cpp b/frameworks/src/background_task_mgr_stub.cpp index 1b4bef13..2ef7c347 100644 --- a/frameworks/src/background_task_mgr_stub.cpp +++ b/frameworks/src/background_task_mgr_stub.cpp @@ -153,7 +153,7 @@ ErrCode BackgroundTaskMgrStub::HandleStopBackgroundRunning(MessageParcel &data, if (!data.ReadString(abilityName)) { return ERR_BGTASK_PARCELABLE_FAILED; } - sptr abilityToken = data.ReadParcelable(); + sptr abilityToken = data.ReadRemoteObject(); ErrCode result = StopBackgroundRunning(abilityName, abilityToken); if (!reply.WriteInt32(result)) { BGTASK_LOGE("write result failed, ErrCode=%{public}d", result); diff --git a/interfaces/innerkits/src/continuous_task_param.cpp b/interfaces/innerkits/src/continuous_task_param.cpp index 6b79d16c..0b81dabf 100644 --- a/interfaces/innerkits/src/continuous_task_param.cpp +++ b/interfaces/innerkits/src/continuous_task_param.cpp @@ -46,7 +46,7 @@ bool ContinuousTaskParam::ReadFromParcel(Parcel &parcel) } valid = parcel.ReadBool(); if (valid) { - abilityToken_ = parcel.ReadParcelable(); + abilityToken_ = parcel.ReadObject(); if (!abilityToken_) { BGTASK_LOGE("Failed to read ablityToken"); return false; @@ -102,7 +102,7 @@ bool ContinuousTaskParam::Marshalling(Parcel &parcel) const return false; } if (valid) { - if (!parcel.WriteParcelable(abilityToken_)) { + if (!parcel.WriteObject(abilityToken_)) { BGTASK_LOGE("parcel ability token failed"); return false; } -- Gitee From 5bd763bee37d6837533c4b8c7940a221fd236f72 Mon Sep 17 00:00:00 2001 From: zhangxin_T Date: Thu, 17 Mar 2022 08:36:51 +0800 Subject: [PATCH 72/77] codex bugfix Signed-off-by: zhangxin_T --- .../innerkits/src/continuous_task_param.cpp | 6 ++-- .../continuous_task/include/data_storage.h | 2 +- .../src/app_state_observer.cpp | 2 +- .../src/bundle_manager_helper.cpp | 2 +- services/continuous_task/src/data_storage.cpp | 29 ++++++++++++------- 5 files changed, 23 insertions(+), 18 deletions(-) diff --git a/interfaces/innerkits/src/continuous_task_param.cpp b/interfaces/innerkits/src/continuous_task_param.cpp index 0b81dabf..6878d5d8 100644 --- a/interfaces/innerkits/src/continuous_task_param.cpp +++ b/interfaces/innerkits/src/continuous_task_param.cpp @@ -29,8 +29,7 @@ bool ContinuousTaskParam::ReadFromParcel(Parcel &parcel) BGTASK_LOGE("Failed to read request background mode info"); return false; } - bool valid = false; - valid = parcel.ReadBool(); + bool valid = parcel.ReadBool(); if (valid) { wantAgent_ = std::shared_ptr( parcel.ReadParcelable()); @@ -78,8 +77,7 @@ bool ContinuousTaskParam::Marshalling(Parcel &parcel) const BGTASK_LOGE("Failed to write request background mode info"); return false; } - bool valid = false; - valid = wantAgent_ != nullptr; + bool valid = wantAgent_ != nullptr; if (!parcel.WriteBool(valid)) { BGTASK_LOGE("Failed to write the flag which indicate whether wantAgent is null"); return false; diff --git a/services/continuous_task/include/data_storage.h b/services/continuous_task/include/data_storage.h index c76e3667..da148eb9 100644 --- a/services/continuous_task/include/data_storage.h +++ b/services/continuous_task/include/data_storage.h @@ -26,7 +26,7 @@ public: int32_t RestoreTaskRecord(std::unordered_map> &allRecord); private: - int32_t CreateNodeFile(const std::string &filePath); + bool CreateNodeFile(const std::string &filePath); bool ConvertFullPath(const std::string &partialPath, std::string &fullPath); }; } diff --git a/services/continuous_task/src/app_state_observer.cpp b/services/continuous_task/src/app_state_observer.cpp index 3494fd94..dff74a48 100644 --- a/services/continuous_task/src/app_state_observer.cpp +++ b/services/continuous_task/src/app_state_observer.cpp @@ -144,7 +144,7 @@ bool AppStateObserver::Connect() void AppStateObserver::Disconnect() { - if (appMgrProxy_ != nullptr) { + if (appMgrProxy_ != nullptr && appMgrProxy_->AsObject() != nullptr) { appMgrProxy_->AsObject()->RemoveDeathRecipient(appMgrDeathRecipient_); appMgrProxy_ = nullptr; } diff --git a/services/continuous_task/src/bundle_manager_helper.cpp b/services/continuous_task/src/bundle_manager_helper.cpp index 0b144d40..3c0e8aa0 100644 --- a/services/continuous_task/src/bundle_manager_helper.cpp +++ b/services/continuous_task/src/bundle_manager_helper.cpp @@ -117,7 +117,7 @@ bool BundleManagerHelper::Connect() void BundleManagerHelper::Disconnect() { - if (bundleMgr_ != nullptr && bundleMgrDeathRecipient_ != nullptr) { + if (bundleMgr_ != nullptr && bundleMgr_->AsObject() != nullptr) { bundleMgr_->AsObject()->RemoveDeathRecipient(bundleMgrDeathRecipient_); bundleMgr_ = nullptr; } diff --git a/services/continuous_task/src/data_storage.cpp b/services/continuous_task/src/data_storage.cpp index ccf435b9..c2ef610f 100644 --- a/services/continuous_task/src/data_storage.cpp +++ b/services/continuous_task/src/data_storage.cpp @@ -55,7 +55,10 @@ int32_t DataStorage::RefreshTaskRecord(const std::unordered_map jsonWriter(writerBuilder.newStreamWriter()); jsonWriter->write(root, &os); std::string result = os.str(); - CreateNodeFile(TASK_RECORD_FILE_PATH); + if (!CreateNodeFile(TASK_RECORD_FILE_PATH)) { + BGTASK_LOGE("Create file failed."); + return ERR_BGTASK_DATA_STORAGE_ERR; + } std::ofstream fout; std::string realPath; if (!ConvertFullPath(TASK_RECORD_FILE_PATH, realPath)) { @@ -64,6 +67,10 @@ int32_t DataStorage::RefreshTaskRecord(const std::unordered_map Date: Thu, 17 Mar 2022 10:31:11 +0800 Subject: [PATCH 73/77] codex bugfix Signed-off-by: zhangxin_T --- services/continuous_task/src/continuous_task_record.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index 96e0d058..cdc51d5c 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -124,7 +124,7 @@ bool ContinuousTaskRecord::ParseFromJson(const Json::Value value) this->userId_ = value["userId"].asInt(); this->uid_ = value["uid"].asInt(); this->pid_ = value["pid"].asInt(); - this->bgModeId_ = value["bgModeId"].asInt(); + this->bgModeId_ = value["bgModeId"].asUInt(); this->isNewApi_ = value["isNewApi"].asBool(); this->notificationLabel_ = value["notificationLabel"].asString(); -- Gitee From 8167e769daec49def8632a47ac09f4f1593b626f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BB=96=E5=BA=B7=E5=BA=B7?= Date: Mon, 21 Mar 2022 15:47:19 +0800 Subject: [PATCH 74/77] =?UTF-8?q?=E5=86=85=E6=BA=90=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 廖康康 --- .../common/include/continuous_task_log.h | 2 +- frameworks/common/include/ipc_util.h | 4 ++-- frameworks/include/background_task_manager.h | 4 ++-- .../include/background_task_subscriber_stub.h | 4 ++-- frameworks/src/background_task_manager.cpp | 4 ++-- .../src/background_task_subscriber_stub.cpp | 8 +++---- .../innerkits/include/background_mode.h | 6 ++--- .../include/background_task_subscriber.h | 2 +- .../include/continuous_task_callback_info.h | 6 ++--- .../innerkits/include/continuous_task_param.h | 11 +++++----- .../innerkits/include/expired_callback.h | 2 +- .../src/continuous_task_callback_info.cpp | 4 ++-- .../innerkits/src/continuous_task_param.cpp | 4 ++-- .../innerkits/src/delay_suspend_info.cpp | 3 +++ .../kits/js/@ohos.backgroundTaskManager.d.ts | 2 +- .../kits/napi/include/request_suspend_delay.h | 2 +- .../src/bg_continuous_task_napi_module.cpp | 4 ++-- interfaces/kits/napi/src/common.cpp | 2 +- .../include/app_state_observer.h | 6 ++--- .../include/bg_continuous_task_mgr.h | 7 +++--- .../include/bundle_manager_helper.h | 7 +++--- .../include/continuous_task_record.h | 6 ++--- .../include/remote_death_recipient.h | 8 +++---- .../include/system_event_observer.h | 8 +++---- .../include/task_notification_subscriber.h | 22 +++++++++---------- .../src/app_state_observer.cpp | 4 ++-- .../src/bg_continuous_task_mgr.cpp | 4 ++-- .../src/bundle_manager_helper.cpp | 4 ++-- .../src/continuous_task_record.cpp | 4 ++-- .../src/system_event_observer.cpp | 4 ++-- .../src/task_notification_subscriber.cpp | 2 +- services/test/unittest/BUILD.gn | 2 +- .../background_task_mgr_service_test.cpp | 8 +++---- .../unittest/bg_continuous_task_mgr_test.cpp | 8 +++---- .../unittest/bg_transient_task_mgr_test.cpp | 8 +++---- .../mock/mock_bundle_manager_helper.cpp | 4 ++-- .../unittest/mock/mock_resource_manager.cpp | 6 ++--- .../include/bg_transient_task_mgr.h | 1 + .../transient_task/include/decision_maker.h | 10 ++++----- services/transient_task/include/event_info.h | 1 + .../transient_task/include/timer_manager.h | 2 +- .../src/bg_transient_task_mgr.cpp | 8 +++---- .../src/device_info_manager.cpp | 2 +- .../bgtask_observer/include/bgtask_observer.h | 12 +++++----- utils/bgtask_observer/src/bgtask_observer.cpp | 4 ++-- utils/dump/include/shell_command.h | 6 ----- utils/dump/src/bgtaskmgr_shell_command.cpp | 2 +- 47 files changed, 120 insertions(+), 124 deletions(-) diff --git a/frameworks/common/include/continuous_task_log.h b/frameworks/common/include/continuous_task_log.h index 282ef60d..0cd13f93 100644 --- a/frameworks/common/include/continuous_task_log.h +++ b/frameworks/common/include/continuous_task_log.h @@ -22,4 +22,4 @@ #include "bgtaskmgr_log_wrapper.h" -#endif \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_COMMON_INCLUDE_CONTINUOUS_TASK_LOG_H \ No newline at end of file diff --git a/frameworks/common/include/ipc_util.h b/frameworks/common/include/ipc_util.h index 98d25f33..6e95fa07 100644 --- a/frameworks/common/include/ipc_util.h +++ b/frameworks/common/include/ipc_util.h @@ -61,6 +61,6 @@ static inline sptr GetSystemService(const std::string &name) auto registry = ServiceRegistry::GetInstance(); return (registry != nullptr) ? registry->GetService(Str8ToStr16(name)) : nullptr; } -}; -}; +}; // namespace BackgroundTaskMgr +}; // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_FRAMEWORKS_COMMON_INCLUDE_IPC_UTIL_H \ No newline at end of file diff --git a/frameworks/include/background_task_manager.h b/frameworks/include/background_task_manager.h index ff8bdf18..1c023a67 100644 --- a/frameworks/include/background_task_manager.h +++ b/frameworks/include/background_task_manager.h @@ -55,11 +55,11 @@ private: private: class BgTaskMgrDeathRecipient : public IRemoteObject::DeathRecipient { public: - BgTaskMgrDeathRecipient(BackgroundTaskManager &backgroundTaskManager); + explicit BgTaskMgrDeathRecipient(BackgroundTaskManager &backgroundTaskManager); ~BgTaskMgrDeathRecipient(); - virtual void OnRemoteDied(const wptr &object) override; + void OnRemoteDied(const wptr &object) override; private: BackgroundTaskManager &backgroundTaskManager_; diff --git a/frameworks/include/background_task_subscriber_stub.h b/frameworks/include/background_task_subscriber_stub.h index a72025c9..1571c592 100644 --- a/frameworks/include/background_task_subscriber_stub.h +++ b/frameworks/include/background_task_subscriber_stub.h @@ -31,8 +31,8 @@ public: int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; private: - ErrCode HandleOnConnected(MessageParcel &data); - ErrCode HandleOnDisconnected(MessageParcel &data); + ErrCode HandleOnConnected(); + ErrCode HandleOnDisconnected(); ErrCode HandleOnTransientTaskStart(MessageParcel& data); ErrCode HandleOnTransientTaskEnd(MessageParcel& data); ErrCode HandleOnContinuousTaskStart(MessageParcel &data); diff --git a/frameworks/src/background_task_manager.cpp b/frameworks/src/background_task_manager.cpp index 8c96b916..ffca3be7 100644 --- a/frameworks/src/background_task_manager.cpp +++ b/frameworks/src/background_task_manager.cpp @@ -172,9 +172,9 @@ ErrCode BackgroundTaskManager::ShellDump(const std::vector &dumpOpt } BackgroundTaskManager::BgTaskMgrDeathRecipient::BgTaskMgrDeathRecipient(BackgroundTaskManager &backgroundTaskManager) - : backgroundTaskManager_(backgroundTaskManager) {}; + : backgroundTaskManager_(backgroundTaskManager) {} -BackgroundTaskManager::BgTaskMgrDeathRecipient::~BgTaskMgrDeathRecipient() {}; +BackgroundTaskManager::BgTaskMgrDeathRecipient::~BgTaskMgrDeathRecipient() {} void BackgroundTaskManager::BgTaskMgrDeathRecipient::OnRemoteDied(const wptr &remote) { diff --git a/frameworks/src/background_task_subscriber_stub.cpp b/frameworks/src/background_task_subscriber_stub.cpp index 6c9e602a..685f0f1f 100644 --- a/frameworks/src/background_task_subscriber_stub.cpp +++ b/frameworks/src/background_task_subscriber_stub.cpp @@ -48,10 +48,10 @@ int BackgroundTaskSubscriberStub::OnRemoteRequest(uint32_t code, switch (code) { case ON_CONNECTED: { - return HandleOnConnected(data); + return HandleOnConnected(); } case ON_DISCONNECTED: { - return HandleOnDisconnected(data); + return HandleOnDisconnected(); } case ON_TRANSIENT_TASK_START: { return HandleOnTransientTaskStart(data); @@ -70,13 +70,13 @@ int BackgroundTaskSubscriberStub::OnRemoteRequest(uint32_t code, } } -ErrCode BackgroundTaskSubscriberStub::HandleOnConnected(MessageParcel &data) +ErrCode BackgroundTaskSubscriberStub::HandleOnConnected() { OnConnected(); return ERR_OK; } -ErrCode BackgroundTaskSubscriberStub::HandleOnDisconnected(MessageParcel &data) +ErrCode BackgroundTaskSubscriberStub::HandleOnDisconnected() { OnDisconnected(); return ERR_OK; diff --git a/interfaces/innerkits/include/background_mode.h b/interfaces/innerkits/include/background_mode.h index eaeb3051..da0cc2d6 100644 --- a/interfaces/innerkits/include/background_mode.h +++ b/interfaces/innerkits/include/background_mode.h @@ -33,6 +33,6 @@ public: TASK_KEEPING, }; }; -} -} -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_BACKGROUND_MODE_H \ No newline at end of file diff --git a/interfaces/innerkits/include/background_task_subscriber.h b/interfaces/innerkits/include/background_task_subscriber.h index aaa5e10a..95a3247c 100644 --- a/interfaces/innerkits/include/background_task_subscriber.h +++ b/interfaces/innerkits/include/background_task_subscriber.h @@ -95,7 +95,7 @@ private: public: BackgroundTaskSubscriberImpl(BackgroundTaskSubscriber &subscriber); - ~BackgroundTaskSubscriberImpl() {}; + ~BackgroundTaskSubscriberImpl() {} void OnConnected() override; void OnDisconnected() override; void OnTransientTaskStart(const std::shared_ptr& info) override; diff --git a/interfaces/innerkits/include/continuous_task_callback_info.h b/interfaces/innerkits/include/continuous_task_callback_info.h index 46f91afb..e91b0141 100644 --- a/interfaces/innerkits/include/continuous_task_callback_info.h +++ b/interfaces/innerkits/include/continuous_task_callback_info.h @@ -43,6 +43,6 @@ private: pid_t creatorPid_ {0}; std::string abilityName_ {""}; }; -} -} -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_LONGTIME_TASK_EVENT_DATA_H \ No newline at end of file diff --git a/interfaces/innerkits/include/continuous_task_param.h b/interfaces/innerkits/include/continuous_task_param.h index 69b86024..226aa755 100644 --- a/interfaces/innerkits/include/continuous_task_param.h +++ b/interfaces/innerkits/include/continuous_task_param.h @@ -28,7 +28,7 @@ struct ContinuousTaskParam : public Parcelable { std::shared_ptr wantAgent_ {nullptr}; std::string abilityName_ {""}; sptr abilityToken_ {nullptr}; - + ContinuousTaskParam() = default; ContinuousTaskParam(bool isNewApi, uint32_t bgModeId, const std::shared_ptr wantAgent, const std::string abilityName, @@ -37,10 +37,9 @@ struct ContinuousTaskParam : public Parcelable { abilityName_(abilityName), abilityToken_(abilityToken) {} bool ReadFromParcel(Parcel &parcel); - virtual bool Marshalling(Parcel &parcel) const override; + bool Marshalling(Parcel &parcel) const override; static ContinuousTaskParam *Unmarshalling(Parcel &parcel); }; -} -} - -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_INTERFACES_INNERKITS_INCLUDE_CONTINUOUS_TASK_PARAMS_H \ No newline at end of file diff --git a/interfaces/innerkits/include/expired_callback.h b/interfaces/innerkits/include/expired_callback.h index 68b6d4f4..2de364d8 100644 --- a/interfaces/innerkits/include/expired_callback.h +++ b/interfaces/innerkits/include/expired_callback.h @@ -44,7 +44,7 @@ private: class ExpiredCallbackImpl final : public ExpiredCallbackStub { public: ExpiredCallbackImpl(ExpiredCallback &callback); - ~ExpiredCallbackImpl() {}; + ~ExpiredCallbackImpl() {} void OnExpired() override; public: diff --git a/interfaces/innerkits/src/continuous_task_callback_info.cpp b/interfaces/innerkits/src/continuous_task_callback_info.cpp index 9be2f68f..b2e5f4fa 100644 --- a/interfaces/innerkits/src/continuous_task_callback_info.cpp +++ b/interfaces/innerkits/src/continuous_task_callback_info.cpp @@ -92,5 +92,5 @@ bool ContinuousTaskCallbackInfo::ReadFromParcel(Parcel &parcel) } return true; } -} -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/src/continuous_task_param.cpp b/interfaces/innerkits/src/continuous_task_param.cpp index 6878d5d8..82570f9b 100644 --- a/interfaces/innerkits/src/continuous_task_param.cpp +++ b/interfaces/innerkits/src/continuous_task_param.cpp @@ -107,5 +107,5 @@ bool ContinuousTaskParam::Marshalling(Parcel &parcel) const } return true; } -} -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/src/delay_suspend_info.cpp b/interfaces/innerkits/src/delay_suspend_info.cpp index bb2f392c..68f45102 100644 --- a/interfaces/innerkits/src/delay_suspend_info.cpp +++ b/interfaces/innerkits/src/delay_suspend_info.cpp @@ -33,6 +33,9 @@ bool DelaySuspendInfo::Marshalling(Parcel& out) const std::shared_ptr DelaySuspendInfo::Unmarshalling(Parcel &in) { auto info = std::make_shared(); + if (info == nullptr) { + return nullptr; + } return info->ReadFromParcel(in) ? info : nullptr; } diff --git a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts index fd8692f5..c547680f 100644 --- a/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts +++ b/interfaces/kits/js/@ohos.backgroundTaskManager.d.ts @@ -171,7 +171,7 @@ declare namespace backgroundTaskManager { VOIP = 8, /** - * backgroud continuous calculate mode, for example 3d render. + * background continuous calculate mode, for example 3d render. * only supported in portable computer * * @since 8 diff --git a/interfaces/kits/napi/include/request_suspend_delay.h b/interfaces/kits/napi/include/request_suspend_delay.h index f118c3df..d240b63b 100644 --- a/interfaces/kits/napi/include/request_suspend_delay.h +++ b/interfaces/kits/napi/include/request_suspend_delay.h @@ -30,7 +30,7 @@ public: virtual ~CallbackInstance(); - virtual void OnExpired() override; + void OnExpired() override; void SetCallbackInfo(const napi_env &env, const napi_ref &ref); diff --git a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp index b9a5b029..d9dd44fc 100644 --- a/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp +++ b/interfaces/kits/napi/src/bg_continuous_task_napi_module.cpp @@ -471,5 +471,5 @@ napi_value StopBackgroundRunning(napi_env env, napi_callback_info info) BGTASK_LOGI("end"); return ret; } -} // namespace BackgroundTaskMgr -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/src/common.cpp b/interfaces/kits/napi/src/common.cpp index fe7d07cd..526662d6 100644 --- a/interfaces/kits/napi/src/common.cpp +++ b/interfaces/kits/napi/src/common.cpp @@ -145,7 +145,7 @@ napi_value Common::GetU16StringValue(const napi_env &env, const napi_value &valu char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); - + result = Str8ToStr16((std::string)str); BGTASK_LOGI("string result: %{public}s", Str16ToStr8(result).c_str()); } else { diff --git a/services/continuous_task/include/app_state_observer.h b/services/continuous_task/include/app_state_observer.h index b0a3d97a..28d5fe86 100644 --- a/services/continuous_task/include/app_state_observer.h +++ b/services/continuous_task/include/app_state_observer.h @@ -50,6 +50,6 @@ private: sptr appMgrProxy_ {nullptr}; sptr appMgrDeathRecipient_ {nullptr}; }; -} -} -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_APP_STATE_OBSERVER_H \ No newline at end of file diff --git a/services/continuous_task/include/bg_continuous_task_mgr.h b/services/continuous_task/include/bg_continuous_task_mgr.h index dacdb939..026bbca7 100644 --- a/services/continuous_task/include/bg_continuous_task_mgr.h +++ b/services/continuous_task/include/bg_continuous_task_mgr.h @@ -116,7 +116,6 @@ private: DECLARE_DELAYED_SINGLETON(BgContinuousTaskMgr); }; -} -} - -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BG_CONTINUOUS_TASK_MGR_H \ No newline at end of file diff --git a/services/continuous_task/include/bundle_manager_helper.h b/services/continuous_task/include/bundle_manager_helper.h index 7be2323d..2be45003 100644 --- a/services/continuous_task/include/bundle_manager_helper.h +++ b/services/continuous_task/include/bundle_manager_helper.h @@ -47,7 +47,6 @@ private: DECLARE_DELAYED_SINGLETON(BundleManagerHelper) }; -} -} - -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_BUNDLE_MANAGER_HELPER_H \ No newline at end of file diff --git a/services/continuous_task/include/continuous_task_record.h b/services/continuous_task/include/continuous_task_record.h index 1eb3acaf..92a62137 100644 --- a/services/continuous_task/include/continuous_task_record.h +++ b/services/continuous_task/include/continuous_task_record.h @@ -66,6 +66,6 @@ private: friend class BgContinuousTaskMgr; }; -} -} -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_CONTINUOUS_TASK_INFO_H \ No newline at end of file diff --git a/services/continuous_task/include/remote_death_recipient.h b/services/continuous_task/include/remote_death_recipient.h index d1587747..ce02c6c9 100644 --- a/services/continuous_task/include/remote_death_recipient.h +++ b/services/continuous_task/include/remote_death_recipient.h @@ -24,7 +24,7 @@ namespace OHOS { namespace BackgroundTaskMgr { class RemoteDeathRecipient : public IRemoteObject::DeathRecipient { public: - RemoteDeathRecipient(std::function &)> callback) + explicit RemoteDeathRecipient(std::function &)> callback) { callback_ = callback; } @@ -44,6 +44,6 @@ public: private: std::function &)> callback_; }; -} -} -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_REMOTE_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/continuous_task/include/system_event_observer.h b/services/continuous_task/include/system_event_observer.h index c46e20a9..9228b0f4 100644 --- a/services/continuous_task/include/system_event_observer.h +++ b/services/continuous_task/include/system_event_observer.h @@ -27,7 +27,7 @@ class BgContinuousTaskMgr; class SystemEventObserver : public EventFwk::CommonEventSubscriber, public std::enable_shared_from_this { public: - SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo); + explicit SystemEventObserver(const EventFwk::CommonEventSubscribeInfo &subscribeInfo); ~SystemEventObserver() = default; void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; void SetEventHandler(const std::shared_ptr &handler); @@ -39,6 +39,6 @@ private: std::weak_ptr handler_; std::weak_ptr bgContinuousTaskMgr_; }; -} -} -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_SYSTEM_EVENT_OBSERVER_H \ No newline at end of file diff --git a/services/continuous_task/include/task_notification_subscriber.h b/services/continuous_task/include/task_notification_subscriber.h index 54591ecc..f0532e5c 100644 --- a/services/continuous_task/include/task_notification_subscriber.h +++ b/services/continuous_task/include/task_notification_subscriber.h @@ -26,19 +26,19 @@ class TaskNotificationSubscriber : public Notification::NotificationSubscriber { public: TaskNotificationSubscriber(); virtual ~TaskNotificationSubscriber(); - virtual void OnConnected() override; - virtual void OnDisconnected() override; - virtual void OnCanceled(const std::shared_ptr &request) override; - virtual void OnCanceled(const std::shared_ptr &request, + void OnConnected() override; + void OnDisconnected() override; + void OnCanceled(const std::shared_ptr &request) override; + void OnCanceled(const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) override; - virtual void OnConsumed(const std::shared_ptr &request) override; - virtual void OnConsumed(const std::shared_ptr &request, + void OnConsumed(const std::shared_ptr &request) override; + void OnConsumed(const std::shared_ptr &request, const std::shared_ptr &sortingMap) override; - virtual void OnUpdate(const std::shared_ptr &sortingMap) override; - virtual void OnDied() override; - virtual void OnDoNotDisturbDateChange( + void OnUpdate(const std::shared_ptr &sortingMap) override; + void OnDied() override; + void OnDoNotDisturbDateChange( const std::shared_ptr &date) override; - virtual void OnEnabledNotificationChanged( + void OnEnabledNotificationChanged( const std::shared_ptr &callbackData) override; private: @@ -49,4 +49,4 @@ private: }; } // namespace BackgroundTaskMgr } // namespace OHOS -#endif \ No newline at end of file +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_SERVICES_CONTINUOUS_TASK_INCLUDE_NOTIFICATION_SUBSCRIBER_H \ No newline at end of file diff --git a/services/continuous_task/src/app_state_observer.cpp b/services/continuous_task/src/app_state_observer.cpp index dff74a48..0f5e7906 100644 --- a/services/continuous_task/src/app_state_observer.cpp +++ b/services/continuous_task/src/app_state_observer.cpp @@ -155,5 +155,5 @@ void AppStateObserver::OnRemoteDied(const wptr &object) std::lock_guard lock(mutex_); Disconnect(); } -} -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/continuous_task/src/bg_continuous_task_mgr.cpp b/services/continuous_task/src/bg_continuous_task_mgr.cpp index 63719507..268ca24b 100644 --- a/services/continuous_task/src/bg_continuous_task_mgr.cpp +++ b/services/continuous_task/src/bg_continuous_task_mgr.cpp @@ -1008,5 +1008,5 @@ int32_t BgContinuousTaskMgr::RefreshTaskRecord() } return ERR_OK; } -} -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/continuous_task/src/bundle_manager_helper.cpp b/services/continuous_task/src/bundle_manager_helper.cpp index 3c0e8aa0..33ec5c20 100644 --- a/services/continuous_task/src/bundle_manager_helper.cpp +++ b/services/continuous_task/src/bundle_manager_helper.cpp @@ -128,5 +128,5 @@ void BundleManagerHelper::OnRemoteDied(const wptr &object) std::lock_guard lock(connectionMutex_); Disconnect(); } -} -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/continuous_task/src/continuous_task_record.cpp b/services/continuous_task/src/continuous_task_record.cpp index cdc51d5c..994ddeac 100644 --- a/services/continuous_task/src/continuous_task_record.cpp +++ b/services/continuous_task/src/continuous_task_record.cpp @@ -137,5 +137,5 @@ bool ContinuousTaskRecord::ParseFromJson(const Json::Value value) } return true; } -} -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp index 6fa84c3f..e737f7e8 100644 --- a/services/continuous_task/src/system_event_observer.cpp +++ b/services/continuous_task/src/system_event_observer.cpp @@ -96,5 +96,5 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &eventD auto task = [=]() { bgContinuousTaskMgr->OnBundleInfoChanged(action, bundleName, uid); }; handler->PostTask(task, TASK_ON_BUNDLEINFO_CHANGED); } -} -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/continuous_task/src/task_notification_subscriber.cpp b/services/continuous_task/src/task_notification_subscriber.cpp index d20bd5b0..deb0aec3 100644 --- a/services/continuous_task/src/task_notification_subscriber.cpp +++ b/services/continuous_task/src/task_notification_subscriber.cpp @@ -72,7 +72,7 @@ void TaskNotificationSubscriber::OnCanceled(const std::shared_ptr + void OnContinuousTaskStart(const std::shared_ptr &continuousTaskCallbackInfo) override {} - virtual void OnContinuousTaskStop(const std::shared_ptr + void OnContinuousTaskStop(const std::shared_ptr &continuousTaskCallbackInfo) override {} }; @@ -182,5 +182,5 @@ HWTEST_F(BgContinuousTaskMgrTest, UnsubscribeContinuousTask_001, TestSize.Level1 SleepForFC(); EXPECT_EQ((int)bgContinuousTaskMgr_->RemoveSubscriber(subscriber->GetImpl()), (int)ERR_OK); } -} -} +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/test/unittest/bg_transient_task_mgr_test.cpp b/services/test/unittest/bg_transient_task_mgr_test.cpp index 188d9e05..98d0b3e1 100644 --- a/services/test/unittest/bg_transient_task_mgr_test.cpp +++ b/services/test/unittest/bg_transient_task_mgr_test.cpp @@ -33,10 +33,10 @@ public: class BgTransientTaskMgrTest : public testing::Test { public: - static void SetUpTestCase() {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() {} }; /** diff --git a/services/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/test/unittest/mock/mock_bundle_manager_helper.cpp index 32a25e1d..b140d075 100644 --- a/services/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -64,5 +64,5 @@ bool BundleManagerHelper::Connect() void BundleManagerHelper::Disconnect() {} void BundleManagerHelper::OnRemoteDied(const wptr &object) {} -} -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/services/test/unittest/mock/mock_resource_manager.cpp b/services/test/unittest/mock/mock_resource_manager.cpp index 7b92c5a7..201a0eac 100644 --- a/services/test/unittest/mock/mock_resource_manager.cpp +++ b/services/test/unittest/mock/mock_resource_manager.cpp @@ -213,6 +213,6 @@ RState ResourceManagerImpl::CloseRawFileDescriptor(const std::string &name) { return SUCCESS; } -} -} -} \ No newline at end of file +} // namespace Resource +} // namespace Global +} // namespace OHOS \ No newline at end of file diff --git a/services/transient_task/include/bg_transient_task_mgr.h b/services/transient_task/include/bg_transient_task_mgr.h index fcbd7c1e..61120345 100644 --- a/services/transient_task/include/bg_transient_task_mgr.h +++ b/services/transient_task/include/bg_transient_task_mgr.h @@ -50,6 +50,7 @@ enum class TransientTaskEventType: uint32_t { }; class BgTransientTaskMgr { DECLARE_DELAYED_SINGLETON(BgTransientTaskMgr); + public: void Init(); ErrCode RequestSuspendDelay(const std::u16string& reason, diff --git a/services/transient_task/include/decision_maker.h b/services/transient_task/include/decision_maker.h index 4a7fd28e..6552ff1d 100644 --- a/services/transient_task/include/decision_maker.h +++ b/services/transient_task/include/decision_maker.h @@ -53,8 +53,8 @@ public: private: class ApplicationStateObserver : public AppExecFwk::ApplicationStateObserverStub { public: - ApplicationStateObserver(DecisionMaker &decisionMaker) : decisionMaker_(decisionMaker) {} - ~ApplicationStateObserver() {}; + explicit ApplicationStateObserver(DecisionMaker &decisionMaker) : decisionMaker_(decisionMaker) {} + ~ApplicationStateObserver() {} void OnForegroundApplicationChanged(const AppExecFwk::AppStateData &appStateData) override; void OnAbilityStateChanged(const AppExecFwk::AbilityStateData &abilityStateData) override {} @@ -72,11 +72,11 @@ private: private: class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient { public: - AppMgrDeathRecipient(DecisionMaker &decisionMaker) : decisionMaker_(decisionMaker) {} + explicit AppMgrDeathRecipient(DecisionMaker &decisionMaker) : decisionMaker_(decisionMaker) {} - ~AppMgrDeathRecipient() {}; + ~AppMgrDeathRecipient() {} - virtual void OnRemoteDied(const wptr &object) override; + void OnRemoteDied(const wptr &object) override; private: DecisionMaker &decisionMaker_; diff --git a/services/transient_task/include/event_info.h b/services/transient_task/include/event_info.h index 434d8f18..2abec37f 100644 --- a/services/transient_task/include/event_info.h +++ b/services/transient_task/include/event_info.h @@ -85,6 +85,7 @@ public: ret += "]"; return ret; } + private: int32_t eventId_ {0}; std::vector intArgs_; diff --git a/services/transient_task/include/timer_manager.h b/services/transient_task/include/timer_manager.h index 78e02dec..f2dad8cc 100644 --- a/services/transient_task/include/timer_manager.h +++ b/services/transient_task/include/timer_manager.h @@ -26,7 +26,7 @@ class BackgroundTaskMgrService; class TimerManager : public AppExecFwk::EventHandler { public: - TimerManager(const wptr& service); + explicit TimerManager(const wptr& service); ~TimerManager() override = default; bool AddTimer(int32_t requestId, int32_t interval); void RemoveTimer(int32_t requestId); diff --git a/services/transient_task/src/bg_transient_task_mgr.cpp b/services/transient_task/src/bg_transient_task_mgr.cpp index 5a9045f1..13f21372 100644 --- a/services/transient_task/src/bg_transient_task_mgr.cpp +++ b/services/transient_task/src/bg_transient_task_mgr.cpp @@ -532,7 +532,7 @@ void BgTransientTaskMgr::SendScreenOnEvent(std::vector &dumpInfo) data.SetWant(want); EventFwk::CommonEventPublishInfo publishInfo; publishInfo.SetOrdered(true); - + data.SetCode(0); data.SetData("dump"); if (EventFwk::CommonEventManager::PublishCommonEvent(data, publishInfo)) { @@ -550,7 +550,7 @@ void BgTransientTaskMgr::SendScreenOffEvent(std::vector &dumpInfo) data.SetWant(want); EventFwk::CommonEventPublishInfo publishInfo; publishInfo.SetOrdered(true); - + data.SetCode(0); data.SetData("dump"); if (EventFwk::CommonEventManager::PublishCommonEvent(data, publishInfo)) { @@ -568,7 +568,7 @@ void BgTransientTaskMgr::SendLowBatteryEvent(std::vector &dumpInfo) data.SetWant(want); EventFwk::CommonEventPublishInfo publishInfo; publishInfo.SetOrdered(true); - + data.SetCode(0); data.SetData("dump"); if (EventFwk::CommonEventManager::PublishCommonEvent(data, publishInfo)) { @@ -586,7 +586,7 @@ void BgTransientTaskMgr::SendOkayBatteryEvent(std::vector &dumpInfo data.SetWant(want); EventFwk::CommonEventPublishInfo publishInfo; publishInfo.SetOrdered(true); - + data.SetCode(0); data.SetData("dump"); if (EventFwk::CommonEventManager::PublishCommonEvent(data, publishInfo)) { diff --git a/services/transient_task/src/device_info_manager.cpp b/services/transient_task/src/device_info_manager.cpp index e9426f1b..77a31730 100644 --- a/services/transient_task/src/device_info_manager.cpp +++ b/services/transient_task/src/device_info_manager.cpp @@ -29,7 +29,7 @@ void DeviceInfoManager::OnInputEvent(const EventInfo& eventInfo) return; } } - + switch (eventInfo.GetEventId()) { case EVENT_SCREEN_ON: isScreenOn_ = true; diff --git a/utils/bgtask_observer/include/bgtask_observer.h b/utils/bgtask_observer/include/bgtask_observer.h index 79eccba1..0b1e0160 100644 --- a/utils/bgtask_observer/include/bgtask_observer.h +++ b/utils/bgtask_observer/include/bgtask_observer.h @@ -24,16 +24,16 @@ namespace OHOS { namespace BackgroundTaskMgr { class BgTaskObserver : public OHOS::BackgroundTaskMgr::BackgroundTaskSubscriber { public: - virtual void OnContinuousTaskStart(const std::shared_ptr + void OnContinuousTaskStart(const std::shared_ptr &continuousTaskCallbackInfo) override; - virtual void OnContinuousTaskStop(const std::shared_ptr + void OnContinuousTaskStop(const std::shared_ptr &continuousTaskCallbackInfo) override; - virtual void OnRemoteDied(const wptr &object) override; + void OnRemoteDied(const wptr &object) override; std::atomic isRemoteDied_ {false}; }; -} -} -#endif \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_BACKGROUND_TASK_MGR_UTILS_BGTASK_OBSERVER_INCLUDE_BGTASK_OBSERVER_H \ No newline at end of file diff --git a/utils/bgtask_observer/src/bgtask_observer.cpp b/utils/bgtask_observer/src/bgtask_observer.cpp index 91cfc8f6..a8045c86 100644 --- a/utils/bgtask_observer/src/bgtask_observer.cpp +++ b/utils/bgtask_observer/src/bgtask_observer.cpp @@ -66,5 +66,5 @@ void BgTaskObserver::OnRemoteDied(const wptr &object) BGTASK_LOGW("remote service died"); isRemoteDied_.store(true); } -} -} \ No newline at end of file +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/utils/dump/include/shell_command.h b/utils/dump/include/shell_command.h index 203b1c67..2f86169f 100644 --- a/utils/dump/include/shell_command.h +++ b/utils/dump/include/shell_command.h @@ -25,12 +25,6 @@ namespace OHOS { namespace BackgroundTaskMgr { -namespace { -const std::string HELP_MSG_NO_OPTION = "error: you must specify an option at least."; - -const int OFFSET_REQUIRED_ARGUMENT = 2; -} // namespace - class ShellCommand { public: ShellCommand(int argc, char *argv[], std::string name); diff --git a/utils/dump/src/bgtaskmgr_shell_command.cpp b/utils/dump/src/bgtaskmgr_shell_command.cpp index ea908c7c..ab22b255 100644 --- a/utils/dump/src/bgtaskmgr_shell_command.cpp +++ b/utils/dump/src/bgtaskmgr_shell_command.cpp @@ -129,7 +129,7 @@ ErrCode BgtaskmgrShellCommand::RunAsDumpCommand() resultReceiver_.append(DUMP_HELP_MSG); break; } - + for (auto info : infos) { resultReceiver_.append(info); } -- Gitee From a221a7f4c5999c38fdc0de129bdabfb8dec51bae Mon Sep 17 00:00:00 2001 From: wangqing Date: Wed, 23 Mar 2022 09:16:30 +0800 Subject: [PATCH 75/77] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangqing --- services/transient_task/include/key_info.h | 3 +++ services/transient_task/src/bg_transient_task_mgr.cpp | 2 +- services/transient_task/src/suspend_controller.cpp | 8 ++++++++ utils/bgtask_observer/src/bgtask_observer.cpp | 6 ++++++ 4 files changed, 18 insertions(+), 1 deletion(-) diff --git a/services/transient_task/include/key_info.h b/services/transient_task/include/key_info.h index 8df78694..8fc707ee 100644 --- a/services/transient_task/include/key_info.h +++ b/services/transient_task/include/key_info.h @@ -69,6 +69,9 @@ private: struct KeyInfoComp { bool operator()(const std::shared_ptr x, const std::shared_ptr y) const { + if (x == nullptr || y == nullptr) { + return false + } return (x->GetPkg() < y->GetPkg()) || ((x->GetPkg() == y->GetPkg()) && (x->GetUid() < y->GetUid())); } }; diff --git a/services/transient_task/src/bg_transient_task_mgr.cpp b/services/transient_task/src/bg_transient_task_mgr.cpp index 13f21372..3f1ea6c0 100644 --- a/services/transient_task/src/bg_transient_task_mgr.cpp +++ b/services/transient_task/src/bg_transient_task_mgr.cpp @@ -446,7 +446,7 @@ ErrCode BgTransientTaskMgr::SubscribeBackgroundTask(const sptr& key) { + if (key == nullptr) { + return false + } + // do delayed suspend BGTASK_LOGI("Add delayed suspend app uid: %{public}d, name: %{public}s", key->GetUid(), key->GetPkg().c_str()); } void SuspendController::CancelSuspendDelay(const std::shared_ptr& key) { + if (key == nullptr) { + return false + } + // cancel delayed suspend BGTASK_LOGI("Remove delayed suspend app uid: %{public}d, name: %{public}s", key->GetUid(), key->GetPkg().c_str()); } diff --git a/utils/bgtask_observer/src/bgtask_observer.cpp b/utils/bgtask_observer/src/bgtask_observer.cpp index a8045c86..c480d942 100644 --- a/utils/bgtask_observer/src/bgtask_observer.cpp +++ b/utils/bgtask_observer/src/bgtask_observer.cpp @@ -25,6 +25,9 @@ void BgTaskObserver::OnContinuousTaskStart(const std::shared_ptr &continuousTaskCallbackInfo) { BGTASK_LOGI("Continuous Task Start"); + if (continuousTaskCallbackInfo == nullptr) { + return false + } std::stringstream stream; int32_t typeId = continuousTaskCallbackInfo->GetTypeId(); int32_t uid = continuousTaskCallbackInfo->GetCreatorUid(); @@ -45,6 +48,9 @@ void BgTaskObserver::OnContinuousTaskStop(const std::shared_ptr &continuousTaskCallbackInfo) { BGTASK_LOGI("Continuous Task Stop"); + if (continuousTaskCallbackInfo == nullptr) { + return false + } std::stringstream stream; int32_t typeId = continuousTaskCallbackInfo->GetTypeId(); int32_t uid = continuousTaskCallbackInfo->GetCreatorUid(); -- Gitee From f2d4eb9865ba2dca0f745591561f307900aec42b Mon Sep 17 00:00:00 2001 From: wangqing Date: Wed, 23 Mar 2022 10:39:41 +0800 Subject: [PATCH 76/77] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangqing --- services/test/unittest/bg_continuous_task_mgr_test.cpp | 4 ++-- services/transient_task/include/key_info.h | 2 +- services/transient_task/src/suspend_controller.cpp | 6 +++--- utils/bgtask_observer/src/bgtask_observer.cpp | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/services/test/unittest/bg_continuous_task_mgr_test.cpp b/services/test/unittest/bg_continuous_task_mgr_test.cpp index e9cc2e08..c926c497 100644 --- a/services/test/unittest/bg_continuous_task_mgr_test.cpp +++ b/services/test/unittest/bg_continuous_task_mgr_test.cpp @@ -129,7 +129,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StartBackgroundRunning_002, TestSize.Level1) /** * @tc.name: StopBackgroundRunning_001 - * @tc.desc: start background runnging use new api test. + * @tc.desc: stop background runnging test. * @tc.type: FUNC * @tc.require: SR000GGT7V AR000GH6ES AR000GH6EM AR000GH6G9 AR000GH56K */ @@ -150,7 +150,7 @@ HWTEST_F(BgContinuousTaskMgrTest, StopBackgroundRunning_001, TestSize.Level1) } /** - * @tc.name: StartBackgroundRunning_001 + * @tc.name: SubscribeContinuousTask_001 * @tc.desc: subscribe continuous task event callback test. * @tc.type: FUNC * @tc.require: SR000GGT81 AR000GH6EM AR000GH6G9 AR000GH6ET diff --git a/services/transient_task/include/key_info.h b/services/transient_task/include/key_info.h index 8fc707ee..21ba6bec 100644 --- a/services/transient_task/include/key_info.h +++ b/services/transient_task/include/key_info.h @@ -70,7 +70,7 @@ struct KeyInfoComp { bool operator()(const std::shared_ptr x, const std::shared_ptr y) const { if (x == nullptr || y == nullptr) { - return false + return false; } return (x->GetPkg() < y->GetPkg()) || ((x->GetPkg() == y->GetPkg()) && (x->GetUid() < y->GetUid())); } diff --git a/services/transient_task/src/suspend_controller.cpp b/services/transient_task/src/suspend_controller.cpp index f135bb13..13939184 100644 --- a/services/transient_task/src/suspend_controller.cpp +++ b/services/transient_task/src/suspend_controller.cpp @@ -24,7 +24,7 @@ namespace BackgroundTaskMgr { void SuspendController::RequestSuspendDelay(const std::shared_ptr& key) { if (key == nullptr) { - return false + return; } // do delayed suspend @@ -34,9 +34,9 @@ void SuspendController::RequestSuspendDelay(const std::shared_ptr& key) void SuspendController::CancelSuspendDelay(const std::shared_ptr& key) { if (key == nullptr) { - return false + return; } - + // cancel delayed suspend BGTASK_LOGI("Remove delayed suspend app uid: %{public}d, name: %{public}s", key->GetUid(), key->GetPkg().c_str()); } diff --git a/utils/bgtask_observer/src/bgtask_observer.cpp b/utils/bgtask_observer/src/bgtask_observer.cpp index c480d942..d1f94c9f 100644 --- a/utils/bgtask_observer/src/bgtask_observer.cpp +++ b/utils/bgtask_observer/src/bgtask_observer.cpp @@ -26,7 +26,7 @@ void BgTaskObserver::OnContinuousTaskStart(const std::shared_ptrGetTypeId(); @@ -49,7 +49,7 @@ void BgTaskObserver::OnContinuousTaskStop(const std::shared_ptrGetTypeId(); -- Gitee From bb6e8f94d91b4f0735e52fb7ec7d1731911dc72b Mon Sep 17 00:00:00 2001 From: wangqing Date: Wed, 23 Mar 2022 17:53:00 +0800 Subject: [PATCH 77/77] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangqing --- services/continuous_task/src/system_event_observer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/continuous_task/src/system_event_observer.cpp b/services/continuous_task/src/system_event_observer.cpp index e737f7e8..8be84e5d 100644 --- a/services/continuous_task/src/system_event_observer.cpp +++ b/services/continuous_task/src/system_event_observer.cpp @@ -36,7 +36,7 @@ bool SystemEventObserver::Subscribe() { BGTASK_LOGI("Subscribe called"); - if (EventFwk::CommonEventManager::SubscribeCommonEvent(shared_from_this()) != true) { + if (!EventFwk::CommonEventManager::SubscribeCommonEvent(shared_from_this())) { BGTASK_LOGI("SubscribeCommonEvent occur exception."); return false; } @@ -46,7 +46,7 @@ bool SystemEventObserver::Subscribe() bool SystemEventObserver::Unsubscribe() { BGTASK_LOGI("UnSubscribe called"); - if (EventFwk::CommonEventManager::UnSubscribeCommonEvent(shared_from_this()) != true) { + if (!EventFwk::CommonEventManager::UnSubscribeCommonEvent(shared_from_this())) { BGTASK_LOGI("UnsubscribeCommonEvent occur exception."); return false; } -- Gitee