1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "ability.h"
17
18 #include <cinttypes>
19 #include <thread>
20
21 #include "ability_impl.h"
22 #include "ability_loader.h"
23 #include "ability_post_event_timeout.h"
24 #include "ability_runtime/js_ability.h"
25 #include "abs_shared_result_set.h"
26 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
27 #include "background_task_mgr_helper.h"
28 #endif
29 #include "bytrace.h"
30 #include "configuration_convertor.h"
31 #include "connection_manager.h"
32 #include "context_impl.h"
33 #include "continuation_manager.h"
34 #include "continuation_register_manager.h"
35 #include "continuation_register_manager_proxy.h"
36 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
37 #include "continuous_task_param.h"
38 #endif
39 #include "data_ability_operation.h"
40 #include "data_ability_predicates.h"
41 #include "data_ability_result.h"
42 #include "data_uri_utils.h"
43 #include "distributed_objectstore.h"
44 #include "hilog_wrapper.h"
45 #ifdef SUPPORT_GRAPHICS
46 #include "display_type.h"
47 #include "form_host_client.h"
48 #include "form_mgr.h"
49 #include "form_provider_client.h"
50 #endif
51 #include "if_system_ability_manager.h"
52 #include "ipc_skeleton.h"
53 #include "iservice_registry.h"
54 #ifdef SUPPORT_GRAPHICS
55 #include "key_event.h"
56 #endif
57 #include "ohos_application.h"
58 #include "permission/permission.h"
59 #include "permission/permission_kit.h"
60 #include "reverse_continuation_scheduler_primary.h"
61 #include "reverse_continuation_scheduler_replica.h"
62 #include "reverse_continuation_scheduler_replica_handler_interface.h"
63 #include "runtime.h"
64 #include "string_wrapper.h"
65 #include "system_ability_definition.h"
66 #include "task_handler_client.h"
67 #include "values_bucket.h"
68
69 namespace OHOS {
70 namespace AppExecFwk {
71 using PermissionKit = OHOS::Security::Permission::PermissionKit;
72 using PermissionState = OHOS::Security::Permission::PermissionState;
73
74 // REGISTER_AA(Ability)
75 const std::string Ability::SYSTEM_UI("com.ohos.systemui");
76 const std::string Ability::STATUS_BAR("com.ohos.systemui.statusbar.MainAbility");
77 const std::string Ability::NAVIGATION_BAR("com.ohos.systemui.navigationbar.MainAbility");
78 const std::string Ability::KEYGUARD("com.ohos.screenlock");
79 const std::string DEVICE_MANAGER_BUNDLE_NAME = "com.ohos.devicemanagerui";
80 const std::string DEVICE_MANAGER_NAME = "com.ohos.devicemanagerui.MainAbility";
81 const std::string Ability::DMS_SESSION_ID("sessionId");
82 const std::string Ability::DMS_ORIGIN_DEVICE_ID("deviceId");
83 const int Ability::DEFAULT_DMS_SESSION_ID(0);
84 const std::string PERMISSION_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM";
85 const std::string LAUNCHER_BUNDLE_NAME = "com.ohos.launcher";
86 const std::string LAUNCHER_ABILITY_NAME = "com.ohos.launcher.MainAbility";
87 const std::string SHOW_ON_LOCK_SCREEN = "ShowOnLockScreen";
88
89 #ifdef SUPPORT_GRAPHICS
90 static std::mutex formLock;
91
92 constexpr int64_t SEC_TO_MILLISEC = 1000;
93 constexpr int64_t MILLISEC_TO_NANOSEC = 1000000;
94 #endif
95 #ifdef DISTRIBUTED_DATA_OBJECT_ENABLE
96 constexpr int32_t DISTRIBUTED_OBJECT_TIMEOUT = 10000;
97 #endif
98
Create(const std::unique_ptr<AbilityRuntime::Runtime> & runtime)99 Ability* Ability::Create(const std::unique_ptr<AbilityRuntime::Runtime>& runtime)
100 {
101 if (!runtime) {
102 return new Ability;
103 }
104
105 switch (runtime->GetLanguage()) {
106 case AbilityRuntime::Runtime::Language::JS:
107 return AbilityRuntime::JsAbility::Create(runtime);
108
109 default:
110 return new Ability();
111 }
112 }
113
Init(const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<OHOSApplication> & application,std::shared_ptr<AbilityHandler> & handler,const sptr<IRemoteObject> & token)114 void Ability::Init(const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<OHOSApplication> &application,
115 std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token)
116 {
117 HILOG_INFO("%{public}s begin.", __func__);
118 abilityInfo_ = abilityInfo;
119 handler_ = handler;
120 AbilityContext::token_ = token;
121
122 #ifdef SUPPORT_GRAPHICS
123 // page ability only.
124 if (abilityInfo_->type == AbilityType::PAGE) {
125 if (!abilityInfo_->isStageBasedModel) {
126 abilityWindow_ = std::make_shared<AbilityWindow>();
127 if (abilityWindow_ != nullptr) {
128 HILOG_INFO("%{public}s begin abilityWindow_->Init", __func__);
129 abilityWindow_->Init(handler_, shared_from_this());
130 HILOG_INFO("%{public}s end abilityWindow_->Init", __func__);
131 }
132 }
133 continuationManager_ = std::make_shared<ContinuationManager>();
134 std::weak_ptr<Ability> ability = shared_from_this();
135 std::weak_ptr<ContinuationManager> continuationManager = continuationManager_;
136 continuationHandler_ = std::make_shared<ContinuationHandler>(continuationManager, ability);
137 if (!continuationManager_->Init(shared_from_this(), GetToken(), GetAbilityInfo(), continuationHandler_)) {
138 continuationManager_.reset();
139 } else {
140 std::weak_ptr<ContinuationHandler> continuationHandler = continuationHandler_;
141 sptr<ReverseContinuationSchedulerPrimary> Primary = sptr<ReverseContinuationSchedulerPrimary>(
142 new (std::nothrow) ReverseContinuationSchedulerPrimary(continuationHandler, handler_));
143 if (Primary == nullptr) {
144 HILOG_ERROR("Ability::Init failed,Primary create failed");
145 } else {
146 continuationHandler_->SetPrimaryStub(Primary);
147 continuationHandler_->SetAbilityInfo(abilityInfo_);
148 }
149 }
150
151 // register displayid change callback
152 HILOG_INFO("Ability::Init call RegisterDisplayListener");
153 OHOS::sptr<OHOS::Rosen::DisplayManager::IDisplayListener> thisAbility(this);
154 Rosen::DisplayManager::GetInstance().RegisterDisplayListener(thisAbility);
155 }
156 #endif
157 lifecycle_ = std::make_shared<LifeCycle>();
158 abilityLifecycleExecutor_ = std::make_shared<AbilityLifecycleExecutor>();
159 if (abilityLifecycleExecutor_ != nullptr) {
160 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INITIAL);
161 } else {
162 HILOG_ERROR("%{public}s abilityLifecycleExecutor_ make failed.", __func__);
163 }
164
165 application_ = application;
166 if (abilityContext_ != nullptr) {
167 abilityContext_->RegisterAbilityCallback(weak_from_this());
168 }
169 HILOG_INFO("%{public}s end.", __func__);
170 }
171
AttachAbilityContext(const std::shared_ptr<AbilityRuntime::AbilityContext> & abilityContext)172 void Ability::AttachAbilityContext(const std::shared_ptr<AbilityRuntime::AbilityContext> &abilityContext)
173 {
174 abilityContext_ = abilityContext;
175 }
176
177 /**
178 * @brief Obtains a resource manager.
179 *
180 * @return Returns a ResourceManager object.
181 */
GetResourceManager() const182 std::shared_ptr<Global::Resource::ResourceManager> Ability::GetResourceManager() const
183 {
184 return AbilityContext::GetResourceManager();
185 }
186
187 /**
188 * @brief Checks whether the configuration of this ability is changing.
189 *
190 * @return Returns true if the configuration of this ability is changing and false otherwise.
191 */
IsUpdatingConfigurations()192 bool Ability::IsUpdatingConfigurations()
193 {
194 return AbilityContext::IsUpdatingConfigurations();
195 }
196
197 #ifdef SUPPORT_GRAPHICS
198 /**
199 * @brief Informs the system of the time required for drawing this Page ability.
200 *
201 * @return Returns the notification is successful or fail
202 */
PrintDrawnCompleted()203 bool Ability::PrintDrawnCompleted()
204 {
205 return AbilityContext::PrintDrawnCompleted();
206 }
207 #endif
208
209 /**
210 * Will be called when ability start. You should override this function
211 *
212 * @param want ability start information
213 */
OnStart(const Want & want)214 void Ability::OnStart(const Want &want)
215 {
216 BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
217 HILOG_INFO("%{public}s begin.", __func__);
218 if (abilityInfo_ == nullptr) {
219 HILOG_ERROR("Ability::OnStart failed abilityInfo_ is nullptr.");
220 return;
221 }
222
223 #ifdef SUPPORT_GRAPHICS
224 if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
225 Rosen::WindowType winType = Rosen::WindowType::WINDOW_TYPE_APP_MAIN_WINDOW;
226 if (abilityInfo_->bundleName == SYSTEM_UI) {
227 if (abilityInfo_->name == STATUS_BAR) {
228 winType = Rosen::WindowType::WINDOW_TYPE_STATUS_BAR;
229 }
230 if (abilityInfo_->name == NAVIGATION_BAR) {
231 winType = Rosen::WindowType::WINDOW_TYPE_NAVIGATION_BAR;
232 }
233 }
234 if (abilityInfo_->bundleName == OHOS_REQUEST_PERMISSION_BUNDLENAME &&
235 abilityInfo_->name == OHOS_REQUEST_PERMISSION_ABILITY_NAME) {
236 winType = Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW;
237 }
238
239 if (abilityInfo_->bundleName == KEYGUARD) {
240 winType = Rosen::WindowType::WINDOW_TYPE_DRAGGING_EFFECT;
241 }
242
243 if (abilityInfo_->bundleName == DEVICE_MANAGER_BUNDLE_NAME && abilityInfo_->name == DEVICE_MANAGER_NAME) {
244 winType = Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW;
245 }
246
247 if (abilityInfo_->bundleName == LAUNCHER_BUNDLE_NAME && abilityInfo_->name == LAUNCHER_ABILITY_NAME) {
248 winType = Rosen::WindowType::WINDOW_TYPE_DESKTOP;
249 }
250
251 int defualtDisplayId = Rosen::WindowScene::DEFAULT_DISPLAY_ID;
252 int displayId = want.GetIntParam(Want::PARAM_RESV_DISPLAY_ID, defualtDisplayId);
253 HILOG_INFO("Ability::OnStart bundleName:%{public}s, abilityName:%{public}s, windowType:%{public}d, "
254 "displayId:%{public}d",
255 abilityInfo_->bundleName.c_str(),
256 abilityInfo_->name.c_str(),
257 winType,
258 displayId);
259 auto option = GetWindowOption(want);
260 InitWindow(winType, displayId, option);
261
262 if (abilityWindow_ != nullptr) {
263 HILOG_INFO("%{public}s begin abilityWindow_->OnPostAbilityStart.", __func__);
264 abilityWindow_->OnPostAbilityStart();
265 auto window = abilityWindow_->GetWindow();
266 if (window) {
267 auto windowId = window->GetWindowId();
268 HILOG_INFO("Ability::OnStart: add windowId = %{public}d", windowId);
269 OHOS::AAFwk::AbilityManagerClient::GetInstance()->AddWindowInfo(AbilityContext::GetToken(), windowId);
270
271 if (winType == Rosen::WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
272 HILOG_INFO("Call RegisterDisplayMoveListener, windowId: %{public}d", windowId);
273 OHOS::sptr<OHOS::Rosen::IDisplayMoveListener> displayMoveListener(this);
274 window->RegisterDisplayMoveListener(displayMoveListener);
275 }
276 }
277 HILOG_INFO("%{public}s end abilityWindow_->OnPostAbilityStart.", __func__);
278 }
279
280 // Update resMgr, Configuration
281 HILOG_INFO("%{public}s get display by displayId %{public}d.", __func__, displayId);
282 auto display = Rosen::DisplayManager::GetInstance().GetDisplayById(displayId);
283 if (display) {
284 float density = display->GetVirtualPixelRatio();
285 int32_t width = display->GetWidth();
286 int32_t height = display->GetHeight();
287 auto configuration = application_->GetConfiguration();
288 if (configuration) {
289 std::string direction = GetDirectionStr(height, width);
290 configuration->AddItem(displayId, ConfigurationInner::APPLICATION_DIRECTION, direction);
291 configuration->AddItem(displayId, ConfigurationInner::APPLICATION_DENSITYDPI, GetDensityStr(density));
292 configuration->AddItem(ConfigurationInner::APPLICATION_DISPLAYID, std::to_string(displayId));
293 UpdateContextConfiguration();
294 }
295
296 std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
297 if (resConfig == nullptr) {
298 HILOG_ERROR("%{public}s error, resConfig is nullptr.", __func__);
299 return;
300 }
301 auto resourceManager = GetResourceManager();
302 if (resourceManager != nullptr) {
303 resourceManager->GetResConfig(*resConfig);
304 resConfig->SetScreenDensity(ConvertDensity(density));
305 resConfig->SetDirection(ConvertDirection(height, width));
306 resourceManager->UpdateResConfig(*resConfig);
307 HILOG_INFO("%{public}s Notify ResourceManager, Density: %{public}d, Direction: %{public}d.", __func__,
308 resConfig->GetScreenDensity(), resConfig->GetDirection());
309 }
310 }
311 }
312 #endif
313
314 SetWant(want);
315 if (abilityLifecycleExecutor_ == nullptr) {
316 HILOG_ERROR("Ability::OnStart error. abilityLifecycleExecutor_ == nullptr.");
317 return;
318 }
319 if (!abilityInfo_->isStageBasedModel) {
320 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INACTIVE);
321 } else {
322 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::STARTED_NEW);
323 }
324
325 if (lifecycle_ == nullptr) {
326 HILOG_ERROR("Ability::OnStart error. lifecycle_ == nullptr.");
327 return;
328 }
329 lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_START, want);
330 HILOG_INFO("%{public}s end.", __func__);
331 }
332
333 /**
334 * @brief Called when this ability enters the <b>STATE_STOP</b> state.
335 *
336 * The ability in the <b>STATE_STOP</b> is being destroyed.
337 * You can override this function to implement your own processing logic.
338 */
OnStop()339 void Ability::OnStop()
340 {
341 BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
342 HILOG_INFO("%{public}s begin.", __func__);
343 #ifdef SUPPORT_GRAPHICS
344 // Call JS Func(onWindowStageDestroy) and Release the scene.
345 if (scene_ != nullptr) {
346 scene_->GoDestroy();
347 scene_ = nullptr;
348 onSceneDestroyed();
349 }
350 #endif
351 if (abilityLifecycleExecutor_ == nullptr) {
352 HILOG_ERROR("Ability::OnStop error. abilityLifecycleExecutor_ == nullptr.");
353 return;
354 }
355 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INITIAL);
356
357 if (lifecycle_ == nullptr) {
358 HILOG_ERROR("Ability::OnStop error. lifecycle_ == nullptr.");
359 return;
360 }
361 lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_STOP);
362 HILOG_INFO("%{public}s end.", __func__);
363 }
364
365 /**
366 * @brief Release the ability instance.
367 */
DestroyInstance()368 void Ability::DestroyInstance()
369 {
370 HILOG_INFO("%{public}s begin.", __func__);
371 #ifdef SUPPORT_GRAPHICS
372 // Release the window.
373 if (abilityWindow_ != nullptr && abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
374 abilityWindow_->OnPostAbilityStop(); // Ability instance will been released when window destroy.
375 }
376 #endif
377 HILOG_INFO("%{public}s end.", __func__);
378 }
379
380 /**
381 * @brief Called when this ability enters the <b>STATE_ACTIVE</b> state.
382 *
383 * The ability in the <b>STATE_ACTIVE</b> state is visible and has focus.
384 * You can override this function to implement your own processing logic.
385 *
386 * @param Want Indicates the {@link Want} structure containing activation information about the ability.
387 */
OnActive()388 void Ability::OnActive()
389 {
390 BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
391 HILOG_INFO("%{public}s begin.", __func__);
392 #ifdef SUPPORT_GRAPHICS
393 if (abilityWindow_ != nullptr) {
394 HILOG_INFO("%{public}s begin abilityWindow_->OnPostAbilityActive.", __func__);
395 abilityWindow_->OnPostAbilityActive();
396 HILOG_INFO("%{public}s end abilityWindow_->OnPostAbilityActive.", __func__);
397 }
398 bWindowFocus_ = true;
399 #endif
400 if (abilityLifecycleExecutor_ == nullptr) {
401 HILOG_ERROR("Ability::OnActive error. abilityLifecycleExecutor_ == nullptr.");
402 return;
403 }
404 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::ACTIVE);
405
406 if (lifecycle_ == nullptr) {
407 HILOG_ERROR("Ability::OnActive error. lifecycle_ == nullptr.");
408 return;
409 }
410 lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
411 HILOG_INFO("%{public}s end.", __func__);
412 }
413
414 /**
415 * @brief Called when this ability enters the <b>STATE_INACTIVE</b> state.
416 *
417 * <b>STATE_INACTIVE</b> is an instantaneous state. The ability in this state may be visible but does not have
418 * focus.You can override this function to implement your own processing logic.
419 */
OnInactive()420 void Ability::OnInactive()
421 {
422 BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
423 HILOG_INFO("%{public}s begin.", __func__);
424 #ifdef SUPPORT_GRAPHICS
425 if (abilityWindow_ != nullptr && abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
426 HILOG_INFO("%{public}s begin abilityWindow_->OnPostAbilityInactive.", __func__);
427 abilityWindow_->OnPostAbilityInactive();
428 HILOG_INFO("%{public}s end abilityWindow_->OnPostAbilityInactive.", __func__);
429 }
430 bWindowFocus_ = false;
431 #endif
432 if (abilityLifecycleExecutor_ == nullptr) {
433 HILOG_ERROR("Ability::OnInactive error. abilityLifecycleExecutor_ == nullptr.");
434 return;
435 }
436 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INACTIVE);
437
438 if (lifecycle_ == nullptr) {
439 HILOG_ERROR("Ability::OnInactive error. lifecycle_ == nullptr.");
440 return;
441 }
442 lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE);
443 HILOG_INFO("%{public}s end.", __func__);
444 }
445
446 #ifdef SUPPORT_GRAPHICS
447 /**
448 * @brief Called after instantiating WindowScene.
449 *
450 *
451 * You can override this function to implement your own processing logic.
452 */
OnSceneCreated()453 void Ability::OnSceneCreated()
454 {
455 HILOG_INFO("%{public}s called.", __func__);
456 }
457
458 /**
459 * @brief Called after restore WindowScene.
460 *
461 *
462 * You can override this function to implement your own processing logic.
463 */
OnSceneRestored()464 void Ability::OnSceneRestored()
465 {
466 HILOG_INFO("%{public}s called.", __func__);
467 }
468
469 /**
470 * @brief Called after ability stoped.
471 *
472 *
473 * You can override this function to implement your own processing logic.
474 */
onSceneDestroyed()475 void Ability::onSceneDestroyed()
476 {
477 HILOG_INFO("%{public}s called.", __func__);
478 }
479
480 /**
481 * @brief Called when this ability enters the <b>STATE_FOREGROUND</b> state.
482 *
483 *
484 * The ability in the <b>STATE_FOREGROUND</b> state is visible.
485 * You can override this function to implement your own processing logic.
486 */
OnForeground(const Want & want)487 void Ability::OnForeground(const Want &want)
488 {
489 BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
490 HILOG_INFO("%{public}s begin.", __func__);
491 DoOnForeground(want);
492 DispatchLifecycleOnForeground(want);
493 HILOG_INFO("%{public}s end.", __func__);
494 }
495 #endif
496
IsRestoredInContinuation() const497 bool Ability::IsRestoredInContinuation() const
498 {
499 if (abilityContext_ == nullptr) {
500 HILOG_ERROR("abilityContext_ is null");
501 return false;
502 }
503 if (launchParam_.launchReason == LaunchReason::LAUNCHREASON_CONTINUATION
504 && abilityInfo_->launchMode == LaunchMode::STANDARD
505 && abilityContext_->GetContentStorage() != nullptr) {
506 HILOG_INFO("Is Restored In Continuation");
507 return true;
508 }
509 HILOG_INFO("not Restored In Continuation");
510 return false;
511 }
512
WaitingDistributedObjectSyncComplete(const Want & want)513 void Ability::WaitingDistributedObjectSyncComplete(const Want& want)
514 {
515 #ifdef DISTRIBUTED_DATA_OBJECT_ENABLE
516 int sessionId = want.GetIntParam(DMS_SESSION_ID, DEFAULT_DMS_SESSION_ID);
517 std::string originDeviceId = want.GetStringParam(DMS_ORIGIN_DEVICE_ID);
518
519 HILOG_INFO("continuation WaitingDistributedObjectSyncComplete begin");
520 auto timeout = [self = shared_from_this(), sessionId, originDeviceId]() {
521 HILOG_INFO("DistributedObject sync timeout");
522 self->continuationManager_->NotifyCompleteContinuation(
523 originDeviceId, sessionId, false, nullptr);
524 };
525
526 // std::shared_ptr<AppExecFwk::EventHandler> handler = handler_;
527 auto callback = [self = shared_from_this(), sessionId, originDeviceId]() {
528 HILOG_INFO("DistributedObject sync complete");
529 if (self->handler_ != nullptr) {
530 self->handler_->RemoveTask("Waiting_Sync_Timeout");
531 }
532 self->continuationManager_->NotifyCompleteContinuation(
533 originDeviceId, sessionId, true, nullptr);
534 };
535
536 std::string &bundleName = abilityInfo_->bundleName;
537 HILOG_INFO("continuation TriggerRestore begin");
538 ObjectStore::DistributedObjectStore::GetInstance(bundleName)->TriggerRestore(callback);
539 HILOG_INFO("continuation TriggerRestore end");
540
541 if (handler_ != nullptr) {
542 HILOG_INFO("continuation set timeout begin");
543 handler_->PostTask(timeout, "Waiting_Sync_Timeout", DISTRIBUTED_OBJECT_TIMEOUT);
544 HILOG_INFO("continuation set timeout end");
545 }
546 #else
547 NotityContinuationResult(want, true);
548 #endif
549 }
550
NotityContinuationResult(const Want & want,bool success)551 void Ability::NotityContinuationResult(const Want& want, bool success)
552 {
553 HILOG_INFO("NotityContinuationResult begin");
554 std::weak_ptr<IReverseContinuationSchedulerReplicaHandler> ReplicaHandler = continuationHandler_;
555 reverseContinuationSchedulerReplica_ = sptr<ReverseContinuationSchedulerReplica>(
556 new (std::nothrow) ReverseContinuationSchedulerReplica(handler_, ReplicaHandler));
557
558 if (reverseContinuationSchedulerReplica_ == nullptr) {
559 HILOG_ERROR("Ability::NotityContinuationComplete failed, create reverseContinuationSchedulerReplica failed");
560 return;
561 }
562 int sessionId = want.GetIntParam(DMS_SESSION_ID, DEFAULT_DMS_SESSION_ID);
563 std::string originDeviceId = want.GetStringParam(DMS_ORIGIN_DEVICE_ID);
564 HILOG_INFO("Ability::NotityContinuationComplete DeviceId: %{public}s", originDeviceId.c_str());
565 continuationManager_->NotifyCompleteContinuation(
566 originDeviceId, sessionId, success, reverseContinuationSchedulerReplica_);
567 }
568
569 #ifdef SUPPORT_GRAPHICS
570 /**
571 * @brief Called when this ability enters the <b>STATE_BACKGROUND</b> state.
572 *
573 *
574 * The ability in the <b>STATE_BACKGROUND</b> state is invisible.
575 * You can override this function to implement your own processing logic.
576 */
OnBackground()577 void Ability::OnBackground()
578 {
579 BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
580 HILOG_INFO("%{public}s begin.", __func__);
581 if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
582 HILOG_INFO("%{public}s begin OnPostAbilityBackground.", __func__);
583 if (abilityInfo_->isStageBasedModel) {
584 if (scene_ == nullptr) {
585 HILOG_ERROR("Ability::OnBackground error. scene_ == nullptr.");
586 return;
587 }
588 HILOG_INFO("GoBackground sceneFlag:%{public}d.", sceneFlag_);
589 scene_->GoBackground(sceneFlag_);
590 } else {
591 if (abilityWindow_ == nullptr) {
592 HILOG_ERROR("Ability::OnBackground error. abilityWindow_ == nullptr.");
593 return;
594 }
595 HILOG_INFO("OnPostAbilityBackground sceneFlag:%{public}d.", sceneFlag_);
596 abilityWindow_->OnPostAbilityBackground(sceneFlag_);
597 }
598 HILOG_INFO("%{public}s end OnPostAbilityBackground.", __func__);
599 }
600
601 if (abilityLifecycleExecutor_ == nullptr) {
602 HILOG_ERROR("Ability::OnBackground error. abilityLifecycleExecutor_ == nullptr.");
603 return;
604 }
605
606 if (abilityInfo_->isStageBasedModel) {
607 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND_NEW);
608 } else {
609 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND);
610 }
611
612 if (lifecycle_ == nullptr) {
613 HILOG_ERROR("Ability::OnBackground error. lifecycle_ == nullptr.");
614 return;
615 }
616 lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND);
617 HILOG_INFO("%{public}s end.", __func__);
618 }
619 #endif
620
621 /**
622 * @brief Called when this Service ability is connected for the first time.
623 *
624 * You can override this function to implement your own processing logic.
625 *
626 * @param want Indicates the {@link Want} structure containing connection information about the Service ability.
627 * @return Returns a pointer to the <b>sid</b> of the connected Service ability.
628 */
OnConnect(const Want & want)629 sptr<IRemoteObject> Ability::OnConnect(const Want &want)
630 {
631 BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
632 HILOG_INFO("%{public}s begin.", __func__);
633 if (abilityLifecycleExecutor_ == nullptr) {
634 HILOG_ERROR("Ability::OnConnect error. abilityLifecycleExecutor_ == nullptr.");
635 return nullptr;
636 }
637 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::ACTIVE);
638
639 if (lifecycle_ == nullptr) {
640 HILOG_ERROR("Ability::OnConnect error. lifecycle_ == nullptr.");
641 return nullptr;
642 }
643 lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
644 HILOG_INFO("%{public}s end.", __func__);
645 return nullptr;
646 }
647
648 /**
649 * @brief Called when all abilities connected to this Service ability are disconnected.
650 *
651 * You can override this function to implement your own processing logic.
652 *
653 */
OnDisconnect(const Want & want)654 void Ability::OnDisconnect(const Want &want)
655 {
656 BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
657 }
658
659 /**
660 * Start other ability for result.
661 *
662 * @param want information of other ability
663 * @param requestCode request code for abilityMS to return result
664 *
665 * @return errCode ERR_OK on success, others on failure.
666 */
StartAbilityForResult(const Want & want,int requestCode)667 ErrCode Ability::StartAbilityForResult(const Want &want, int requestCode)
668 {
669 HILOG_INFO("%{public}s begin.", __func__);
670 if (abilityInfo_ == nullptr) {
671 HILOG_ERROR("Ability::StartAbilityForResult abilityInfo_ == nullptr");
672 return ERR_NULL_OBJECT;
673 }
674 HILOG_INFO("Ability::StartAbilityForResult called type = %{public}d", abilityInfo_->type);
675 if (abilityInfo_->type != AppExecFwk::AbilityType::PAGE) {
676 HILOG_ERROR("Ability::StartAbility ability type: %{public}d", abilityInfo_->type);
677 return ERR_INVALID_VALUE;
678 }
679 ErrCode err = AbilityContext::StartAbility(want, requestCode);
680 HILOG_INFO("%{public}s end.", __func__);
681 return err;
682 }
683
684 /**
685 * Starts an ability with specific start settings and returns the execution result when the ability is destroyed.
686 * When the ability is destroyed, onAbilityResult(int,int,ohos.aafwk.content.Want) is called and the returned
687 * requestCode is transferred to the current method. The given requestCode is customized and cannot be a negative
688 * number.
689 *
690 * @param want Indicates the ability to start.
691 * @param requestCode Indicates the request code returned after the ability is started. You can define the request
692 * code to identify the results returned by abilities. The value ranges from 0 to 65535.
693 * @param abilityStartSetting Indicates the setting ability used to start.
694 *
695 * @return errCode ERR_OK on success, others on failure.
696 */
StartAbilityForResult(const Want & want,int requestCode,AbilityStartSetting abilityStartSetting)697 ErrCode Ability::StartAbilityForResult(const Want &want, int requestCode, AbilityStartSetting abilityStartSetting)
698 {
699 HILOG_INFO("%{public}s begin.", __func__);
700 if (abilityInfo_ == nullptr) {
701 HILOG_ERROR("Ability::StartAbilityForResult abilityInfo_ == nullptr");
702 return ERR_NULL_OBJECT;
703 }
704 HILOG_INFO("Ability::StartAbilityForResult called type = %{public}d", abilityInfo_->type);
705 if (abilityInfo_->type != AppExecFwk::AbilityType::PAGE) {
706 HILOG_ERROR("Ability::StartAbility ability type: %{public}d", abilityInfo_->type);
707 return ERR_INVALID_VALUE;
708 }
709 ErrCode err = AbilityContext::StartAbility(want, requestCode, abilityStartSetting);
710 HILOG_INFO("%{public}s end.", __func__);
711 return err;
712 }
713
714 /**
715 * Starts a new ability with specific start settings.
716 * A Page or Service ability uses this method to start a specific ability.
717 * The system locates the target ability from installed abilities based on
718 * the value of the intent parameter and then starts it. You can specify the
719 * ability to start using the intent parameter.
720 *
721 * @param want Indicates the ability to start.
722 * @param abilityStartSetting Indicates the setting ability used to start.
723 *
724 * @return errCode ERR_OK on success, others on failure.
725 */
StartAbility(const Want & want,AbilityStartSetting abilityStartSetting)726 ErrCode Ability::StartAbility(const Want &want, AbilityStartSetting abilityStartSetting)
727 {
728 HILOG_INFO("%{public}s beign.", __func__);
729 if (abilityInfo_ == nullptr) {
730 HILOG_ERROR("Ability::StartAbility abilityInfo_ == nullptr");
731 return ERR_NULL_OBJECT;
732 }
733 HILOG_INFO("Ability::StartAbility called type = %{public}d", abilityInfo_->type);
734 if (abilityInfo_->type != AppExecFwk::AbilityType::PAGE && abilityInfo_->type != AppExecFwk::AbilityType::SERVICE) {
735 HILOG_ERROR("Ability::StartAbility ability type: %{public}d", abilityInfo_->type);
736 return ERR_INVALID_VALUE;
737 }
738 ErrCode err = AbilityContext::StartAbility(want, -1, abilityStartSetting);
739 HILOG_INFO("%{public}s end.", __func__);
740 return err;
741 }
742
743 #ifdef SUPPORT_GRAPHICS
744 /**
745 * @brief Called when a key is pressed. When any component in the Ability gains focus, the key-down event for
746 * the component will be handled first. This callback will not be invoked if the callback triggered for the
747 * key-down event of the component returns true. The default implementation of this callback does nothing
748 * and returns false.
749 *
750 * @param keyEvent Indicates the key-down event.
751 *
752 * @return Returns true if this event is handled and will not be passed further; returns false if this event
753 * is not handled and should be passed to other handlers.
754 */
OnKeyDown(const std::shared_ptr<MMI::KeyEvent> & keyEvent)755 void Ability::OnKeyDown(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
756 {
757 HILOG_INFO("Ability::OnKeyDown called");
758 }
759
760 /**
761 * @brief Called when a key is released. When any component in the Ability gains focus, the key-up event for
762 * the component will be handled first. This callback will not be invoked if the callback triggered for the
763 * key-up event of the component returns true. The default implementation of this callback does nothing and
764 * returns false.
765 *
766 * @param keyEvent Indicates the key-up event.
767 *
768 * @return Returns true if this event is handled and will not be passed further; returns false if this event
769 * is not handled and should be passed to other handlers.
770 */
OnKeyUp(const std::shared_ptr<MMI::KeyEvent> & keyEvent)771 void Ability::OnKeyUp(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
772 {
773 HILOG_INFO("Ability::OnKeyUp called");
774 auto code = keyEvent->GetKeyCode();
775 if (code == MMI::KeyEvent::KEYCODE_BACK) {
776 HILOG_INFO("Ability::OnKey Back key pressed.");
777 OnBackPressed();
778 }
779 }
780
781 /**
782 * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback
783 * does nothing and returns false.
784 *
785 * @param event Indicates information about the touch event.
786 *
787 * @return Returns true if the event is handled; returns false otherwise.
788 */
OnPointerEvent(std::shared_ptr<MMI::PointerEvent> & pointerEvent)789 void Ability::OnPointerEvent(std::shared_ptr<MMI::PointerEvent>& pointerEvent)
790 {
791 HILOG_INFO("Ability::OnTouchEvent called");
792 }
793
794 /**
795 * @brief Inflates UI controls by using ComponentContainer.
796 * You can create a ComponentContainer instance that contains multiple components.
797 *
798 * @param componentContainer Indicates a set of customized components.
799 */
SetUIContent(const ComponentContainer & componentContainer)800 void Ability::SetUIContent(const ComponentContainer &componentContainer)
801 {}
802
803 /**
804 * @brief Inflates layout resources by using the layout resource ID.
805 *
806 * @param layoutRes Indicates the layout resource ID, which cannot be a negative number.
807 */
SetUIContent(int layoutRes)808 void Ability::SetUIContent(int layoutRes)
809 {}
810
811 /**
812 * @brief Inflates UI controls by using ComponentContainer.
813 * You can create a ComponentContainer instance that contains multiple components.
814 *
815 * @param componentContainer Indicates the component layout defined by the user.
816 * @param context Indicates the context to use.
817 * @param typeFlag Indicates the window type.
818 */
SetUIContent(const ComponentContainer & componentContainer,std::shared_ptr<Context> & context,int typeFlag)819 void Ability::SetUIContent(
820 const ComponentContainer &componentContainer, std::shared_ptr<Context> &context, int typeFlag)
821 {}
822
823 /**
824 * @brief Inflates layout resources by using the layout resource ID.
825 *
826 * @param layoutRes Indicates the layout resource ID, which cannot be a negative number.
827 * @param context Indicates the context to use.
828 * @param typeFlag Indicates the window type.
829 */
SetUIContent(int layoutRes,std::shared_ptr<Context> & context,int typeFlag)830 void Ability::SetUIContent(int layoutRes, std::shared_ptr<Context> &context, int typeFlag)
831 {}
832
833 /**
834 * @brief Inflates UI controls by using WindowOption.
835 *
836 * @param windowOption Indicates the window option defined by the user.
837 */
InitWindow(Rosen::WindowType winType,int32_t displayId,sptr<Rosen::WindowOption> option)838 void Ability::InitWindow(Rosen::WindowType winType, int32_t displayId, sptr<Rosen::WindowOption> option)
839 {
840 if (abilityWindow_ == nullptr) {
841 HILOG_ERROR("Ability::InitWindow abilityWindow_ is nullptr");
842 return;
843 }
844 bool useNewMission = AbilityImpl::IsUseNewMission();
845 HILOG_INFO("%{public}s beign abilityWindow_->InitWindow.", __func__);
846 if (useNewMission) {
847 abilityWindow_->InitWindow(winType, abilityContext_, sceneListener_, displayId, option);
848 } else {
849 std::shared_ptr<AbilityRuntime::AbilityContext> context = nullptr;
850 sptr<Rosen::IWindowLifeCycle> listener = nullptr;
851 abilityWindow_->InitWindow(winType, context, listener, displayId, option);
852 }
853 HILOG_INFO("%{public}s end abilityWindow_->InitWindow.", __func__);
854 }
855
856 /**
857 * @brief Get the window belong to the ability.
858 *
859 * @return Returns a IWindowsManager object pointer.
860 */
GetWindow()861 const sptr<Rosen::Window> Ability::GetWindow()
862 {
863 if (abilityWindow_ != nullptr) {
864 return abilityWindow_->GetWindow();
865 } else {
866 HILOG_INFO("%{public}s abilityWindow_ is nullptr.", __func__);
867 return nullptr;
868 }
869 }
870
871 /**
872 * @brief get the scene belong to the ability.
873 *
874 * @return Returns a WindowScene object pointer.
875 */
GetScene()876 std::shared_ptr<Rosen::WindowScene> Ability::GetScene()
877 {
878 return scene_;
879 }
880
881 /**
882 * @brief Obtains the type of audio whose volume is adjusted by the volume button.
883 *
884 * @return Returns the AudioManager.AudioVolumeType.
885 */
GetVolumeTypeAdjustedByKey()886 int Ability::GetVolumeTypeAdjustedByKey()
887 {
888 return 0;
889 }
890
891 /**
892 * @brief Checks whether the main window of this ability has window focus.
893 *
894 * @return Returns true if this ability currently has window focus; returns false otherwise.
895 */
HasWindowFocus()896 bool Ability::HasWindowFocus()
897 {
898 if (abilityInfo_ == nullptr) {
899 HILOG_INFO("Ability::HasWindowFocus abilityInfo_ == nullptr");
900 return false;
901 }
902
903 if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
904 return bWindowFocus_;
905 }
906
907 return false;
908 }
909 #endif
910
911 /**
912 * @description: Obtains api version based on ability.
913 * @return api version.
914 */
GetCompatibleVersion()915 int Ability::GetCompatibleVersion()
916 {
917 return compatibleVersion_;
918 }
919
920 /**
921 * @description: Set api version in an ability.
922 * @param compatibleVersion api version
923 * @return None.
924 */
SetCompatibleVersion(int32_t compatibleVersion)925 void Ability::SetCompatibleVersion(int32_t compatibleVersion)
926 {
927 compatibleVersion_ = compatibleVersion;
928 }
929
930 #ifdef SUPPORT_GRAPHICS
SetShowOnLockScreen(bool showOnLockScreen)931 void Ability::SetShowOnLockScreen(bool showOnLockScreen)
932 {
933 HILOG_INFO("SetShowOnLockScreen come, showOnLockScreen is %{public}d", showOnLockScreen);
934 showOnLockScreen_ = showOnLockScreen;
935 sptr<Rosen::Window> window = nullptr;
936 if (abilityWindow_ == nullptr || (window = abilityWindow_->GetWindow()) == nullptr) {
937 HILOG_INFO("SetShowOnLockScreen come, window is null");
938 return;
939 }
940 HILOG_INFO("SetShowOnLockScreen come, addWindowFlag, showOnLockScreen is %{public}d", showOnLockScreen);
941 if (showOnLockScreen) {
942 window->AddWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED);
943 } else {
944 window->RemoveWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED);
945 }
946 }
947
948 /**
949 * @brief Called when a key is lone pressed.
950 *
951 * @param keyCode Indicates the code of the key long pressed.
952 * @param keyEvent Indicates the key-long-press event.
953 *
954 * @return Returns true if this event is handled and will not be passed further; returns false if this event
955 * is not handled and should be passed to other handlers.
956 */
OnKeyPressAndHold(int keyCode,const std::shared_ptr<KeyEvent> & keyEvent)957 bool Ability::OnKeyPressAndHold(int keyCode, const std::shared_ptr<KeyEvent> &keyEvent)
958 {
959 return false;
960 }
961 #endif
962
963 /**
964 * @brief Called back after permissions are requested by using
965 * AbilityContext.requestPermissionsFromUser(java.lang.String[],int).
966 *
967 * @param requestCode Indicates the request code passed to this method from
968 * AbilityContext.requestPermissionsFromUser(java.lang.String[],int).
969 * @param permissions Indicates the list of permissions requested by using
970 * AbilityContext.requestPermissionsFromUser(java.lang.String[],int). This parameter cannot be null.
971 * @param grantResults Indicates the granting results of the corresponding permissions requested using
972 * AbilityContext.requestPermissionsFromUser(java.lang.String[],int). The value 0 indicates that a
973 * permission is granted, and the value -1 indicates not.
974 *
975 */
OnRequestPermissionsFromUserResult(int requestCode,const std::vector<std::string> & permissions,const std::vector<int> & grantResults)976 void Ability::OnRequestPermissionsFromUserResult(
977 int requestCode, const std::vector<std::string> &permissions, const std::vector<int> &grantResults)
978 {}
979
980 #ifdef SUPPORT_GRAPHICS
981 /**
982 * @brief Called when this ability is about to leave the foreground and enter the background due to a user
983 * operation, for example, when the user touches the Home key.
984 *
985 */
OnLeaveForeground()986 void Ability::OnLeaveForeground()
987 {}
988 #endif
989
990 /**
991 * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
992 * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
993 *
994 * @param uri Indicates the URI of the data.
995 *
996 * @return Returns the MIME type that matches the data specified by uri.
997 */
GetType(const Uri & uri)998 std::string Ability::GetType(const Uri &uri)
999 {
1000 return "";
1001 }
1002
1003 /**
1004 * @brief Inserts a data record into the database. This method should be implemented by a Data ability.
1005 *
1006 * @param uri Indicates the position where the data is to insert.
1007 * @param value Indicates the data to insert.
1008 *
1009 * @return Returns the index of the newly inserted data record.
1010 */
Insert(const Uri & uri,const NativeRdb::ValuesBucket & value)1011 int Ability::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value)
1012 {
1013 return 0;
1014 }
1015
Call(const Uri & uri,const std::string & method,const std::string & arg,const AppExecFwk::PacMap & pacMap)1016 std::shared_ptr<AppExecFwk::PacMap> Ability::Call(
1017 const Uri &uri, const std::string &method, const std::string &arg, const AppExecFwk::PacMap &pacMap)
1018 {
1019 return nullptr;
1020 }
1021
1022 /**
1023 * @brief Called when the system configuration is updated.
1024 *
1025 * @param configuration Indicates the updated configuration information.
1026 */
OnConfigurationUpdated(const Configuration & configuration)1027 void Ability::OnConfigurationUpdated(const Configuration &configuration)
1028 {
1029 HILOG_INFO("%{public}s called.", __func__);
1030 }
1031
OnConfigurationUpdatedNotify(const Configuration & changeConfiguration)1032 void Ability::OnConfigurationUpdatedNotify(const Configuration &changeConfiguration)
1033 {
1034 HILOG_INFO("%{public}s begin.", __func__);
1035
1036 std::string language;
1037 std::string colormode;
1038 if (setting_) {
1039 auto displayId = std::atoi(setting_->GetProperty(AbilityStartSetting::WINDOW_DISPLAY_ID_KEY).c_str());
1040 language = changeConfiguration.GetItem(displayId, GlobalConfigurationKey::SYSTEM_LANGUAGE);
1041 colormode = changeConfiguration.GetItem(displayId, GlobalConfigurationKey::SYSTEM_COLORMODE);
1042 HILOG_INFO("displayId: [%{public}d], language: [%{public}s], colormode: [%{public}s]",
1043 displayId, language.c_str(), colormode.c_str());
1044 } else {
1045 language = changeConfiguration.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE);
1046 colormode = changeConfiguration.GetItem(GlobalConfigurationKey::SYSTEM_COLORMODE);
1047 HILOG_INFO("language: [%{public}s], colormode: [%{public}s]", language.c_str(), colormode.c_str());
1048 }
1049
1050 // Notify ResourceManager
1051 std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1052 if (resConfig == nullptr) {
1053 HILOG_ERROR("Create res config failed.");
1054 return;
1055 }
1056 auto resourceManager = GetResourceManager();
1057 if (resourceManager != nullptr) {
1058 resourceManager->GetResConfig(*resConfig);
1059 #ifdef SUPPORT_GRAPHICS
1060 if (!language.empty()) {
1061 UErrorCode status = U_ZERO_ERROR;
1062 icu::Locale locale = icu::Locale::forLanguageTag(language, status);
1063 HILOG_INFO("get Locale::forLanguageTag return[%{public}d].", static_cast<int>(status));
1064 if (status == U_ZERO_ERROR) {
1065 resConfig->SetLocaleInfo(locale);
1066 }
1067 }
1068 #endif
1069 resConfig->SetColorMode(ConvertColorMode(colormode));
1070 resourceManager->UpdateResConfig(*resConfig);
1071 HILOG_INFO("Notify ResourceManager, colorMode: %{public}d.", resConfig->GetColorMode());
1072 }
1073
1074 #ifdef SUPPORT_GRAPHICS
1075 // Notify WindowScene
1076 if (scene_ != nullptr) {
1077 auto diffConfiguration = std::make_shared<AppExecFwk::Configuration>(changeConfiguration);
1078 scene_->UpdateConfiguration(diffConfiguration);
1079 HILOG_INFO("%{public}s scene_ -> UpdateConfiguration success.", __func__);
1080 }
1081 #endif
1082 if (abilityContext_ != nullptr && application_ != nullptr) {
1083 abilityContext_->SetConfiguration(application_->GetConfiguration());
1084 }
1085 // Notify Ability Subclass
1086 OnConfigurationUpdated(changeConfiguration);
1087 HILOG_INFO("%{public}s Notify Ability Subclass.", __func__);
1088 }
1089
1090 /**
1091 * @brief Called when the system configuration is updated.
1092 *
1093 * @param level Indicates the memory trim level, which shows the current memory usage status.
1094 *
1095 */
OnMemoryLevel(int level)1096 void Ability::OnMemoryLevel(int level)
1097 {}
1098
1099 /**
1100 * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets
1101 * inside of their .hap.
1102 *
1103 * @param uri Indicates the path of the file to open.
1104 * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
1105 * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
1106 * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
1107 * data, or "rwt" for read and write access that truncates any existing file.
1108 *
1109 * @return Returns the RawFileDescriptor object containing file descriptor.
1110 */
OpenRawFile(const Uri & uri,const std::string & mode)1111 int Ability::OpenRawFile(const Uri &uri, const std::string &mode)
1112 {
1113 return -1;
1114 }
1115
1116 /**
1117 * @brief Updates one or more data records in the database. This method should be implemented by a Data ability.
1118 *
1119 * @param uri Indicates the database table storing the data to update.
1120 * @param value Indicates the data to update. This parameter can be null.
1121 * @param predicates Indicates filter criteria. If this parameter is null, all data records will be updated by
1122 * default.
1123 *
1124 * @return Returns the number of data records updated.
1125 */
Update(const Uri & uri,const NativeRdb::ValuesBucket & value,const NativeRdb::DataAbilityPredicates & predicates)1126 int Ability::Update(
1127 const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates)
1128 {
1129 return 0;
1130 }
1131
1132 /**
1133 * @brief get application witch the ability belong
1134 *
1135 * @return Returns the application ptr
1136 */
GetApplication()1137 std::shared_ptr<OHOSApplication> Ability::GetApplication()
1138 {
1139 HILOG_INFO("%{public}s begin.", __func__);
1140 if (application_ == nullptr) {
1141 HILOG_ERROR("Ability::GetApplication error. application_ == nullptr.");
1142 return nullptr;
1143 }
1144 HILOG_INFO("%{public}s end.", __func__);
1145 return application_;
1146 }
1147
1148 /**
1149 * @brief Obtains the class name in this ability name, without the prefixed bundle name.
1150 *
1151 * @return Returns the class name of this ability.
1152 */
GetAbilityName()1153 std::string Ability::GetAbilityName()
1154 {
1155 if (abilityInfo_ == nullptr) {
1156 HILOG_ERROR("Ability::GetAbilityName abilityInfo_ is nullptr");
1157 return "";
1158 }
1159
1160 return abilityInfo_->name;
1161 }
1162
1163 /**
1164 * @brief OChecks whether the current ability is being destroyed.
1165 * An ability is being destroyed if you called terminateAbility() on it or someone else requested to destroy it.
1166 *
1167 * @return Returns true if the current ability is being destroyed; returns false otherwise.
1168 */
IsTerminating()1169 bool Ability::IsTerminating()
1170 {
1171 return false;
1172 }
1173
1174 /**
1175 * @brief Called when startAbilityForResult(ohos.aafwk.content.Want,int) is called to start an ability and the
1176 * result is returned. This method is called only on Page abilities. You can start a new ability to perform some
1177 * calculations and use setResult (int,ohos.aafwk.content.Want) to return the calculation result. Then the system
1178 * calls back the current method to use the returned data to execute its own logic.
1179 *
1180 * @param requestCode Indicates the request code returned after the ability is started. You can define the request
1181 * code to identify the results returned by abilities. The value ranges from 0 to 65535.
1182 * @param resultCode Indicates the result code returned after the ability is started. You can define the result code
1183 * to identify an error.
1184 * @param resultData Indicates the data returned after the ability is started. You can define the data returned. The
1185 * value can be null.
1186 *
1187 */
OnAbilityResult(int requestCode,int resultCode,const Want & want)1188 void Ability::OnAbilityResult(int requestCode, int resultCode, const Want &want)
1189 {}
1190
1191 #ifdef SUPPORT_GRAPHICS
1192 /**
1193 * @brief Called back when the Back key is pressed.
1194 * The default implementation destroys the ability. You can override this method.
1195 *
1196 */
OnBackPressed()1197 void Ability::OnBackPressed()
1198 {
1199 HILOG_INFO("%{public}s begin.", __func__);
1200 if (abilityInfo_ == nullptr) {
1201 HILOG_ERROR("Ability::OnBackPressed abilityInfo_ is nullptr");
1202 return;
1203 }
1204
1205 if (abilityInfo_->isLauncherAbility == false) {
1206 HILOG_INFO("Ability::OnBackPressed the ability is not Launcher");
1207 TerminateAbility();
1208 }
1209 HILOG_INFO("%{public}s end.", __func__);
1210 }
1211 #endif
1212
1213 /**
1214 * @brief Called when the launch mode of an ability is set to singleInstance. This happens when you re-launch an
1215 * ability that has been at the top of the ability stack.
1216 *
1217 * @param want Indicates the new Want containing information about the ability.
1218 */
OnNewWant(const Want & want)1219 void Ability::OnNewWant(const Want &want)
1220 {
1221 HILOG_INFO("Ability::OnNewWant called");
1222 }
1223
1224 /**
1225 * @brief Restores data and states of an ability when it is restored by the system. This method should be
1226 * implemented by a Page ability. This method is called if an ability was destroyed at a certain time due to
1227 * resource reclaim or was unexpectedly destroyed and the onSaveAbilityState(ohos.utils.PacMap) method was called to
1228 * save its user data and states. Generally, this method is called after the onStart(ohos.aafwk.content.Want)
1229 * method.
1230 *
1231 * @param inState Indicates the PacMap object used for storing data and states. This parameter can not be null.
1232 *
1233 */
OnRestoreAbilityState(const PacMap & inState)1234 void Ability::OnRestoreAbilityState(const PacMap &inState)
1235 {
1236 HILOG_INFO("Ability::OnRestoreAbilityState called");
1237 }
1238
1239 /**
1240 * @brief Saves temporary data and states of this ability. This method should be implemented by a Page ability.
1241 * This method is called when the system determines that the ability may be destroyed in an unexpected situation,
1242 * for example, when the screen orientation changes or the user touches the Home key. Generally, this method is used
1243 * only to save temporary states.
1244 *
1245 * @param outState Indicates the PacMap object used for storing user data and states. This parameter cannot be
1246 * null.
1247 *
1248 */
OnSaveAbilityState(PacMap & outState)1249 void Ability::OnSaveAbilityState(PacMap &outState)
1250 {
1251 HILOG_INFO("Ability::OnSaveAbilityState called");
1252 }
1253
1254 /**
1255 * @brief Called every time a key, touch, or trackball event is dispatched to this ability.
1256 * You can override this callback method if you want to know that the user has interacted with
1257 * the device in a certain way while this ability is running. This method, together with onLeaveForeground(),
1258 * is designed to help abilities intelligently manage status bar notifications. Specifically, they help
1259 * abilities determine when to cancel a notification.
1260 *
1261 */
OnEventDispatch()1262 void Ability::OnEventDispatch()
1263 {}
1264
1265 /**
1266 * @brief Sets the want object that can be obtained by calling getWant().
1267 * @param Want information of other ability
1268 */
SetWant(const AAFwk::Want & want)1269 void Ability::SetWant(const AAFwk::Want &want)
1270 {
1271 setWant_ = std::make_shared<AAFwk::Want>(want);
1272 }
1273
1274 /**
1275 * @brief Obtains the Want object that starts this ability.
1276 *
1277 * @return Returns the Want object that starts this ability.
1278 */
GetWant()1279 std::shared_ptr<AAFwk::Want> Ability::GetWant()
1280 {
1281 return setWant_;
1282 }
1283
1284 /**
1285 * @brief Sets the result code and data to be returned by this Page ability to the caller.
1286 * When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want) method to
1287 * receive the result set in the current method. This method can be called only after the ability has been
1288 * initialized.
1289 *
1290 * @param resultCode Indicates the result code returned after the ability is destroyed. You can define the result
1291 * code to identify an error.
1292 * @param resultData Indicates the data returned after the ability is destroyed. You can define the data returned.
1293 * This parameter can be null.
1294 */
SetResult(int resultCode,const Want & resultData)1295 void Ability::SetResult(int resultCode, const Want &resultData)
1296 {
1297 HILOG_INFO("%{public}s begin.", __func__);
1298 if (abilityInfo_ == nullptr) {
1299 HILOG_ERROR("Ability::SetResult abilityInfo_ == nullptr");
1300 return;
1301 }
1302 HILOG_INFO("Ability::SetResult called type = %{public}d", abilityInfo_->type);
1303 if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
1304 AbilityContext::resultWant_ = resultData;
1305 AbilityContext::resultCode_ = resultCode;
1306 }
1307 HILOG_INFO("%{public}s end.", __func__);
1308 }
1309
1310 #ifdef SUPPORT_GRAPHICS
1311 /**
1312 * @brief Sets the type of audio whose volume will be adjusted by the volume button.
1313 *
1314 * @param volumeType Indicates the AudioManager.AudioVolumeType to set.
1315 */
SetVolumeTypeAdjustedByKey(int volumeType)1316 void Ability::SetVolumeTypeAdjustedByKey(int volumeType)
1317 {}
1318 #endif
1319
1320 /**
1321 * @brief Called back when Service is started.
1322 * This method can be called only by Service. You can use the StartAbility(ohos.aafwk.content.Want) method to start
1323 * Service. Then the system calls back the current method to use the transferred want parameter to execute its own
1324 * logic.
1325 *
1326 * @param want Indicates the want of Service to start.
1327 * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being
1328 * destroyed, and the value false indicates a normal startup.
1329 * @param startId Indicates the number of times the Service ability has been started. The startId is incremented by
1330 * 1 every time the ability is started. For example, if the ability has been started for six times, the value of
1331 * startId is 6.
1332 */
OnCommand(const AAFwk::Want & want,bool restart,int startId)1333 void Ability::OnCommand(const AAFwk::Want &want, bool restart, int startId)
1334 {
1335 BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1336 HILOG_INFO(
1337 "%{public}s begin restart=%{public}s,startId=%{public}d.", __func__, restart ? "true" : "false", startId);
1338 if (abilityLifecycleExecutor_ == nullptr) {
1339 HILOG_ERROR("Ability::OnCommand error. abilityLifecycleExecutor_ == nullptr.");
1340 return;
1341 }
1342 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::ACTIVE);
1343
1344 if (lifecycle_ == nullptr) {
1345 HILOG_ERROR("Ability::OnCommand error. lifecycle_ == nullptr.");
1346 return;
1347 }
1348 lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
1349 HILOG_INFO("%{public}s end.", __func__);
1350 }
1351
1352 /**
1353 * @brief dump ability info
1354 *
1355 * @param extra dump ability info
1356 */
Dump(const std::string & extra)1357 void Ability::Dump(const std::string &extra)
1358 {
1359 HILOG_INFO("Ability::Dump called");
1360 // abilityInfo
1361 HILOG_INFO("==============AbilityInfo==============");
1362 if (abilityInfo_ != nullptr) {
1363 HILOG_INFO("abilityInfo: package: %{public}s", abilityInfo_->package.c_str());
1364 HILOG_INFO("abilityInfo: name: %{public}s", abilityInfo_->name.c_str());
1365 HILOG_INFO("abilityInfo: label: %{public}s", abilityInfo_->label.c_str());
1366 HILOG_INFO("abilityInfo: description: %{public}s", abilityInfo_->description.c_str());
1367 HILOG_INFO("abilityInfo: iconPath: %{public}s", abilityInfo_->iconPath.c_str());
1368 HILOG_INFO("abilityInfo: visible: %{public}d", abilityInfo_->visible);
1369 HILOG_INFO("abilityInfo: kind: %{public}s", abilityInfo_->kind.c_str());
1370 HILOG_INFO("abilityInfo: type: %{public}d", abilityInfo_->type);
1371 HILOG_INFO("abilityInfo: orientation: %{public}d", abilityInfo_->orientation);
1372 HILOG_INFO("abilityInfo: launchMode: %{public}d", abilityInfo_->launchMode);
1373 for (auto permission : abilityInfo_->permissions) {
1374 HILOG_INFO("abilityInfo: permission: %{public}s", permission.c_str());
1375 }
1376 HILOG_INFO("abilityInfo: bundleName: %{public}s", abilityInfo_->bundleName.c_str());
1377 HILOG_INFO("abilityInfo: applicationName: %{public}s", abilityInfo_->applicationName.c_str());
1378 } else {
1379 HILOG_INFO("abilityInfo is nullptr");
1380 }
1381
1382 // lifecycle_Event
1383 HILOG_INFO("==============lifecycle_Event==============");
1384 if (lifecycle_ != nullptr) {
1385 HILOG_INFO("lifecycle_Event: launchMode: %{public}d", lifecycle_->GetLifecycleState());
1386 } else {
1387 HILOG_INFO("lifecycle is nullptr");
1388 }
1389
1390 // lifecycle_State
1391 HILOG_INFO("==============lifecycle_State==============");
1392 if (abilityLifecycleExecutor_ != nullptr) {
1393 HILOG_INFO("lifecycle_State: launchMode: %{public}d", abilityLifecycleExecutor_->GetState());
1394 } else {
1395 HILOG_INFO("abilityLifecycleExecutor is nullptr");
1396 }
1397
1398 // applicationInfo
1399 HILOG_INFO("==============applicationInfo==============");
1400 std::shared_ptr<ApplicationInfo> ApplicationInfoPtr = GetApplicationInfo();
1401 if (ApplicationInfoPtr != nullptr) {
1402 HILOG_INFO("applicationInfo: name: %{public}s", ApplicationInfoPtr->name.c_str());
1403 HILOG_INFO("applicationInfo: bundleName: %{public}s", ApplicationInfoPtr->bundleName.c_str());
1404 } else {
1405 HILOG_INFO("ApplicationInfoPtr is nullptr");
1406 }
1407 }
1408
1409 /**
1410 * @brief dump ability info
1411 *
1412 * @param params dump params that indicate different dump targets
1413 * @param info dump ability info
1414 */
Dump(const std::vector<std::string> & params,std::vector<std::string> & info)1415 void Ability::Dump(const std::vector<std::string> ¶ms, std::vector<std::string> &info)
1416 {}
1417
1418 /**
1419 * @brief Keeps this Service ability in the background and displays a notification bar.
1420 * To use this method, you need to request the ohos.permission.KEEP_BACKGROUND_RUNNING permission from the system.
1421 * The ohos.permission.KEEP_BACKGROUND_RUNNING permission is of the normal level.
1422 * This method can be called only by Service abilities after the onStart(ohos.aafwk.content.Want) method is called.
1423 *
1424 * @param id Identifies the notification bar information.
1425 * @param notificationRequest Indicates the NotificationRequest instance containing information for displaying a
1426 * notification bar.
1427 */
KeepBackgroundRunning(int id,const NotificationRequest & notificationRequest)1428 void Ability::KeepBackgroundRunning(int id, const NotificationRequest ¬ificationRequest)
1429 {}
1430
1431 /**
1432 * @brief Cancels background running of this ability to free up system memory.
1433 * This method can be called only by Service abilities when the onStop() method is called.
1434 *
1435 */
CancelBackgroundRunning()1436 void Ability::CancelBackgroundRunning()
1437 {}
1438
1439 /**
1440 * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used
1441 * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the
1442 * context has changed. If you implement URI normalization for a Data ability, you must also implement
1443 * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
1444 * any method that is called on the Data ability must require normalization verification and denormalization. The
1445 * default implementation of this method returns null, indicating that this Data ability does not support URI
1446 * normalization.
1447 *
1448 * @param uri Indicates the Uri object to normalize.
1449 *
1450 * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise.
1451 */
NormalizeUri(const Uri & uri)1452 Uri Ability::NormalizeUri(const Uri &uri)
1453 {
1454 return uri;
1455 }
1456
1457 /**
1458 * @brief Deletes one or more data records. This method should be implemented by a Data ability.
1459 *
1460 * @param uri Indicates the database table storing the data to delete.
1461 * @param predicates Indicates filter criteria. If this parameter is null, all data records will be deleted by
1462 * default.
1463 *
1464 * @return Returns the number of data records deleted.
1465 */
Delete(const Uri & uri,const NativeRdb::DataAbilityPredicates & predicates)1466 int Ability::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates)
1467 {
1468 return 0;
1469 }
1470
1471 /**
1472 * @brief Obtains the MIME type of files. This method should be implemented by a Data ability.
1473 *
1474 * @param uri Indicates the path of the files to obtain.
1475 * @param mimeTypeFilter Indicates the MIME type of the files to obtain. This parameter cannot be set to null.
1476 * 1. * / *: Obtains all types supported by a Data ability.
1477 * 2. image/ *: Obtains files whose main type is image of any subtype.
1478 * 3. * /jpg: Obtains files whose subtype is JPG of any main type.
1479 *
1480 * @return Returns the MIME type of the matched files; returns null if there is no type that matches the Data
1481 * ability.
1482 */
GetFileTypes(const Uri & uri,const std::string & mimeTypeFilter)1483 std::vector<std::string> Ability::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
1484 {
1485 return types_;
1486 }
1487
1488 /**
1489 * @brief Opens a file. This method should be implemented by a Data ability.
1490 *
1491 * @param uri Indicates the path of the file to open.
1492 * @param mode Indicates the open mode, which can be "r" for read-only access, "w" for write-only access
1493 * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
1494 * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
1495 * or "rwt" for read and write access that truncates any existing file.
1496 *
1497 * @return Returns the FileDescriptor object of the file descriptor.
1498 */
OpenFile(const Uri & uri,const std::string & mode)1499 int Ability::OpenFile(const Uri &uri, const std::string &mode)
1500 {
1501 return -1;
1502 }
1503
1504 /**
1505 * @brief Queries one or more data records in the database. This method should be implemented by a Data ability.
1506 *
1507 * @param uri Indicates the database table storing the data to query.
1508 * @param columns Indicates the columns to be queried, in array, for example, {"name","age"}. You should define the
1509 * processing logic when this parameter is null.
1510 * @param predicates Indicates filter criteria. If this parameter is null, all data records will be queried by
1511 * default.
1512 *
1513 * @return Returns the queried data.
1514 */
Query(const Uri & uri,const std::vector<std::string> & columns,const NativeRdb::DataAbilityPredicates & predicates)1515 std::shared_ptr<NativeRdb::AbsSharedResultSet> Ability::Query(
1516 const Uri &uri, const std::vector<std::string> &columns, const NativeRdb::DataAbilityPredicates &predicates)
1517 {
1518 return nullptr;
1519 }
1520
1521 /**
1522 * @brief Reloads data in the database.
1523 * The default implementation of this method returns false. You must implement this method in the child class
1524 * of your Data Ability if you want to use it.
1525 *
1526 * @param uri Indicates the position where the data is to reload.
1527 * @param extras Indicates the additional parameters contained in the PacMap object to be passed in this call.
1528 *
1529 * @return Returns true if the data is successfully reloaded; returns false otherwise.
1530 */
Reload(const Uri & uri,const PacMap & extras)1531 bool Ability::Reload(const Uri &uri, const PacMap &extras)
1532 {
1533 return false;
1534 }
1535
1536 /**
1537 * @brief Inserts multiple data records into the database.
1538 *
1539 * @param uri Indicates the path of the data to operate.
1540 * @param values Indicates the data records to insert.
1541 *
1542 * @return Returns the number of data records inserted.
1543 */
BatchInsert(const Uri & uri,const std::vector<NativeRdb::ValuesBucket> & values)1544 int Ability::BatchInsert(const Uri &uri, const std::vector<NativeRdb::ValuesBucket> &values)
1545 {
1546 HILOG_INFO("%{public}s begin.", __func__);
1547 int amount = 0;
1548 for (auto it = values.begin(); it != values.end(); it++) {
1549 if (Insert(uri, *it) >= 0) {
1550 amount++;
1551 }
1552 }
1553 HILOG_INFO("%{public}s end, amount=%{public}d", __func__, amount);
1554 return amount;
1555 }
1556
1557 /**
1558 * @brief Migrates this ability to the given device on the same distributed network in a reversible way that allows
1559 * this ability to be migrated back to the local device through reverseContinueAbility(). The ability to migrate and
1560 * its ability slices must implement the IAbilityContinuation interface. Otherwise, an exception is thrown,
1561 * indicating that the ability does not support migration.
1562 *
1563 * @param deviceId Indicates the ID of the target device where this ability will be migrated to. If this parameter
1564 * is null, this method has the same effect as ContinueAbilityReversibly().
1565 *
1566 */
ContinueAbilityReversibly(const std::string & deviceId)1567 void Ability::ContinueAbilityReversibly(const std::string &deviceId)
1568 {
1569 if (!VerifySupportForContinuation()) {
1570 HILOG_ERROR("Ability::ContinueAbilityReversibly(deviceId) failed. VerifySupportForContinuation faled");
1571 return;
1572 }
1573 continuationManager_->ContinueAbility(true, deviceId);
1574 }
1575
1576 /**
1577 * @brief public final String getOriginalDeviceId() throws UnsupportedOperationException
1578 * Obtains the ID of the source device from which this ability is migrated.
1579 *
1580 * @return Returns the source device ID.
1581 */
GetOriginalDeviceId()1582 std::string Ability::GetOriginalDeviceId()
1583 {
1584 return "";
1585 }
1586
1587 /**
1588 * @brief Obtains the migration state of this ability.
1589 * @return Returns the migration state.
1590 *
1591 * @return Returns the source device ID.
1592 */
GetContinuationState()1593 ContinuationState Ability::GetContinuationState()
1594 {
1595 if (!VerifySupportForContinuation()) {
1596 HILOG_ERROR("Ability::GetContinuationState failed. VerifySupportForContinuation faled");
1597 return ContinuationState::LOCAL_RUNNING;
1598 }
1599 return continuationManager_->GetContinuationState();
1600 }
1601
1602 /**
1603 * @brief Obtains the singleton AbilityPackage object to which this ability belongs.
1604 *
1605 * @return Returns the singleton AbilityPackage object to which this ability belongs.
1606 */
GetAbilityPackage()1607 std::shared_ptr<AbilityPackage> Ability::GetAbilityPackage()
1608 {
1609 return nullptr;
1610 }
1611
1612 /**
1613 * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
1614 * The default implementation of this method returns the original URI passed to it.
1615 *
1616 * @param uri uri Indicates the Uri object to denormalize.
1617 *
1618 * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed
1619 * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found
1620 * in the current environment.
1621 */
DenormalizeUri(const Uri & uri)1622 Uri Ability::DenormalizeUri(const Uri &uri)
1623 {
1624 return uri;
1625 }
1626
1627 /**
1628 * @brief Obtains the Lifecycle object of the current ability.
1629 *
1630 * @return Returns the Lifecycle object.
1631 */
GetLifecycle()1632 std::shared_ptr<LifeCycle> Ability::GetLifecycle()
1633 {
1634 HILOG_INFO("Ability::GetLifecycle called");
1635 return lifecycle_;
1636 }
1637
1638 /**
1639 * @brief Obtains the lifecycle state of this ability.
1640 *
1641 * @return Returns the lifecycle state of this ability.
1642 */
GetState()1643 AbilityLifecycleExecutor::LifecycleState Ability::GetState()
1644 {
1645 HILOG_INFO("Ability::GetState called");
1646
1647 if (abilityLifecycleExecutor_ == nullptr) {
1648 HILOG_ERROR("Ability::GetState error. abilityLifecycleExecutor_ == nullptr.");
1649 return AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED;
1650 }
1651
1652 return (AbilityLifecycleExecutor::LifecycleState)abilityLifecycleExecutor_->GetState();
1653 }
1654
StartAbility(const Want & want)1655 ErrCode Ability::StartAbility(const Want &want)
1656 {
1657 HILOG_INFO("%{public}s begin Ability::StartAbility", __func__);
1658 return AbilityContext::StartAbility(want, -1);
1659 }
1660
1661 /**
1662 * @brief Destroys this Page or Service ability.
1663 * After a Page or Service ability performs all operations, it can use this method to destroy itself
1664 * to free up memory. This method can be called only after the ability is initialized.
1665 *
1666 * @return errCode ERR_OK on success, others on failure.
1667 */
TerminateAbility()1668 ErrCode Ability::TerminateAbility()
1669 {
1670 HILOG_INFO("%{public}s begin Ability::TerminateAbility", __func__);
1671 return AbilityContext::TerminateAbility();
1672 }
1673
1674 /**
1675 * @brief Destroys ability.
1676 *
1677 * @param want Indicates the want containing information about TerminateAbility
1678 *
1679 * @return Returns the result of TerminateAbility
1680 */
TerminateAbility(Want & want)1681 int Ability::TerminateAbility(Want &want)
1682 {
1683 return -1;
1684 }
1685
1686 /**
1687 * @brief Sets the main route for this ability.
1688 *
1689 * The main route, also called main entry, refers to the default <b>AbilitySlice</b> to present for this ability.
1690 * This function should be called only on Feature Abilities. If this function is not called in the
1691 * {@link OnStart(const Want &want)} function for a Feature Ability, the Feature Ability will fail to start.
1692 *
1693 * @param entry Indicates the main entry, which is the class name of the <b>AbilitySlice</b> instance to start.
1694 *
1695 * @return Returns the result of SetMainRouter
1696 */
SetMainRoute(const std::string & entry)1697 void Ability::SetMainRoute(const std::string &entry)
1698 {}
1699
1700 /**
1701 * @brief By binding an action, you can set different action parameters in Intent to present different initial
1702 * pages. You must register actions in the profile file.
1703 *
1704 * @param action Indicates the action to bind.
1705 *
1706 * @param entry Indicates the entry, which is the fully qualified name of your AbilitySlice class.
1707 *
1708 * @return Returns the result of AddActionRoute
1709 */
AddActionRoute(const std::string & action,const std::string & entry)1710 void Ability::AddActionRoute(const std::string &action, const std::string &entry)
1711 {}
1712
1713 #ifdef SUPPORT_GRAPHICS
1714 /**
1715 * @brief Sets the background color of the window in RGB color mode.
1716 *
1717 * @param red The value ranges from 0 to 255.
1718 *
1719 * @param green The value ranges from 0 to 255.
1720 *
1721 * @param blue The value ranges from 0 to 255.
1722 *
1723 * @return Returns the result of SetWindowBackgroundColor
1724 */
SetWindowBackgroundColor(int red,int green,int blue)1725 int Ability::SetWindowBackgroundColor(int red, int green, int blue)
1726 {
1727 return -1;
1728 }
1729 #endif
1730
1731 /**
1732 * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template.
1733 *
1734 * @param want Indicates the want containing information about the ability to connect
1735 *
1736 * @param conn Indicates the callback object when the target ability is connected.
1737 *
1738 * @return True means success and false means failure
1739 */
ConnectAbility(const Want & want,const sptr<AAFwk::IAbilityConnection> & conn)1740 bool Ability::ConnectAbility(const Want &want, const sptr<AAFwk::IAbilityConnection> &conn)
1741 {
1742 return AbilityContext::ConnectAbility(want, conn);
1743 }
1744
1745 /**
1746 * @brief Disconnects the current ability from an ability
1747 *
1748 * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection
1749 * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities.
1750 *
1751 * @return errCode ERR_OK on success, others on failure.
1752 */
DisconnectAbility(const sptr<AAFwk::IAbilityConnection> & conn)1753 ErrCode Ability::DisconnectAbility(const sptr<AAFwk::IAbilityConnection> &conn)
1754 {
1755 return AbilityContext::DisconnectAbility(conn);
1756 }
1757
1758 /**
1759 * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template.
1760 * The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE
1761 * template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE
1762 * template. The current ability itself can be destroyed by calling the terminateAbility() method.
1763 *
1764 * @param want Indicates the Want containing information about the ability to destroy.
1765 *
1766 * @return Returns true if the ability is destroyed successfully; returns false otherwise.
1767 */
StopAbility(const AAFwk::Want & want)1768 bool Ability::StopAbility(const AAFwk::Want &want)
1769 {
1770 return AbilityContext::StopAbility(want);
1771 }
1772
1773 /**
1774 * @brief Posts a scheduled Runnable task to a new non-UI thread.
1775 * The task posted via this method will be executed in a new thread, which allows you to perform certain
1776 * time-consuming operations. To use this method, you must also override the supportHighPerformanceUI() method.
1777 *
1778 * @param task Indicates the Runnable task to post.
1779 *
1780 * @param delayTime Indicates the number of milliseconds after which the task will be executed.
1781 *
1782 * @return -
1783 */
PostTask(std::function<void ()> task,long delayTime)1784 void Ability::PostTask(std::function<void()> task, long delayTime)
1785 {
1786 HILOG_INFO("%{public}s begin.", __func__);
1787 TaskHandlerClient::GetInstance()->PostTask(task, delayTime);
1788 HILOG_INFO("%{public}s end.", __func__);
1789 }
1790
1791 /**
1792 * @brief You can use the IContinuationRegisterManager object to interact with the Device+ control center,
1793 * including registering and unregistering the ability to migrate, updating the device connection state, and
1794 * showing the list of devices that can be selected for ability migration.
1795 *
1796 * @return Returns true if the migration request is successful; returns false otherwise.
1797 */
GetContinuationRegisterManager()1798 std::weak_ptr<IContinuationRegisterManager> Ability::GetContinuationRegisterManager()
1799 {
1800 if (abilityInfo_ != nullptr) {
1801 if ((abilityInfo_->type == AbilityType::PAGE) && (continuationRegisterManager_ == nullptr)) {
1802 std::weak_ptr<Context> context = shared_from_this();
1803 std::shared_ptr<ContinuationRegisterManagerProxy> continuationRegisterManagerProxy =
1804 std::make_shared<ContinuationRegisterManagerProxy>(context);
1805 continuationRegisterManager_ = std::make_shared<ContinuationRegisterManager>();
1806 continuationRegisterManager_->Init(continuationRegisterManagerProxy);
1807 }
1808 }
1809 std::weak_ptr<IContinuationRegisterManager> continuationRegisterManager =
1810 std::weak_ptr<IContinuationRegisterManager>(continuationRegisterManager_);
1811 return continuationRegisterManager;
1812 }
1813
1814 /**
1815 * @brief Callback function to ask the user to prepare for the migration .
1816 *
1817 * @return If the user allows migration and saves data suscessfully, it returns 0; otherwise, it returns errcode.
1818 */
OnContinue(WantParams & wantParams)1819 int32_t Ability::OnContinue(WantParams &wantParams)
1820 {
1821 return ContinuationManager::OnContinueResult::Reject;
1822 }
1823
1824 #ifdef SUPPORT_GRAPHICS
1825 /**
1826 * @brief Get page ability stack info.
1827 *
1828 * @return A string represents page ability stack info, empty if failed;
1829 */
GetContentInfo()1830 std::string Ability::GetContentInfo()
1831 {
1832 if (scene_ == nullptr) {
1833 return "";
1834 }
1835 return scene_->GetContentInfo();
1836 }
1837 #endif
1838
1839 /**
1840 * @brief Migrates this ability to the given device on the same distributed network. The ability to migrate and its
1841 * ability slices must implement the IAbilityContinuation interface.
1842 *
1843 * @param deviceId Indicates the ID of the target device where this ability will be migrated to. If this parameter
1844 * is null, this method has the same effect as continueAbility().
1845 *
1846 */
ContinueAbilityWithStack(const std::string & deviceId)1847 void Ability::ContinueAbilityWithStack(const std::string &deviceId)
1848 {
1849 if (deviceId.empty()) {
1850 HILOG_ERROR("ContinueAbilityWithStack(deviceId) failed. deviceId is empty");
1851 return;
1852 }
1853
1854 if (!VerifySupportForContinuation()) {
1855 HILOG_ERROR("ContinueAbilityWithStack(deviceId) failed. VerifySupportForContinuation failed");
1856 return;
1857 }
1858 continuationManager_->ContinueAbilityWithStack(deviceId);
1859 }
1860
1861 /**
1862 * @brief Migrates this ability to the given device on the same distributed network. The ability to migrate and its
1863 * ability slices must implement the IAbilityContinuation interface.
1864 *
1865 * @param deviceId Indicates the ID of the target device where this ability will be migrated to. If this parameter
1866 * is null, this method has the same effect as continueAbility().
1867 *
1868 */
ContinueAbility(const std::string & deviceId)1869 void Ability::ContinueAbility(const std::string &deviceId)
1870 {
1871 if (deviceId.empty()) {
1872 HILOG_ERROR("Ability::ContinueAbility(deviceId) failed. deviceId is empty");
1873 return;
1874 }
1875
1876 if (!VerifySupportForContinuation()) {
1877 HILOG_ERROR("Ability::ContinueAbility(deviceId) failed. VerifySupportForContinuation failed");
1878 return;
1879 }
1880 continuationManager_->ContinueAbility(false, deviceId);
1881 }
1882
1883 /**
1884 * @brief Callback function to ask the user whether to start the migration .
1885 *
1886 * @return If the user allows migration, it returns true; otherwise, it returns false.
1887 */
OnStartContinuation()1888 bool Ability::OnStartContinuation()
1889 {
1890 return false;
1891 }
1892
1893 /**
1894 * @brief Save user data of local Ability generated at runtime.
1895 *
1896 * @param saveData Indicates the user data to be saved.
1897 * @return If the data is saved successfully, it returns true; otherwise, it returns false.
1898 */
OnSaveData(WantParams & saveData)1899 bool Ability::OnSaveData(WantParams &saveData)
1900 {
1901 return false;
1902 }
1903
1904 /**
1905 * @brief After creating the Ability on the remote device,
1906 * immediately restore the user data saved during the migration of the Ability on the remote device.
1907 * @param restoreData Indicates the user data to be restored.
1908 * @return If the data is restored successfully, it returns true; otherwise, it returns false .
1909 */
OnRestoreData(WantParams & restoreData)1910 bool Ability::OnRestoreData(WantParams &restoreData)
1911 {
1912 return false;
1913 }
1914
1915 /**
1916 * @brief This function can be used to implement the processing logic after the migration is completed.
1917 *
1918 * @param result Migration result code. 0 means the migration was successful, -1 means the migration failed.
1919 * @return None.
1920 */
OnCompleteContinuation(int result)1921 void Ability::OnCompleteContinuation(int result)
1922 {
1923 HILOG_INFO("Ability::OnCompleteContinuation change continuation state to initial");
1924 continuationManager_->ChangeProcessStateToInit();
1925 }
1926
1927 /**
1928 * @brief Used to notify the local Ability that the remote Ability has been destroyed.
1929 *
1930 * @return None.
1931 */
OnRemoteTerminated()1932 void Ability::OnRemoteTerminated()
1933 {}
1934
DispatchLifecycleOnForeground(const Want & want)1935 void Ability::DispatchLifecycleOnForeground(const Want &want)
1936 {
1937 if (abilityLifecycleExecutor_ == nullptr) {
1938 HILOG_ERROR("Ability::OnForeground error. abilityLifecycleExecutor_ == nullptr.");
1939 return;
1940 }
1941 if (abilityInfo_->isStageBasedModel) {
1942 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::FOREGROUND_NEW);
1943 } else {
1944 abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INACTIVE);
1945 }
1946 if (lifecycle_ == nullptr) {
1947 HILOG_ERROR("Ability::OnForeground error. lifecycle_ == nullptr.");
1948 return;
1949 }
1950 lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND, want);
1951 }
1952
VerifySupportForContinuation()1953 bool Ability::VerifySupportForContinuation()
1954 {
1955 if (continuationManager_ == nullptr) {
1956 HILOG_ERROR("Ability::VerifySupportForContinuation failed. continuationManager_ is nullptr");
1957 return false;
1958 }
1959 return true;
1960 }
1961
HandleCreateAsContinuation(const Want & want)1962 void Ability::HandleCreateAsContinuation(const Want &want)
1963 {
1964 if (!IsFlagExists(Want::FLAG_ABILITY_CONTINUATION, want.GetFlags())) {
1965 HILOG_INFO("Ability::HandleCreateAsContinuation return. This not continuated ability");
1966 return;
1967 }
1968
1969 // check whether it needs reversible
1970 bool reversible = false;
1971 reversible = IsFlagExists(Want::FLAG_ABILITY_CONTINUATION_REVERSIBLE, want.GetFlags());
1972 if (!VerifySupportForContinuation()) {
1973 HILOG_ERROR("Ability::HandleCreateAsContinuation failed. VerifySupportForContinuation failed");
1974 return;
1975 }
1976 bool success = continuationManager_->RestoreData(
1977 want.GetParams(), reversible, want.GetStringParam(ContinuationHandler::ORIGINAL_DEVICE_ID));
1978
1979 if (success && reversible) {
1980 // Register this ability to receive reverse continuation callback.
1981 std::weak_ptr<IReverseContinuationSchedulerReplicaHandler> ReplicaHandler = continuationHandler_;
1982 reverseContinuationSchedulerReplica_ = sptr<ReverseContinuationSchedulerReplica>(
1983 new (std::nothrow) ReverseContinuationSchedulerReplica(handler_, ReplicaHandler));
1984
1985 if (reverseContinuationSchedulerReplica_ == nullptr) {
1986 HILOG_ERROR(
1987 "Ability::HandleCreateAsContinuation failed, create reverseContinuationSchedulerReplica failed");
1988 return;
1989 }
1990 }
1991
1992 int sessionId = want.GetIntParam(DMS_SESSION_ID, DEFAULT_DMS_SESSION_ID);
1993 std::string originDeviceId = want.GetStringParam(DMS_ORIGIN_DEVICE_ID);
1994 HILOG_ERROR("Ability::HandleCreateAsContinuationoriginDeviceId: %{public}s", originDeviceId.c_str());
1995 continuationManager_->NotifyCompleteContinuation(
1996 originDeviceId, sessionId, success, reverseContinuationSchedulerReplica_);
1997 }
IsFlagExists(unsigned int flag,unsigned int flagSet)1998 bool Ability::IsFlagExists(unsigned int flag, unsigned int flagSet)
1999 {
2000 return (flag & flagSet) == flag;
2001 }
2002
2003 #ifdef SUPPORT_GRAPHICS
2004 /**
2005 * @brief Called when this ability gains or loses window focus.
2006 *
2007 * @param hasFocus Specifies whether this ability has focus.
2008 */
OnWindowFocusChanged(bool hasFocus)2009 void Ability::OnWindowFocusChanged(bool hasFocus)
2010 {}
2011
2012 /**
2013 * @brief Called when this ability is moved to or removed from the top of the stack.
2014 *
2015 * @param topActive Specifies whether this ability is moved to or removed from the top of the stack. The value true
2016 * indicates that it is moved to the top, and false indicates that it is removed from the top of the stack.
2017 */
OnTopActiveAbilityChanged(bool topActive)2018 void Ability::OnTopActiveAbilityChanged(bool topActive)
2019 {}
2020 #endif
2021
2022 /**
2023 * @brief Called to set caller information for the application. The default implementation returns null.
2024 *
2025 * @return Returns the caller information.
2026 */
OnSetCaller()2027 Uri Ability::OnSetCaller()
2028 {
2029 return Uri("");
2030 }
2031
2032 /**
2033 * @brief Call this when your ability should be closed and the mission should be completely removed as a part of
2034 * finishing the root ability of the mission.
2035 */
TerminateAndRemoveMission()2036 void Ability::TerminateAndRemoveMission()
2037 {
2038 HILOG_INFO("%{public}s begin.", __func__);
2039 auto state = GetState();
2040 if (state > AbilityLifecycleExecutor::LifecycleState::INITIAL) {
2041 HILOG_INFO("Ability::TerminateAndRemoveMission the GetState retval is %d", state);
2042 return;
2043 }
2044 AbilityContext::TerminateAndRemoveMission();
2045 HILOG_INFO("%{public}s end.", __func__);
2046 }
2047
2048 /**
2049 * @brief Create a PostEvent timeout task. The default delay is 5000ms
2050 *
2051 * @return Return a smart pointer to a timeout object
2052 */
CreatePostEventTimeouter(std::string taskstr)2053 std::shared_ptr<AbilityPostEventTimeout> Ability::CreatePostEventTimeouter(std::string taskstr)
2054 {
2055 return std::make_shared<AbilityPostEventTimeout>(taskstr, handler_);
2056 }
2057
2058 #ifdef SUPPORT_GRAPHICS
2059 /**
2060 * Releases an obtained form by its ID.
2061 *
2062 * <p>After this method is called, the form won't be available for use by the application, but the Form Manager
2063 * Service still keeps the cache information about the form, so that the application can quickly obtain it based on
2064 * the {@code formId}.</p>
2065 * <p><b>Permission: </b>{@link ohos.security.SystemPermission#REQUIRE_FORM}</p>
2066 *
2067 * @param formId Indicates the form ID.
2068 * @return Returns {@code true} if the form is successfully released; returns {@code false} otherwise.
2069 *
2070 * <ul>
2071 * <li>The passed {@code formId} is invalid. Its value must be larger than 0.</li>
2072 * <li>The specified form has not been added by the application.</li>
2073 * <li>An error occurred when connecting to the Form Manager Service.</li>
2074 * <li>The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.</li>
2075 * <li>The form has been obtained by another application and cannot be released by the current application.</li>
2076 * <li>The form is being restored.</li>
2077 * </ul>
2078 */
ReleaseForm(const int64_t formId)2079 ErrCode Ability::ReleaseForm(const int64_t formId)
2080 {
2081 HILOG_INFO("%{public}s called.", __func__);
2082 // release form by formId and do not release cache
2083 return ReleaseForm(formId, false);
2084 }
2085
2086 /**
2087 * Releases an obtained form by its ID.
2088 *
2089 * <p>After this method is called, the form won't be available for use by the application, if isReleaseCache is
2090 * false, this method is same as {@link #releaseForm(int)}, otherwise the Form Manager Service still store this
2091 * form in the cache.</p>
2092 * <p><b>Permission: </b>{@link ohos.security.SystemPermission#REQUIRE_FORM}</p>
2093 *
2094 * @param formId Indicates the form ID.
2095 * @param isReleaseCache Indicates whether to clear cache in service.
2096 * @return Returns {@code true} if the form is successfully released; returns {@code false} otherwise.
2097 *
2098 * <ul>
2099 * <li>The passed {@code formId} is invalid. Its value must be larger than 0.</li>
2100 * <li>The specified form has not been added by the application.</li>
2101 * <li>An error occurred when connecting to the Form Manager Service.</li>
2102 * <li>The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.</li>
2103 * <li>The form has been obtained by another application and cannot be released by the current application.</li>
2104 * <li>The form is being restored.</li>
2105 * </ul>
2106 */
ReleaseForm(const int64_t formId,const bool isReleaseCache)2107 ErrCode Ability::ReleaseForm(const int64_t formId, const bool isReleaseCache)
2108 {
2109 HILOG_INFO("%{public}s called.", __func__);
2110 // release form with formId and specifies whether to release the cache
2111 return DeleteForm(formId, isReleaseCache ? RELEASE_CACHED_FORM : RELEASE_FORM);
2112 }
2113
2114 /**
2115 * Deletes an obtained form by its ID.
2116 *
2117 * <p>After this method is called, the form won't be available for use by the application and the Form Manager
2118 * Service no longer keeps the cache information about the form.</p>
2119 * <p><b>Permission: </b>{@link ohos.security.SystemPermission#REQUIRE_FORM}</p>
2120 *
2121 * @param formId Indicates the form ID.
2122 * @return Returns {@code true} if the form is successfully deleted; returns {@code false} otherwise.
2123 *
2124 * <ul>
2125 * <li>The passed {@code formId} is invalid. Its value must be larger than 0.</li>
2126 * <li>The specified form has not been added by the application.</li>
2127 * <li>An error occurred when connecting to the Form Manager Service.</li>
2128 * <li>The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.</li>
2129 * <li>The form has been obtained by another application and cannot be deleted by the current application.</li>
2130 * <li>The form is being restored.</li>
2131 * </ul>
2132 */
DeleteForm(const int64_t formId)2133 ErrCode Ability::DeleteForm(const int64_t formId)
2134 {
2135 HILOG_INFO("%{public}s called.", __func__);
2136 // delete form with formId
2137 return DeleteForm(formId, DELETE_FORM);
2138 }
2139 #endif
2140
2141 /**
2142 * @brief Keep this Service ability in the background and displays a notification bar.
2143 *
2144 * @param wantAgent Indicates which ability to start when user click the notification bar.
2145 * @return the method result code, 0 means succeed
2146 */
StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent & wantAgent)2147 int Ability::StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent &wantAgent)
2148 {
2149 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2150 uint32_t defaultBgMode = 0;
2151 BackgroundTaskMgr::ContinuousTaskParam taskParam = BackgroundTaskMgr::ContinuousTaskParam(false, defaultBgMode,
2152 std::make_shared<AbilityRuntime::WantAgent::WantAgent>(wantAgent), abilityInfo_->name, GetToken());
2153 return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam);
2154 #else
2155 return ERR_INVALID_OPERATION;
2156 #endif
2157 }
2158
2159 /**
2160 * @brief Cancel background running of this ability to free up system memory.
2161 *
2162 * @return the method result code, 0 means succeed
2163 */
StopBackgroundRunning()2164 int Ability::StopBackgroundRunning()
2165 {
2166 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2167 return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStopBackgroundRunning(abilityInfo_->name, GetToken());
2168 #else
2169 return ERR_INVALID_OPERATION;
2170 #endif
2171 }
2172
2173 #ifdef SUPPORT_GRAPHICS
2174 /**
2175 * @brief Cast temp form with formId.
2176 *
2177 * @param formId Indicates the form's ID.
2178 *
2179 * @return Returns {@code true} if the form is successfully casted; returns {@code false} otherwise.
2180 */
CastTempForm(const int64_t formId)2181 ErrCode Ability::CastTempForm(const int64_t formId)
2182 {
2183 HILOG_INFO("%{public}s start", __func__);
2184 if (formId <= 0) {
2185 HILOG_ERROR("%{public}s error, passing in form id can't be negative.", __func__);
2186 return ERR_APPEXECFWK_FORM_INVALID_FORM_ID;
2187 }
2188
2189 HILOG_INFO("%{public}s, castTempForm begin of temp form %{public}" PRId64, __func__, formId);
2190 ErrCode result = FormMgr::GetInstance().CastTempForm(formId, FormHostClient::GetInstance());
2191
2192 if (result != ERR_OK) {
2193 HILOG_ERROR("%{public}s error, some internal server occurs, error code is %{public}d.", __func__, result);
2194 return result;
2195 }
2196
2197 userReqParams_[formId].SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false);
2198
2199 HILOG_INFO("%{public}s end", __func__);
2200 return result;
2201 }
2202
2203 /**
2204 * @brief Obtains a specified form that matches the application bundle name, module name, form name, and
2205 * other related information specified in the passed {@code Want}.
2206 *
2207 * <p>This method is asynchronous. After the {@link FormJsInfo} instance is obtained.
2208 *
2209 * @param formId Indicates the form ID.
2210 * @param want Indicates the detailed information about the form to be obtained, including the bundle name,
2211 * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data.
2212 * @param callback Indicates the callback to be invoked whenever the {@link FormJsInfo} instance is obtained.
2213 * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise.
2214 */
AcquireForm(const int64_t formId,const Want & want,const std::shared_ptr<FormCallback> callback)2215 bool Ability::AcquireForm(const int64_t formId, const Want &want, const std::shared_ptr<FormCallback> callback)
2216 {
2217 HILOG_INFO("%{public}s called.", __func__);
2218 struct timespec ts;
2219 clock_gettime(CLOCK_REALTIME, &ts);
2220 long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC;
2221 HILOG_INFO("%{public}s begin, current time: %{public}ld", __func__, currentTime);
2222
2223 // check fms recover status
2224 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
2225 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
2226 return false;
2227 }
2228
2229 // check form id
2230 HILOG_DEBUG("%{public}s, param of formId %{public}" PRId64 ".", __func__, formId);
2231 if (formId < 0) {
2232 HILOG_ERROR("%{public}s error, form id should not be negative.", __func__);
2233 return false;
2234 }
2235
2236 // check param of want
2237 if (!CheckWantValid(formId, want)) {
2238 HILOG_ERROR("%{public}s error, failed to check param of want.", __func__);
2239 return false;
2240 };
2241
2242 ElementName elementName = want.GetElement();
2243 std::string bundleName = elementName.GetBundleName();
2244 std::string abilityName = elementName.GetAbilityName();
2245 HILOG_INFO("%{public}s, begin to acquire form, bundleName is %{public}s, abilityName is %{public}s, formId is "
2246 "%{public}" PRId64 ".",
2247 __func__,
2248 bundleName.c_str(),
2249 abilityName.c_str(),
2250 formId);
2251
2252 // hostClient init
2253 sptr<FormHostClient> formHostClient = FormHostClient::GetInstance();
2254 if (formHostClient == nullptr) {
2255 HILOG_ERROR("%{public}s error, formHostClient == nullptr.", __func__);
2256 return false;
2257 }
2258
2259 // acquire form request to fms
2260 FormJsInfo formJsInfo;
2261 if (FormMgr::GetInstance().AddForm(formId, want, formHostClient, formJsInfo) != ERR_OK) {
2262 HILOG_ERROR("%{public}s error, acquire form for fms failed.", __func__);
2263 return false;
2264 }
2265 HILOG_INFO("%{public}s, end to acquire form, the formId returned from the fms is %{public}" PRId64 ".",
2266 __func__,
2267 formJsInfo.formId);
2268
2269 // check for form presence in hostForms
2270 if (formHostClient->ContainsForm(formJsInfo.formId)) {
2271 HILOG_ERROR("%{public}s error, form has already acquired, do not support acquire twice.", __func__);
2272 return false;
2273 }
2274
2275 // add ability of form to hostForms
2276 std::shared_ptr<Ability> thisAbility = this->shared_from_this();
2277 formHostClient->AddForm(thisAbility, formJsInfo.formId);
2278 // post the async task of handleAcquireResult
2279 PostTask([this, want, formJsInfo, callback]() { HandleAcquireResult(want, formJsInfo, callback); }, 0L);
2280 // the acquire form is successfully
2281 return true;
2282 }
2283
2284 /**
2285 * @brief Updates the content of a specified JS form.
2286 *
2287 * <p>This method is called by a form provider to update JS form data as needed.
2288 *
2289 * @param formId Indicates the form ID.
2290 * @param formProviderData The data used to update the JS form displayed on the client.
2291 * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise.
2292 */
UpdateForm(const int64_t formId,const FormProviderData & formProviderData)2293 ErrCode Ability::UpdateForm(const int64_t formId, const FormProviderData &formProviderData)
2294 {
2295 HILOG_INFO("%{public}s called.", __func__);
2296 // check fms recover status
2297 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
2298 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
2299 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
2300 }
2301
2302 // check formId
2303 if (formId <= 0) {
2304 HILOG_ERROR("%{public}s error, the passed in formId can't be negative or zero.", __func__);
2305 return ERR_APPEXECFWK_FORM_INVALID_FORM_ID;
2306 }
2307
2308 // check formProviderData
2309 if (formProviderData.GetDataString().empty()) {
2310 HILOG_ERROR("%{public}s error, the formProviderData is null.", __func__);
2311 return ERR_APPEXECFWK_FORM_PROVIDER_DATA_EMPTY;
2312 }
2313
2314 // update form request to fms
2315 ErrCode result = FormMgr::GetInstance().UpdateForm(formId, formProviderData);
2316 if (result != ERR_OK) {
2317 HILOG_ERROR("%{public}s error, update form for fms failed.", __func__);
2318 }
2319 return result;
2320 }
2321
2322 /**
2323 * @brief Sends a notification to the form framework to make the specified forms visible.
2324 *
2325 * <p>After this method is successfully called, {@link Ability#OnVisibilityChanged(std::map<int64_t, int>)}
2326 * will be called to notify the form provider of the form visibility change event.</p>
2327 *
2328 * @param formIds Indicates the IDs of the forms to be made visible.
2329 * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise.
2330 */
NotifyVisibleForms(const std::vector<int64_t> & formIds)2331 ErrCode Ability::NotifyVisibleForms(const std::vector<int64_t> &formIds)
2332 {
2333 HILOG_INFO("%{public}s called.", __func__);
2334 return NotifyWhetherVisibleForms(formIds, Constants::FORM_VISIBLE);
2335 }
2336
2337 /**
2338 * @brief Sends a notification to the form framework to make the specified forms invisible.
2339 *
2340 * <p>After this method is successfully called, {@link Ability#OnVisibilityChanged(std::map<int64_t, int>)}
2341 * will be called to notify the form provider of the form visibility change event.</p>
2342 *
2343 * @param formIds Indicates the IDs of the forms to be made invisible.
2344 * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise.
2345 */
NotifyInvisibleForms(const std::vector<int64_t> & formIds)2346 ErrCode Ability::NotifyInvisibleForms(const std::vector<int64_t> &formIds)
2347 {
2348 HILOG_INFO("%{public}s called.", __func__);
2349 return NotifyWhetherVisibleForms(formIds, Constants::FORM_INVISIBLE);
2350 }
2351
2352 /**
2353 * @brief Set form next refresh time.
2354 *
2355 * <p>This method is called by a form provider to set refresh time.
2356 *
2357 * @param formId Indicates the ID of the form to set refresh time.
2358 * @param nextTime Indicates the next time gap now in seconds, can not be litter than 300 seconds.
2359 * @return Returns {@code true} if seting succeed; returns {@code false} otherwise.
2360 */
SetFormNextRefreshTime(const int64_t formId,const int64_t nextTime)2361 ErrCode Ability::SetFormNextRefreshTime(const int64_t formId, const int64_t nextTime)
2362 {
2363 HILOG_INFO("%{public}s called.", __func__);
2364 if (nextTime < MIN_NEXT_TIME) {
2365 HILOG_ERROR("next time litte than 300 seconds.");
2366 return ERR_APPEXECFWK_FORM_INVALID_REFRESH_TIME;
2367 }
2368
2369 if (FormMgr::GetInstance().GetRecoverStatus() == Constants::IN_RECOVERING) {
2370 HILOG_ERROR("%{public}s, formManager is in recovering", __func__);
2371 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
2372 }
2373
2374 ErrCode result = FormMgr::GetInstance().SetNextRefreshTime(formId, nextTime);
2375 if (result != ERR_OK) {
2376 HILOG_ERROR("%{public}s, internal error:[%{public}d]", __func__, result);
2377 }
2378
2379 return result;
2380 }
2381 /**
2382 * @brief Requests for form data update.
2383 *
2384 * This method must be called when the application has detected that a system setting item (such as the language,
2385 * resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form
2386 * provider automatically updates the form data (if there is any update) through the form framework, with the update
2387 * process being unperceivable by the application.
2388 *
2389 * @param formId Indicates the ID of the form to update.
2390 * @return Returns true if the update request is successfully initiated, returns false otherwise.
2391 */
RequestForm(const int64_t formId)2392 ErrCode Ability::RequestForm(const int64_t formId)
2393 {
2394 HILOG_INFO("%{public}s called.", __func__);
2395 Want want;
2396 return RequestForm(formId, want);
2397 }
2398
2399 /**
2400 * @brief Update form.
2401 *
2402 * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance.
2403 */
ProcessFormUpdate(const FormJsInfo & formJsInfo)2404 void Ability::ProcessFormUpdate(const FormJsInfo &formJsInfo)
2405 {
2406 HILOG_INFO("%{public}s called.", __func__);
2407 // post the async task of handleFormMessage
2408 int32_t msgCode = OHOS_FORM_UPDATE_FORM;
2409 PostTask([this, msgCode, formJsInfo]() { HandleFormMessage(msgCode, formJsInfo); }, 0L);
2410 }
2411 /**
2412 * @brief Uninstall form.
2413 *
2414 * @param formId Indicates the ID of the form to uninstall.
2415 */
ProcessFormUninstall(const int64_t formId)2416 void Ability::ProcessFormUninstall(const int64_t formId)
2417 {
2418 HILOG_INFO("%{public}s start.", __func__);
2419 // check formId
2420 if (formId <= 0) {
2421 HILOG_ERROR("%{public}s error, the passed in formId can't be negative or zero.", __func__);
2422 return;
2423 }
2424
2425 std::shared_ptr<FormCallback> formCallback = nullptr;
2426 {
2427 std::lock_guard<std::mutex> lock(formLock);
2428 // get callback iterator by formId
2429 std::map<int64_t, std::shared_ptr<FormCallback>>::iterator appCallbackIterator = appCallbacks_.find(formId);
2430
2431 // call the callback function when you need to be notified
2432 if (appCallbackIterator == appCallbacks_.end()) {
2433 HILOG_ERROR("%{public}s failed, callback not find, formId: %{public}" PRId64 ".", __func__, formId);
2434 return;
2435 }
2436 formCallback = appCallbackIterator->second;
2437 CleanFormResource(formId);
2438 }
2439 if (formCallback == nullptr) {
2440 HILOG_ERROR("%{public}s failed, callback is nullptr.", __func__);
2441 return;
2442 }
2443
2444 formCallback->OnFormUninstall(formId);
2445
2446 HILOG_INFO("%{public}s end.", __func__);
2447 }
2448
2449 /**
2450 * @brief Called to return a FormProviderInfo object.
2451 *
2452 * <p>You must override this method if your ability will serve as a form provider to provide a form for clients.
2453 * The default implementation returns nullptr. </p>
2454 *
2455 * @param want Indicates the detailed information for creating a FormProviderInfo.
2456 * The Want object must include the form ID, form name of the form,
2457 * which can be obtained from Ability#PARAM_FORM_IDENTITY_KEY,
2458 * Ability#PARAM_FORM_NAME_KEY, and Ability#PARAM_FORM_DIMENSION_KEY,
2459 * respectively. Such form information must be managed as persistent data for further form
2460 * acquisition, update, and deletion.
2461 *
2462 * @return Returns the created FormProviderInfo object.
2463 */
OnCreate(const Want & want)2464 FormProviderInfo Ability::OnCreate(const Want &want)
2465 {
2466 HILOG_INFO("%{public}s called.", __func__);
2467 FormProviderInfo formProviderInfo;
2468 return formProviderInfo;
2469 }
2470
2471 /**
2472 * @brief Called to notify the form provider that a specified form has been deleted. Override this method if
2473 * you want your application, as the form provider, to be notified of form deletion.
2474 *
2475 * @param formId Indicates the ID of the deleted form.
2476 * @return None.
2477 */
OnDelete(const int64_t formId)2478 void Ability::OnDelete(const int64_t formId)
2479 {}
2480
2481 /**
2482 * @brief Called to notify the form provider to update a specified form.
2483 *
2484 * @param formId Indicates the ID of the form to update.
2485 * @return none.
2486 */
OnUpdate(const int64_t formId)2487 void Ability::OnUpdate(const int64_t formId)
2488 {}
2489
2490 /**
2491 * @brief Called when the form supplier is notified that a temporary form is successfully converted to a normal
2492 * form.
2493 *
2494 * @param formId Indicates the ID of the form.
2495 * @return None.
2496 */
OnCastTemptoNormal(const int64_t formId)2497 void Ability::OnCastTemptoNormal(const int64_t formId)
2498 {}
2499
2500 /**
2501 * @brief Called when the form supplier receives form events from the fms.
2502 *
2503 * @param formEventsMap Indicates the form events occurred. The key in the Map object indicates the form ID,
2504 * and the value indicates the event type, which can be either FORM_VISIBLE
2505 * or FORM_INVISIBLE. FORM_VISIBLE means that the form becomes visible,
2506 * and FORM_INVISIBLE means that the form becomes invisible.
2507 * @return none.
2508 */
OnVisibilityChanged(const std::map<int64_t,int32_t> & formEventsMap)2509 void Ability::OnVisibilityChanged(const std::map<int64_t, int32_t> &formEventsMap)
2510 {}
2511 /**
2512 * @brief Called to notify the form supplier to update a specified form.
2513 *
2514 * @param formId Indicates the ID of the form to update.
2515 * @param message Form event message.
2516 */
OnTriggerEvent(const int64_t formId,const std::string & message)2517 void Ability::OnTriggerEvent(const int64_t formId, const std::string &message)
2518 {}
2519
2520 /**
2521 * @brief Called to notify the form supplier to acquire form state.
2522 *
2523 * @param want Indicates the detailed information about the form to be obtained, including
2524 * the bundle name, module name, ability name, form name and form dimension.
2525 */
OnAcquireFormState(const Want & want)2526 FormState Ability::OnAcquireFormState(const Want &want)
2527 {
2528 return FormState::DEFAULT;
2529 }
2530 /**
2531 * @brief Delete or release form with formId.
2532 *
2533 * @param formId Indicates the form's ID.
2534 * @param deleteType Indicates the type of delete or release.
2535 * @return Returns {@code true} if the form is successfully deleted; returns {@code false} otherwise.
2536 */
DeleteForm(const int64_t formId,const int32_t deleteType)2537 ErrCode Ability::DeleteForm(const int64_t formId, const int32_t deleteType)
2538 {
2539 HILOG_INFO("%{public}s called.", __func__);
2540 // check fms recover status
2541 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
2542 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
2543 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
2544 }
2545 // check formId
2546 if (formId <= 0) {
2547 HILOG_ERROR("%{public}s error, the passed in formId can't be negative or zero.", __func__);
2548 return ERR_APPEXECFWK_FORM_INVALID_FORM_ID;
2549 }
2550
2551 HILOG_INFO("%{public}s, delete form begin, formId is %{public}" PRId64 " and deleteType is %{public}d.",
2552 __func__,
2553 formId,
2554 deleteType);
2555 {
2556 // form lock
2557 std::lock_guard<std::mutex> lock(formLock);
2558 // clean form resource when form is temp form
2559 if (std::find(lostedByReconnectTempForms_.begin(), lostedByReconnectTempForms_.end(), formId) !=
2560 lostedByReconnectTempForms_.end()) {
2561 CleanFormResource(formId);
2562 // the delete temp form is successfully
2563 return ERR_OK;
2564 }
2565 }
2566
2567 // hostClient init
2568 sptr<FormHostClient> formHostClient = FormHostClient::GetInstance();
2569 // delete or release request to fms
2570 ErrCode result;
2571 if (deleteType == DELETE_FORM) {
2572 result = FormMgr::GetInstance().DeleteForm(formId, formHostClient);
2573 } else {
2574 result = FormMgr::GetInstance().ReleaseForm(
2575 formId, formHostClient, (deleteType == RELEASE_CACHED_FORM) ? true : false);
2576 }
2577 if (result != ERR_OK) {
2578 HILOG_ERROR("%{public}s error, some internal server occurs, error code is %{public}d.", __func__, result);
2579 return result;
2580 }
2581 {
2582 // form lock
2583 std::lock_guard<std::mutex> lock(formLock);
2584 // clean form resource
2585 CleanFormResource(formId);
2586 }
2587 // the delete form is successfully
2588 return result;
2589 }
2590
2591 /**
2592 * @brief Clean form resource with formId.
2593 *
2594 * @param formId Indicates the form's ID.
2595 */
CleanFormResource(const int64_t formId)2596 void Ability::CleanFormResource(const int64_t formId)
2597 {
2598 HILOG_INFO("%{public}s called.", __func__);
2599 // compatible with int form id
2600 int64_t cleanId {-1L};
2601 for (auto param : userReqParams_) {
2602 uint64_t unsignedFormId = static_cast<uint64_t>(formId);
2603 uint64_t unsignedParamFirst = static_cast<uint64_t>(param.first);
2604 if ((unsignedParamFirst & 0x00000000ffffffffL) == (unsignedFormId & 0x00000000ffffffffL)) {
2605 cleanId = param.first;
2606 break;
2607 }
2608 }
2609 if (cleanId == -1L) {
2610 return;
2611 }
2612
2613 HILOG_DEBUG("%{public}s. clean id is %{public}" PRId64 ".", __func__, cleanId);
2614 // remove wantParam, callback and lostedByReconnectTempForms
2615 appCallbacks_.erase(cleanId);
2616 userReqParams_.erase(cleanId);
2617 auto tempForm = std::find(lostedByReconnectTempForms_.begin(), lostedByReconnectTempForms_.end(), cleanId);
2618 if (tempForm != lostedByReconnectTempForms_.end()) {
2619 lostedByReconnectTempForms_.erase(tempForm);
2620 }
2621
2622 // remove ability
2623 std::shared_ptr<Ability> thisAbility = this->shared_from_this();
2624 FormHostClient::GetInstance()->RemoveForm(thisAbility, cleanId);
2625
2626 // unregister death callback when appCallbacks is empty
2627 if (appCallbacks_.empty()) {
2628 std::shared_ptr<Ability> thisAbility = this->shared_from_this();
2629 FormMgr::GetInstance().UnRegisterDeathCallback(thisAbility);
2630 }
2631 HILOG_INFO("%{public}s end.", __func__);
2632 }
2633
2634 /**
2635 * @brief Handle acquire result of the obtained form instance.
2636 *
2637 * @param want Indicates the detailed information about the form to be obtained, including the bundle name,
2638 * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data.
2639 * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance.
2640 * @param callback Indicates the callback to be invoked whenever the {@link FormJsInfo} instance is obtained.
2641 */
HandleAcquireResult(const Want & want,const FormJsInfo & formJsInfo,const std::shared_ptr<FormCallback> callback)2642 void Ability::HandleAcquireResult(
2643 const Want &want, const FormJsInfo &formJsInfo, const std::shared_ptr<FormCallback> callback)
2644 {
2645 HILOG_INFO("%{public}s called.", __func__);
2646 {
2647 // form lock
2648 std::lock_guard<std::mutex> lock(formLock);
2649
2650 // register death when userReqParams is empty
2651 if (userReqParams_.empty()) {
2652 std::shared_ptr<Ability> thisAbility = this->shared_from_this();
2653 FormMgr::GetInstance().RegisterDeathCallback(thisAbility);
2654 }
2655
2656 // save wantParam and callback
2657 userReqParams_.insert(std::make_pair(formJsInfo.formId, want));
2658 appCallbacks_.insert(std::make_pair(formJsInfo.formId, callback));
2659 }
2660
2661 struct timespec ts;
2662 clock_gettime(CLOCK_REALTIME, &ts);
2663 long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC;
2664 HILOG_INFO("%{public}s, AcquireForm end, current time: %{public}ld", __func__, currentTime);
2665
2666 // handle acquire message of the obtained form instance
2667 callback->OnAcquired(FormCallback::OHOS_FORM_ACQUIRE_SUCCESS, formJsInfo);
2668 }
2669
2670 /**
2671 * @brief Handle acquire message of the obtained form instance.
2672 *
2673 * @param msgCode Indicates the code of message type.
2674 * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance.
2675 */
HandleFormMessage(const int32_t msgCode,const FormJsInfo & formJsInfo)2676 void Ability::HandleFormMessage(const int32_t msgCode, const FormJsInfo &formJsInfo)
2677 {
2678 HILOG_INFO("%{public}s called.", __func__);
2679 std::shared_ptr<FormCallback> formCallback = nullptr;
2680 {
2681 std::lock_guard<std::mutex> lock(formLock);
2682 // get callback iterator by formId
2683 std::map<int64_t, std::shared_ptr<FormCallback>>::iterator appCallbackIterator =
2684 appCallbacks_.find(formJsInfo.formId);
2685
2686 // call the callback function when you need to be notified
2687 if (appCallbackIterator == appCallbacks_.end()) {
2688 HILOG_ERROR(
2689 "%{public}s failed, callback not find, formId: %{public}" PRId64 ".", __func__, formJsInfo.formId);
2690 return;
2691 }
2692 formCallback = appCallbackIterator->second;
2693 }
2694 if (formCallback == nullptr) {
2695 HILOG_ERROR("%{public}s failed, callback is nullptr.", __func__);
2696 return;
2697 }
2698
2699 HILOG_INFO("%{public}s, call user implement of form %{public}" PRId64 ".", __func__, formJsInfo.formId);
2700
2701 if (msgCode == OHOS_FORM_ACQUIRE_FORM) {
2702 formCallback->OnAcquired(FormCallback::OHOS_FORM_ACQUIRE_SUCCESS, formJsInfo);
2703 } else {
2704 formCallback->OnUpdate(FormCallback::OHOS_FORM_UPDATE_SUCCESS, formJsInfo);
2705 }
2706 }
2707
2708 /**
2709 * @brief Notify the forms visibility change event.
2710 *
2711 * @param formIds Indicates the IDs of the forms to be made visible or invisible.
2712 * @param eventType Indicates the form events occurred. FORM_VISIBLE means that the form becomes visible,
2713 * and FORM_INVISIBLE means that the form becomes invisible.
2714 * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise.
2715 */
NotifyWhetherVisibleForms(const std::vector<int64_t> & formIds,int32_t eventType)2716 ErrCode Ability::NotifyWhetherVisibleForms(const std::vector<int64_t> &formIds, int32_t eventType)
2717 {
2718 HILOG_INFO("%{public}s called.", __func__);
2719 if (formIds.empty() || formIds.size() > Constants::MAX_VISIBLE_NOTIFY_LIST) {
2720 HILOG_ERROR("%{public}s, formIds is empty or exceed 32.", __func__);
2721 return ERR_APPEXECFWK_FORM_INVALID_FORM_ID;
2722 }
2723
2724 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
2725 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
2726 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
2727 }
2728
2729 ErrCode resultCode =
2730 FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, FormHostClient::GetInstance(), eventType);
2731 if (resultCode != ERR_OK) {
2732 HILOG_ERROR("%{public}s error, internal error occurs, error code:%{public}d.", __func__, resultCode);
2733 }
2734 return resultCode;
2735 }
2736
2737 /**
2738 * @brief Check the param of want.
2739 *
2740 * @param formId Indicates the form's ID.
2741 * @param want Indicates the detailed information about the form to be obtained, including the bundle name,
2742 * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data.
2743 * @return Returns {@code true} if the check result is ok; returns {@code false} ng.
2744 */
CheckWantValid(const int64_t formId,const Want & want)2745 bool Ability::CheckWantValid(const int64_t formId, const Want &want)
2746 {
2747 HILOG_INFO("%{public}s called.", __func__);
2748 // get want parameters
2749 int32_t formDimension = want.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, 1);
2750 std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
2751
2752 ElementName elementName = want.GetElement();
2753 std::string bundleName = elementName.GetBundleName();
2754 std::string abilityName = elementName.GetAbilityName();
2755
2756 bool tempFormFlg = want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false);
2757
2758 HILOG_DEBUG("%{public}s, param of formDimension %{public}d in want.", __func__, formDimension);
2759 HILOG_DEBUG("%{public}s, param of moduleName %{public}s in want.", __func__, moduleName.c_str());
2760 HILOG_DEBUG("%{public}s, param of bundleName %{public}s in want.", __func__, bundleName.c_str());
2761 HILOG_DEBUG("%{public}s, param of abilityName %{public}s in want.", __func__, abilityName.c_str());
2762 HILOG_DEBUG("%{public}s, param of tempFormFlg %{public}d in want.", __func__, tempFormFlg);
2763
2764 // check want parameters
2765 if (bundleName.empty() || abilityName.empty() || moduleName.empty()) {
2766 HILOG_ERROR("%{public}s error, bundleName or abilityName or moduleName is not set in want.", __func__);
2767 return false;
2768 }
2769 if (FormHostClient::GetInstance()->ContainsForm(formId)) {
2770 HILOG_ERROR("%{public}s error, form has already acquired, do not support acquire twice.", __func__);
2771 return false;
2772 }
2773 if (formDimension <= 0) {
2774 HILOG_ERROR("%{public}s error, dimension should not be zero or negative in want.", __func__);
2775 return false;
2776 }
2777 if (tempFormFlg && formId != 0) {
2778 HILOG_ERROR("%{public}s error, can not select form id when acquire temporary form.", __func__);
2779 return false;
2780 }
2781
2782 // the check is successfully
2783 return true;
2784 }
2785
2786 /**
2787 * @brief Enable form update.
2788 *
2789 * @param formIds FormIds of hostclient.
2790 */
EnableUpdateForm(const std::vector<int64_t> & formIds)2791 ErrCode Ability::EnableUpdateForm(const std::vector<int64_t> &formIds)
2792 {
2793 HILOG_INFO("%{public}s called.", __func__);
2794 return LifecycleUpdate(formIds, ENABLE_FORM_UPDATE);
2795 }
2796
2797 /**
2798 * @brief Disable form update.
2799 *
2800 * @param formIds FormIds of hostclient.
2801 */
DisableUpdateForm(const std::vector<int64_t> & formIds)2802 ErrCode Ability::DisableUpdateForm(const std::vector<int64_t> &formIds)
2803 {
2804 HILOG_INFO("%{public}s called.", __func__);
2805 return LifecycleUpdate(formIds, DISABLE_FORM_UPDATE);
2806 }
2807
LifecycleUpdate(std::vector<int64_t> formIds,int32_t updateType)2808 ErrCode Ability::LifecycleUpdate(std::vector<int64_t> formIds, int32_t updateType)
2809 {
2810 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
2811 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
2812 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
2813 }
2814
2815 // hostClient init
2816 sptr<FormHostClient> formHostClient = FormHostClient::GetInstance();
2817 if (formHostClient == nullptr) {
2818 HILOG_ERROR("%{public}s error, formHostClient == nullptr.", __func__);
2819 return ERR_APPEXECFWK_FORM_GET_HOST_FAILED;
2820 }
2821
2822 return FormMgr::GetInstance().LifecycleUpdate(formIds, formHostClient, updateType);
2823 }
2824
2825 /**
2826 * @brief Requests for form data update, by passing a set of parameters (using Want) to the form provider.
2827 *
2828 * This method must be called when the application has detected that a system setting item (such as the language,
2829 * resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form
2830 * supplier automatically updates the form data (if there is any update) through the form framework, with the update
2831 * process being unperceivable by the application.
2832 *
2833 * @param formId Indicates the ID of the form to update.
2834 * @param want Indicates a set of parameters to be transparently passed to the form provider.
2835 * @return Returns true if the update request is successfully initiated, returns false otherwise.
2836 */
RequestForm(const int64_t formId,const Want & want)2837 ErrCode Ability::RequestForm(const int64_t formId, const Want &want)
2838 {
2839 HILOG_INFO("%{public}s called.", __func__);
2840 if (formId <= 0) {
2841 HILOG_ERROR("%{public}s error, The passed formid is invalid. Its value must be larger than 0.", __func__);
2842 return ERR_APPEXECFWK_FORM_INVALID_FORM_ID;
2843 }
2844
2845 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
2846 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
2847 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
2848 }
2849
2850 // requestForm request to fms
2851 ErrCode resultCode = FormMgr::GetInstance().RequestForm(formId, FormHostClient::GetInstance(), want);
2852 if (resultCode != ERR_OK) {
2853 HILOG_ERROR(
2854 "%{public}s error, failed to notify the form service that the form user's lifecycle is updated, error "
2855 "code is %{public}d.",
2856 __func__,
2857 resultCode);
2858 }
2859 return resultCode;
2860 }
2861
2862 /**
2863 * @brief Called to reacquire form and update the form host after the death callback is received.
2864 *
2865 */
OnDeathReceived()2866 void Ability::OnDeathReceived()
2867 {
2868 HILOG_INFO("%{public}s called.", __func__);
2869 int64_t formId;
2870 std::map<int64_t, Want> &userReqParams = userReqParams_;
2871 std::vector<int64_t> &lostedTempForms = lostedByReconnectTempForms_;
2872 for (const auto &userReqRaram : userReqParams) {
2873 formId = userReqRaram.first;
2874 Want want;
2875 {
2876 std::lock_guard<std::mutex> lock(formLock);
2877 want = userReqRaram.second;
2878 if (want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false) &&
2879 std::find(lostedTempForms.begin(), lostedTempForms.end(), formId) == lostedTempForms.end()) {
2880 lostedTempForms.emplace_back(formId);
2881 continue;
2882 }
2883 }
2884
2885 bool result = ReAcquireForm(formId, want);
2886 if (!result) {
2887 HILOG_INFO("%{public}s error, reacquire form failed, formId:%{public}" PRId64 ".", __func__, formId);
2888 std::shared_ptr<FormCallback> formCallback = nullptr;
2889 {
2890 std::lock_guard<std::mutex> lock(formLock);
2891 // get callback iterator by formId
2892 std::map<int64_t, std::shared_ptr<FormCallback>>::iterator appCallbackIterator =
2893 appCallbacks_.find(formId);
2894
2895 if (appCallbackIterator == appCallbacks_.end()) {
2896 HILOG_WARN("%{public}s error, lack of form callback for form, formId:%{public}" PRId64 ".",
2897 __func__,
2898 formId);
2899 continue;
2900 }
2901 formCallback = appCallbackIterator->second;
2902 }
2903 if (formCallback == nullptr) {
2904 HILOG_WARN("%{public}s failed, callback is nullptr.", __func__);
2905 continue;
2906 }
2907
2908 FormJsInfo formJsInfo;
2909 formJsInfo.formId = formId;
2910 formCallback->OnAcquired(FormCallback::OHOS_FORM_RESTORE_FAILURE, formJsInfo);
2911 }
2912 }
2913 }
2914
2915 /**
2916 * @brief Reacquire a specified form when the death callback is received.
2917 *
2918 * @param formId Indicates the form ID.
2919 * @param want Indicates the detailed information about the form to be obtained.
2920 * @return Returns true if the request is successfully initiated; returns false otherwise.
2921 */
ReAcquireForm(const int64_t formId,const Want & want)2922 bool Ability::ReAcquireForm(const int64_t formId, const Want &want)
2923 {
2924 HILOG_INFO("%{public}s called.", __func__);
2925
2926 // get the form host client
2927 sptr<FormHostClient> formHostClient = FormHostClient::GetInstance();
2928 if (formHostClient == nullptr) {
2929 HILOG_ERROR("%{public}s error, formHostClient is nullptr, formId:%{public}" PRId64 ".", __func__, formId);
2930 return false;
2931 }
2932
2933 // reacquire form
2934 FormJsInfo formJsInfo;
2935 if (FormMgr::GetInstance().AddForm(formId, want, formHostClient, formJsInfo) != ERR_OK || formJsInfo.formId <= 0 ||
2936 formJsInfo.formId != formId) {
2937 HILOG_ERROR("%{public}s error, fms reacquire form failed, formId:%{public}" PRId64 ".", __func__, formId);
2938 return false;
2939 }
2940
2941 // handle update message of the obtained form instance.
2942 ProcessFormUpdate(formJsInfo);
2943
2944 return true;
2945 }
2946
2947 /**
2948 * @brief Check form manager service ready.
2949 *
2950 * @return Return true if form manager service ready; returns false otherwise.
2951 */
CheckFMSReady()2952 bool Ability::CheckFMSReady()
2953 {
2954 HILOG_INFO("%{public}s called.", __func__);
2955
2956 sptr<ISystemAbilityManager> systemAbilityManager =
2957 SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2958 auto remoteObject = systemAbilityManager->GetSystemAbility(FORM_MGR_SERVICE_ID);
2959 if (remoteObject == nullptr) {
2960 HILOG_INFO("%{public}s, form manager service is not ready.", __func__);
2961 return false;
2962 }
2963
2964 return true;
2965 }
2966
2967 /**
2968 * @brief Delete the given invalid forms.
2969 *
2970 * @param formIds Indicates the ID of the forms to delete.
2971 * @param numFormsDeleted Returns the number of the deleted forms.
2972 * @return Returns true if the request is successfully initiated; returns false otherwise.
2973 */
DeleteInvalidForms(const std::vector<int64_t> & formIds,int32_t & numFormsDeleted)2974 ErrCode Ability::DeleteInvalidForms(const std::vector<int64_t> &formIds, int32_t &numFormsDeleted)
2975 {
2976 HILOG_INFO("%{public}s called.", __func__);
2977
2978 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
2979 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
2980 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
2981 }
2982
2983 // DeleteInvalidForms request to fms
2984 int resultCode = FormMgr::GetInstance().DeleteInvalidForms(formIds, FormHostClient::GetInstance(), numFormsDeleted);
2985 if (resultCode != ERR_OK) {
2986 HILOG_ERROR("%{public}s error, failed to DeleteInvalidForms, error code is %{public}d.", __func__, resultCode);
2987 }
2988 return resultCode;
2989 }
2990
2991 /**
2992 * @brief Acquire form state info by passing a set of parameters (using Want) to the form provider.
2993 *
2994 * @param want Indicates a set of parameters to be transparently passed to the form provider.
2995 * @param stateInfo Returns the form's state info of the specify.
2996 * @return Returns true if the request is successfully initiated; returns false otherwise.
2997 */
AcquireFormState(const Want & want,FormStateInfo & stateInfo)2998 ErrCode Ability::AcquireFormState(const Want &want, FormStateInfo &stateInfo)
2999 {
3000 HILOG_INFO("%{public}s called.", __func__);
3001
3002 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
3003 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
3004 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
3005 }
3006
3007 // AcquireFormState request to fms
3008 int resultCode = FormMgr::GetInstance().AcquireFormState(want, FormHostClient::GetInstance(), stateInfo);
3009 if (resultCode != ERR_OK) {
3010 HILOG_ERROR("%{public}s error, failed to AcquireFormState, error code is %{public}d.", __func__, resultCode);
3011 }
3012 return resultCode;
3013 }
3014
3015 /**
3016 * @brief Notify the forms is visible to FMS.
3017 *
3018 * @param formIds Indicates the ID of the forms.
3019 * @param isVisible Visible or not.
3020 * @return Returns true if the request is successfully initiated; returns false otherwise.
3021 */
NotifyFormsVisible(const std::vector<int64_t> & formIds,bool isVisible)3022 ErrCode Ability::NotifyFormsVisible(const std::vector<int64_t> &formIds, bool isVisible)
3023 {
3024 HILOG_INFO("%{public}s called.", __func__);
3025
3026 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
3027 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
3028 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
3029 }
3030
3031 // NotifyFormsVisible request to fms
3032 int resultCode = FormMgr::GetInstance().NotifyFormsVisible(formIds, isVisible, FormHostClient::GetInstance());
3033 if (resultCode != ERR_OK) {
3034 HILOG_ERROR("%{public}s error, failed to NotifyFormsVisible, error code is %{public}d.", __func__, resultCode);
3035 }
3036 return resultCode;
3037 }
3038
3039 /**
3040 * @brief Notify the forms is enable update to FMS.
3041 *
3042 * @param formIds Indicates the ID of the forms.
3043 * @param isEnableUpdate enable update or not.
3044 * @return Returns true if the request is successfully initiated; returns false otherwise.
3045 */
NotifyFormsEnableUpdate(const std::vector<int64_t> & formIds,bool isEnableUpdate)3046 ErrCode Ability::NotifyFormsEnableUpdate(const std::vector<int64_t> &formIds, bool isEnableUpdate)
3047 {
3048 HILOG_INFO("%{public}s called.", __func__);
3049
3050 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
3051 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
3052 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
3053 }
3054
3055 // NotifyFormsEnableUpdate request to fms
3056 int resultCode = FormMgr::GetInstance().NotifyFormsEnableUpdate(formIds, isEnableUpdate,
3057 FormHostClient::GetInstance());
3058 if (resultCode != ERR_OK) {
3059 HILOG_ERROR("%{public}s error, failed to NotifyFormsEnableUpdate, error code is %{public}d.", __func__,
3060 resultCode);
3061 }
3062 return resultCode;
3063 }
3064
3065 /**
3066 * @brief Get All FormsInfo.
3067 *
3068 * @param formInfos Return the forms' information of all forms provided.
3069 * @return Return true if the request is successfully initiated; return false otherwise.
3070 */
GetAllFormsInfo(std::vector<FormInfo> & formInfos)3071 ErrCode Ability::GetAllFormsInfo(std::vector<FormInfo> &formInfos)
3072 {
3073 HILOG_INFO("%{public}s called.", __func__);
3074
3075 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
3076 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
3077 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
3078 }
3079
3080 // GetAllFormsInfo request to fms
3081 return FormMgr::GetInstance().GetAllFormsInfo(formInfos);
3082 }
3083
3084 /**
3085 * @brief Get forms info by bundle name .
3086 *
3087 * @param bundleName Application name.
3088 * @param formInfos Return the forms' information of the specify application name.
3089 * @return Return true if the request is successfully initiated; return false otherwise.
3090 */
GetFormsInfoByApp(std::string & bundleName,std::vector<FormInfo> & formInfos)3091 ErrCode Ability::GetFormsInfoByApp(std::string &bundleName, std::vector<FormInfo> &formInfos)
3092 {
3093 HILOG_INFO("%{public}s called.", __func__);
3094 if (bundleName.empty()) {
3095 HILOG_WARN("Failed to Get forms info, because empty bundle name");
3096 return ERR_APPEXECFWK_FORM_INVALID_BUNDLENAME;
3097 }
3098
3099 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
3100 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
3101 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
3102 }
3103
3104 // GetFormsInfoByApp request to fms
3105 return FormMgr::GetInstance().GetFormsInfoByApp(bundleName, formInfos);
3106 }
3107
3108 /**
3109 * @brief Get forms info by bundle name and module name.
3110 *
3111 * @param bundleName bundle name.
3112 * @param moduleName Module name of hap.
3113 * @param formInfos Return the forms' information of the specify bundle name and module name.
3114 * @return Return true if the request is successfully initiated; return false otherwise.
3115 */
GetFormsInfoByModule(std::string & bundleName,std::string & moduleName,std::vector<FormInfo> & formInfos)3116 ErrCode Ability::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName,
3117 std::vector<FormInfo> &formInfos)
3118 {
3119 HILOG_INFO("%{public}s called.", __func__);
3120 if (bundleName.empty()) {
3121 HILOG_WARN("Failed to Get forms info, because empty bundleName");
3122 return ERR_APPEXECFWK_FORM_INVALID_BUNDLENAME;
3123 }
3124
3125 if (moduleName.empty()) {
3126 HILOG_WARN("Failed to Get forms info, because empty moduleName");
3127 return ERR_APPEXECFWK_FORM_INVALID_MODULENAME;
3128 }
3129
3130 if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) {
3131 HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__);
3132 return ERR_APPEXECFWK_FORM_SERVER_STATUS_ERR;
3133 }
3134
3135 // GetFormsInfoByModule request to fms
3136 return FormMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
3137 }
3138 #endif
3139
3140 /**
3141 * @brief Get the error message by error code.
3142 * @param errorCode the error code return form fms.
3143 * @return Returns the error message detail.
3144 */
GetErrorMsg(const ErrCode errorCode)3145 std::string Ability::GetErrorMsg(const ErrCode errorCode)
3146 {
3147 return FormMgr::GetInstance().GetErrorMessage(errorCode);
3148 }
3149
3150 /**
3151 * @brief Acquire a bundle manager, if it not existed.
3152 * @return returns the bundle manager ipc object, or nullptr for failed.
3153 */
GetBundleMgr()3154 sptr<IBundleMgr> Ability::GetBundleMgr()
3155 {
3156 HILOG_INFO("%{public}s called.", __func__);
3157 if (iBundleMgr_ == nullptr) {
3158 sptr<ISystemAbilityManager> systemAbilityManager =
3159 SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
3160 auto remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
3161 if (remoteObject == nullptr) {
3162 HILOG_ERROR("%{public}s error, failed to get bundle manager service.", __func__);
3163 return nullptr;
3164 }
3165
3166 iBundleMgr_ = iface_cast<IBundleMgr>(remoteObject);
3167 if (iBundleMgr_ == nullptr) {
3168 HILOG_ERROR("%{public}s error, failed to get bundle manager service", __func__);
3169 return nullptr;
3170 }
3171 }
3172
3173 return iBundleMgr_;
3174 }
3175
3176 /**
3177 * @brief Add the bundle manager instance for debug.
3178 * @param bundleManager the bundle manager ipc object.
3179 */
SetBundleManager(const sptr<IBundleMgr> & bundleManager)3180 void Ability::SetBundleManager(const sptr<IBundleMgr> &bundleManager)
3181 {
3182 HILOG_INFO("%{public}s called.", __func__);
3183
3184 iBundleMgr_ = bundleManager;
3185 }
3186
3187 #ifdef SUPPORT_GRAPHICS
3188 /**
3189 * @brief Acquire a form provider remote object.
3190 * @return Returns form provider remote object.
3191 */
GetFormRemoteObject()3192 sptr<IRemoteObject> Ability::GetFormRemoteObject()
3193 {
3194 HILOG_INFO("%{public}s start", __func__);
3195 if (providerRemoteObject_ == nullptr) {
3196 sptr<FormProviderClient> providerClient = new (std::nothrow) FormProviderClient();
3197 std::shared_ptr<Ability> thisAbility = this->shared_from_this();
3198 if (thisAbility == nullptr) {
3199 HILOG_ERROR("%{public}s failed, thisAbility is nullptr", __func__);
3200 }
3201 providerClient->SetOwner(thisAbility);
3202 providerRemoteObject_ = providerClient->AsObject();
3203 }
3204 HILOG_INFO("%{public}s end", __func__);
3205 return providerRemoteObject_;
3206 }
3207 #endif
3208
3209 /**
3210 * @brief Set the start ability setting.
3211 * @param setting the start ability setting.
3212 */
SetStartAbilitySetting(std::shared_ptr<AbilityStartSetting> setting)3213 void Ability::SetStartAbilitySetting(std::shared_ptr<AbilityStartSetting> setting)
3214 {
3215 HILOG_INFO("%{public}s called.", __func__);
3216 setting_ = setting;
3217 }
3218
3219 /**
3220 * @brief Set the launch param.
3221 *
3222 * @param launchParam the launch param.
3223 */
SetLaunchParam(const AAFwk::LaunchParam & launchParam)3224 void Ability::SetLaunchParam(const AAFwk::LaunchParam &launchParam)
3225 {
3226 HILOG_INFO("%{public}s called.", __func__);
3227 launchParam_ = launchParam;
3228 }
3229
GetLaunchParam() const3230 const AAFwk::LaunchParam& Ability::GetLaunchParam() const
3231 {
3232 return launchParam_;
3233 }
3234
3235 #ifdef SUPPORT_GRAPHICS
SetSceneListener(const sptr<Rosen::IWindowLifeCycle> & listener)3236 void Ability::SetSceneListener(const sptr<Rosen::IWindowLifeCycle> &listener)
3237 {
3238 sceneListener_ = listener;
3239 }
3240 #endif
3241
ExecuteBatch(const std::vector<std::shared_ptr<DataAbilityOperation>> & operations)3242 std::vector<std::shared_ptr<DataAbilityResult>> Ability::ExecuteBatch(
3243 const std::vector<std::shared_ptr<DataAbilityOperation>> &operations)
3244 {
3245 HILOG_INFO("Ability::ExecuteBatch start");
3246 std::vector<std::shared_ptr<DataAbilityResult>> results;
3247 if (abilityInfo_ == nullptr) {
3248 HILOG_ERROR("Ability::ExecuteBatch abilityInfo is nullptr");
3249 return results;
3250 }
3251 if (abilityInfo_->type != AppExecFwk::AbilityType::DATA) {
3252 HILOG_ERROR("Ability::ExecuteBatch data ability type failed, current type: %{public}d", abilityInfo_->type);
3253 return results;
3254 }
3255 size_t len = operations.size();
3256 HILOG_INFO("Ability::ExecuteBatch operation is nullptr, len %{public}zu", len);
3257 for (size_t i = 0; i < len; i++) {
3258 std::shared_ptr<DataAbilityOperation> operation = operations[i];
3259 if (operation == nullptr) {
3260 HILOG_INFO("Ability::ExecuteBatch operation is nullptr, create DataAbilityResult");
3261 results.push_back(std::make_shared<DataAbilityResult>(0));
3262 continue;
3263 }
3264 ExecuteOperation(operation, results, i);
3265 }
3266 HILOG_INFO("Ability::ExecuteBatch end, %{public}zu", results.size());
3267 return results;
3268 }
ExecuteOperation(std::shared_ptr<DataAbilityOperation> & operation,std::vector<std::shared_ptr<DataAbilityResult>> & results,int index)3269 void Ability::ExecuteOperation(std::shared_ptr<DataAbilityOperation> &operation,
3270 std::vector<std::shared_ptr<DataAbilityResult>> &results, int index)
3271 {
3272 HILOG_INFO("Ability::ExecuteOperation start, index=%{public}d", index);
3273 if (abilityInfo_->type != AppExecFwk::AbilityType::DATA) {
3274 HILOG_ERROR("Ability::ExecuteOperation data ability type failed, current type: %{public}d", abilityInfo_->type);
3275 return;
3276 }
3277 if (index < 0) {
3278 HILOG_ERROR(
3279 "Ability::ExecuteOperation operation result index should not below zero, current index: %{public}d", index);
3280 return;
3281 }
3282 if (operation == nullptr) {
3283 HILOG_INFO("Ability::ExecuteOperation operation is nullptr, create DataAbilityResult");
3284 results.push_back(std::make_shared<DataAbilityResult>(0));
3285 return;
3286 }
3287
3288 int numRows = 0;
3289 std::shared_ptr<NativeRdb::ValuesBucket> valuesBucket = ParseValuesBucketReference(results, operation, index);
3290 std::shared_ptr<NativeRdb::DataAbilityPredicates> predicates =
3291 ParsePredictionArgsReference(results, operation, index);
3292 if (operation->IsInsertOperation()) {
3293 HILOG_INFO("Ability::ExecuteOperation IsInsertOperation");
3294 numRows = Insert(*(operation->GetUri().get()), *valuesBucket);
3295 } else if (operation->IsDeleteOperation() && predicates) {
3296 HILOG_INFO("Ability::ExecuteOperation IsDeleteOperation");
3297 numRows = Delete(*(operation->GetUri().get()), *predicates);
3298 } else if (operation->IsUpdateOperation() && predicates) {
3299 HILOG_INFO("Ability::ExecuteOperation IsUpdateOperation");
3300 numRows = Update(*(operation->GetUri().get()), *valuesBucket, *predicates);
3301 } else if (operation->IsAssertOperation() && predicates) {
3302 HILOG_INFO("Ability::ExecuteOperation IsAssertOperation");
3303 std::vector<std::string> columns;
3304 std::shared_ptr<NativeRdb::AbsSharedResultSet> queryResult =
3305 Query(*(operation->GetUri().get()), columns, *predicates);
3306 if (queryResult == nullptr) {
3307 HILOG_ERROR("Ability::ExecuteOperation Query retval is nullptr");
3308 results.push_back(std::make_shared<DataAbilityResult>(0));
3309 return;
3310 }
3311 if (queryResult->GetRowCount(numRows) != 0) {
3312 HILOG_ERROR("Ability::ExecuteOperation queryResult->GetRowCount(numRows) != E_OK");
3313 }
3314 if (!CheckAssertQueryResult(queryResult, operation->GetValuesBucket())) {
3315 if (queryResult != nullptr) {
3316 queryResult->Close();
3317 }
3318 HILOG_ERROR("Query Result is not equal to expected value.");
3319 }
3320
3321 if (queryResult != nullptr) {
3322 queryResult->Close();
3323 }
3324 } else {
3325 HILOG_ERROR("Ability::ExecuteOperation Expected bad type %{public}d", operation->GetType());
3326 }
3327 if (operation->GetExpectedCount() != numRows) {
3328 HILOG_ERROR("Ability::ExecuteOperation Expected %{public}d rows but actual %{public}d",
3329 operation->GetExpectedCount(),
3330 numRows);
3331 } else {
3332 if (operation->GetUri() != nullptr) {
3333 results.push_back(std::make_shared<DataAbilityResult>(*operation->GetUri(), numRows));
3334 } else {
3335 results.push_back(std::make_shared<DataAbilityResult>(Uri(std::string("")), numRows));
3336 }
3337 }
3338 }
3339
ParsePredictionArgsReference(std::vector<std::shared_ptr<DataAbilityResult>> & results,std::shared_ptr<DataAbilityOperation> & operation,int numRefs)3340 std::shared_ptr<NativeRdb::DataAbilityPredicates> Ability::ParsePredictionArgsReference(
3341 std::vector<std::shared_ptr<DataAbilityResult>> &results, std::shared_ptr<DataAbilityOperation> &operation,
3342 int numRefs)
3343 {
3344 if (operation == nullptr) {
3345 HILOG_ERROR("Ability::ParsePredictionArgsReference intpur is nullptr");
3346 return nullptr;
3347 }
3348
3349 std::map<int, int> predicatesBackReferencesMap = operation->GetDataAbilityPredicatesBackReferences();
3350 if (predicatesBackReferencesMap.empty()) {
3351 return operation->GetDataAbilityPredicates();
3352 }
3353
3354 std::vector<std::string> strPredicatesList;
3355 strPredicatesList.clear();
3356 std::shared_ptr<NativeRdb::DataAbilityPredicates> predicates = operation->GetDataAbilityPredicates();
3357 if (predicates == nullptr) {
3358 HILOG_INFO("Ability::ParsePredictionArgsReference operation->GetDataAbilityPredicates is nullptr");
3359 } else {
3360 HILOG_INFO("Ability::ParsePredictionArgsReference operation->GetDataAbilityPredicates isn`t nullptr");
3361 strPredicatesList = predicates->GetWhereArgs();
3362 }
3363
3364 if (strPredicatesList.empty()) {
3365 HILOG_ERROR("Ability::ParsePredictionArgsReference operation->GetDataAbilityPredicates()->GetWhereArgs()"
3366 "error strList is empty()");
3367 }
3368
3369 for (auto iterMap : predicatesBackReferencesMap) {
3370 HILOG_INFO(
3371 "Ability::ParsePredictionArgsReference predicatesBackReferencesMap first:%{public}d second:%{public}d",
3372 iterMap.first,
3373 iterMap.second);
3374 int tempCount = ChangeRef2Value(results, numRefs, iterMap.second);
3375 if (tempCount < 0) {
3376 HILOG_ERROR("Ability::ParsePredictionArgsReference tempCount:%{public}d", tempCount);
3377 continue;
3378 }
3379 std::string strPredicates = std::to_string(tempCount);
3380 HILOG_INFO("Ability::ParsePredictionArgsReference strPredicates:%{public}s", strPredicates.c_str());
3381 strPredicatesList.push_back(strPredicates);
3382 HILOG_INFO("Ability::ParsePredictionArgsReference push_back done");
3383 }
3384
3385 if (predicates) {
3386 predicates->SetWhereArgs(strPredicatesList);
3387 }
3388
3389 return predicates;
3390 }
3391
ParseValuesBucketReference(std::vector<std::shared_ptr<DataAbilityResult>> & results,std::shared_ptr<DataAbilityOperation> & operation,int numRefs)3392 std::shared_ptr<NativeRdb::ValuesBucket> Ability::ParseValuesBucketReference(
3393 std::vector<std::shared_ptr<DataAbilityResult>> &results, std::shared_ptr<DataAbilityOperation> &operation,
3394 int numRefs)
3395 {
3396 NativeRdb::ValuesBucket retValueBucket;
3397 if (operation == nullptr) {
3398 HILOG_ERROR("Ability::ParseValuesBucketReference intpur is nullptr");
3399 return nullptr;
3400 }
3401
3402 if (operation->GetValuesBucketReferences() == nullptr) {
3403 return operation->GetValuesBucket();
3404 }
3405
3406 retValueBucket.Clear();
3407 if (operation->GetValuesBucket() == nullptr) {
3408 HILOG_INFO("Ability::ParseValuesBucketReference operation->GetValuesBucket is nullptr");
3409 } else {
3410 HILOG_INFO("Ability::ParseValuesBucketReference operation->GetValuesBucket is nullptr");
3411 retValueBucket = *operation->GetValuesBucket();
3412 }
3413
3414 std::map<std::string, NativeRdb::ValueObject> valuesMapReferences;
3415 operation->GetValuesBucketReferences()->GetAll(valuesMapReferences);
3416
3417 for (auto itermap : valuesMapReferences) {
3418 std::string key = itermap.first;
3419 NativeRdb::ValueObject obj;
3420 if (!operation->GetValuesBucketReferences()->GetObject(key, obj)) {
3421 HILOG_ERROR("Ability::ParseValuesBucketReference operation->GetValuesBucketReferences()->GetObject error");
3422 continue;
3423 }
3424 switch (obj.GetType()) {
3425 case NativeRdb::ValueObjectType::TYPE_INT: {
3426 int val = 0;
3427 if (obj.GetInt(val) != 0) {
3428 HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetInt() error");
3429 break;
3430 }
3431 HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutInt(%{public}s, %{public}d)",
3432 key.c_str(),
3433 val);
3434 retValueBucket.PutInt(key, val);
3435 } break;
3436 case NativeRdb::ValueObjectType::TYPE_DOUBLE: {
3437 double val = 0.0;
3438 if (obj.GetDouble(val) != 0) {
3439 HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetDouble() error");
3440 break;
3441 }
3442 HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutDouble(%{public}s, %{public}f)",
3443 key.c_str(),
3444 val);
3445 retValueBucket.PutDouble(key, val);
3446 } break;
3447 case NativeRdb::ValueObjectType::TYPE_STRING: {
3448 std::string val = "";
3449 if (obj.GetString(val) != 0) {
3450 HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetString() error");
3451 break;
3452 }
3453 HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutString(%{public}s, %{public}s)",
3454 key.c_str(),
3455 val.c_str());
3456 retValueBucket.PutString(key, val);
3457 } break;
3458 case NativeRdb::ValueObjectType::TYPE_BLOB: {
3459 std::vector<uint8_t> val;
3460 if (obj.GetBlob(val) != 0) {
3461 HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetBlob() error");
3462 break;
3463 }
3464 HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutBlob(%{public}s, %{public}zu)",
3465 key.c_str(),
3466 val.size());
3467 retValueBucket.PutBlob(key, val);
3468 } break;
3469 case NativeRdb::ValueObjectType::TYPE_BOOL: {
3470 bool val = false;
3471 if (obj.GetBool(val) != 0) {
3472 HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetBool() error");
3473 break;
3474 }
3475 HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutBool(%{public}s, %{public}s)",
3476 key.c_str(),
3477 val ? "true" : "false");
3478 retValueBucket.PutBool(key, val);
3479 } break;
3480 default: {
3481 HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutNull(%{public}s)", key.c_str());
3482 retValueBucket.PutNull(key);
3483 } break;
3484 }
3485 }
3486
3487 std::map<std::string, NativeRdb::ValueObject> valuesMap;
3488 retValueBucket.GetAll(valuesMap);
3489
3490 return std::make_shared<NativeRdb::ValuesBucket>(valuesMap);
3491 }
3492
ChangeRef2Value(std::vector<std::shared_ptr<DataAbilityResult>> & results,int numRefs,int index)3493 int Ability::ChangeRef2Value(std::vector<std::shared_ptr<DataAbilityResult>> &results, int numRefs, int index)
3494 {
3495 int retval = -1;
3496 if (index >= numRefs) {
3497 HILOG_ERROR("Ability::ChangeRef2Value index >= numRefs");
3498 return retval;
3499 }
3500
3501 if (index >= static_cast<int>(results.size())) {
3502 HILOG_ERROR("Ability::ChangeRef2Value index:%{public}d >= results.size():%{public}zu", index, results.size());
3503 return retval;
3504 }
3505
3506 std::shared_ptr<DataAbilityResult> refResult = results[index];
3507 if (refResult == nullptr) {
3508 HILOG_ERROR("Ability::ChangeRef2Value No.%{public}d refResult is null", index);
3509 return retval;
3510 }
3511
3512 if (refResult->GetUri().ToString().empty()) {
3513 retval = refResult->GetCount();
3514 } else {
3515 retval = DataUriUtils::GetId(refResult->GetUri());
3516 }
3517
3518 return retval;
3519 }
3520
CheckAssertQueryResult(std::shared_ptr<NativeRdb::AbsSharedResultSet> & queryResult,std::shared_ptr<NativeRdb::ValuesBucket> && valuesBucket)3521 bool Ability::CheckAssertQueryResult(std::shared_ptr<NativeRdb::AbsSharedResultSet> &queryResult,
3522 std::shared_ptr<NativeRdb::ValuesBucket> &&valuesBucket)
3523 {
3524 if (queryResult == nullptr) {
3525 HILOG_ERROR("Ability::CheckAssertQueryResult intput queryResult is null");
3526 return true;
3527 }
3528
3529 if (valuesBucket == nullptr) {
3530 HILOG_ERROR("Ability::CheckAssertQueryResult intput valuesBucket is null");
3531 return true;
3532 }
3533
3534 std::map<std::string, NativeRdb::ValueObject> valuesMap;
3535 valuesBucket->GetAll(valuesMap);
3536 if (valuesMap.empty()) {
3537 HILOG_ERROR("Ability::CheckAssertQueryResult valuesMap is empty");
3538 return true;
3539 }
3540 int count = 0;
3541 if (queryResult->GetRowCount(count) != 0) {
3542 HILOG_ERROR("Ability::CheckAssertQueryResult GetRowCount is 0");
3543 return true;
3544 }
3545
3546 for (auto iterMap : valuesMap) {
3547 std::string strObject;
3548 if (iterMap.second.GetString(strObject) != 0) {
3549 HILOG_ERROR("Ability::CheckAssertQueryResult GetString strObject is error");
3550 continue;
3551 }
3552 if (strObject.empty()) {
3553 HILOG_ERROR("Ability::CheckAssertQueryResult strObject is empty");
3554 continue;
3555 }
3556 for (int i = 0; i < count; ++i) {
3557 std::string strName;
3558 if (queryResult->GetString(i, strName) != 0) {
3559 HILOG_ERROR("Ability::CheckAssertQueryResult GetString strName is error");
3560 continue;
3561 }
3562 if (strName.empty()) {
3563 HILOG_ERROR("Ability::CheckAssertQueryResult strName is empty");
3564 continue;
3565 }
3566 if (strName.c_str() == strObject.c_str()) {
3567 HILOG_ERROR("Ability::CheckAssertQueryResult strName same to strObject");
3568 continue;
3569 }
3570
3571 return false;
3572 }
3573 }
3574
3575 return true;
3576 }
3577
3578 #ifdef SUPPORT_GRAPHICS
GetWindowOption(const Want & want)3579 sptr<Rosen::WindowOption> Ability::GetWindowOption(const Want &want)
3580 {
3581 HILOG_INFO("%{public}s start", __func__);
3582 sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
3583 if (option == nullptr) {
3584 HILOG_ERROR("Ability::GetWindowOption option is null.");
3585 return nullptr;
3586 }
3587 auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE,
3588 AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED);
3589 HILOG_INFO("Ability::GetWindowOption window mode is %{public}d.", windowMode);
3590 option->SetWindowMode(static_cast<Rosen::WindowMode>(windowMode));
3591 bool showOnLockScreen = false;
3592 if (abilityInfo_) {
3593 std::vector<CustomizeData> datas = abilityInfo_->metaData.customizeData;
3594 for (CustomizeData data : datas) {
3595 if (data.name == SHOW_ON_LOCK_SCREEN) {
3596 showOnLockScreen = true;
3597 }
3598 }
3599 }
3600 if (showOnLockScreen_ || showOnLockScreen) {
3601 HILOG_DEBUG("Ability::GetWindowOption come, add window flag WINDOW_FLAG_SHOW_WHEN_LOCKED.");
3602 option->AddWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED);
3603 }
3604
3605 if (want.GetElement().GetBundleName() == LAUNCHER_BUNDLE_NAME &&
3606 want.GetElement().GetAbilityName() == LAUNCHER_ABILITY_NAME) {
3607 HILOG_INFO("Set window type for launcher");
3608 option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_DESKTOP);
3609 }
3610
3611 HILOG_INFO("%{public}s end", __func__);
3612 return option;
3613 }
3614
DoOnForeground(const Want & want)3615 void Ability::DoOnForeground(const Want& want)
3616 {
3617 if (abilityWindow_ != nullptr) {
3618 HILOG_INFO("%{public}s begin abilityWindow_->OnPostAbilityForeground, sceneFlag:%{public}d.",
3619 __func__, sceneFlag_);
3620 auto window = abilityWindow_->GetWindow();
3621 if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) {
3622 auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE,
3623 AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED);
3624 window->SetWindowMode(static_cast<Rosen::WindowMode>(windowMode));
3625 HILOG_INFO("set window mode = %{public}d.", windowMode);
3626 }
3627 abilityWindow_->OnPostAbilityForeground(sceneFlag_);
3628 HILOG_INFO("%{public}s end abilityWindow_->OnPostAbilityForeground.", __func__);
3629 } else {
3630 HILOG_INFO("========================abilityWindow_ != nullptr ======================");
3631
3632 }
3633 }
3634 #endif
3635
3636 /**
3637 * @brief request a remote object of callee from this ability.
3638 * @return Returns the remote object of callee.
3639 */
CallRequest()3640 sptr<IRemoteObject> Ability::CallRequest()
3641 {
3642 return nullptr;
3643 }
3644
3645 #ifdef SUPPORT_GRAPHICS
GetCurrentWindowMode()3646 int Ability::GetCurrentWindowMode()
3647 {
3648 HILOG_INFO("%{public}s start", __func__);
3649 auto windowMode = static_cast<int>(Rosen::WindowMode::WINDOW_MODE_UNDEFINED);
3650 if (scene_ == nullptr) {
3651 return windowMode;
3652 }
3653 auto window = scene_->GetMainWindow();
3654 if (window != nullptr) {
3655 windowMode = static_cast<int>(window->GetMode());
3656 }
3657 return windowMode;
3658 }
3659
OnCreate(Rosen::DisplayId displayId)3660 void Ability::OnCreate(Rosen::DisplayId displayId)
3661 {
3662 HILOG_INFO("%{public}s called.", __func__);
3663 }
3664
OnDestroy(Rosen::DisplayId displayId)3665 void Ability::OnDestroy(Rosen::DisplayId displayId)
3666 {
3667 HILOG_INFO("%{public}s called.", __func__);
3668 }
3669
OnChange(Rosen::DisplayId displayId)3670 void Ability::OnChange(Rosen::DisplayId displayId)
3671 {
3672 HILOG_INFO("%{public}s start, displayId: %{public}" PRIu64"", __func__,
3673 displayId);
3674
3675 // Get display
3676 auto display = Rosen::DisplayManager::GetInstance().GetDisplayById(displayId);
3677 if (!display) {
3678 HILOG_ERROR("Get display by displayId %{public}" PRIu64" failed.", displayId);
3679 return;
3680 }
3681
3682 // Notify ResourceManager
3683 float density = display->GetVirtualPixelRatio();
3684 int32_t width = display->GetWidth();
3685 int32_t height = display->GetHeight();
3686 std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
3687 if (resConfig != nullptr) {
3688 auto resourceManager = GetResourceManager();
3689 if (resourceManager != nullptr) {
3690 resourceManager->GetResConfig(*resConfig);
3691 resConfig->SetScreenDensity(ConvertDensity(density));
3692 resConfig->SetDirection(ConvertDirection(height, width));
3693 resourceManager->UpdateResConfig(*resConfig);
3694 HILOG_INFO("%{public}s Notify ResourceManager, Density: %{public}d, Direction: %{public}d.", __func__,
3695 resConfig->GetScreenDensity(), resConfig->GetDirection());
3696 }
3697 }
3698
3699 // Notify ability
3700 Configuration newConfig;
3701 newConfig.AddItem(displayId, ConfigurationInner::APPLICATION_DIRECTION, GetDirectionStr(height, width));
3702 newConfig.AddItem(displayId, ConfigurationInner::APPLICATION_DENSITYDPI, GetDensityStr(density));
3703
3704 std::vector<std::string> changeKeyV;
3705 auto configuration = application_->GetConfiguration();
3706 if (!configuration) {
3707 HILOG_ERROR("configuration is nullptr.");
3708 return;
3709 }
3710
3711 configuration->CompareDifferent(changeKeyV, newConfig);
3712 uint32_t size = changeKeyV.size();
3713 HILOG_INFO("changeKeyV size :%{public}u", size);
3714 if (!changeKeyV.empty()) {
3715 configuration->Merge(changeKeyV, newConfig);
3716 auto task = [ability = shared_from_this(), configuration = *configuration]() {
3717 ability->OnConfigurationUpdated(configuration);
3718 };
3719 handler_->PostTask(task);
3720 }
3721
3722 HILOG_INFO("%{public}s end", __func__);
3723 }
3724
OnDisplayMove(Rosen::DisplayId from,Rosen::DisplayId to)3725 void Ability::OnDisplayMove(Rosen::DisplayId from, Rosen::DisplayId to)
3726 {
3727 HILOG_INFO("%{public}s called, from displayId %{public}" PRIu64" to %{public}" PRIu64".", __func__, from, to);
3728
3729 auto display = Rosen::DisplayManager::GetInstance().GetDisplayById(to);
3730 if (!display) {
3731 HILOG_ERROR("Get display by displayId %{public}" PRIu64" failed.", to);
3732 return;
3733 }
3734
3735 // Get new display config
3736 float density = display->GetVirtualPixelRatio();
3737 int32_t width = display->GetWidth();
3738 int32_t height = display->GetHeight();
3739 std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
3740 if (resConfig != nullptr) {
3741 auto resourceManager = GetResourceManager();
3742 if (resourceManager != nullptr) {
3743 resourceManager->GetResConfig(*resConfig);
3744 resConfig->SetScreenDensity(ConvertDensity(density));
3745 resConfig->SetDirection(ConvertDirection(height, width));
3746 resourceManager->UpdateResConfig(*resConfig);
3747 HILOG_INFO("%{public}s Notify ResourceManager, Density: %{public}d, Direction: %{public}d.", __func__,
3748 resConfig->GetScreenDensity(), resConfig->GetDirection());
3749 }
3750 }
3751
3752 Configuration newConfig;
3753 newConfig.AddItem(ConfigurationInner::APPLICATION_DISPLAYID, std::to_string(to));
3754 newConfig.AddItem(to, ConfigurationInner::APPLICATION_DIRECTION, GetDirectionStr(height, width));
3755 newConfig.AddItem(to, ConfigurationInner::APPLICATION_DENSITYDPI, GetDensityStr(density));
3756
3757 std::vector<std::string> changeKeyV;
3758 auto configuration = application_->GetConfiguration();
3759 if (!configuration) {
3760 HILOG_ERROR("configuration is nullptr.");
3761 return;
3762 }
3763
3764 configuration->CompareDifferent(changeKeyV, newConfig);
3765 uint32_t size = changeKeyV.size();
3766 HILOG_INFO("changeKeyV size :%{public}u", size);
3767 if (!changeKeyV.empty()) {
3768 configuration->Merge(changeKeyV, newConfig);
3769 auto task = [ability = shared_from_this(), configuration = *configuration]() {
3770 ability->OnConfigurationUpdated(configuration);
3771 };
3772 handler_->PostTask(task);
3773 }
3774 }
3775
RequsetFocus(const Want & want)3776 void Ability::RequsetFocus(const Want &want)
3777 {
3778 HILOG_INFO("%{public}s called.", __func__);
3779 if (abilityWindow_ == nullptr) {
3780 return;
3781 }
3782 auto window = abilityWindow_->GetWindow();
3783 if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) {
3784 auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE,
3785 AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED);
3786 window->SetWindowMode(static_cast<Rosen::WindowMode>(windowMode));
3787 HILOG_INFO("set window mode = %{public}d.", windowMode);
3788 }
3789 abilityWindow_->OnPostAbilityForeground(sceneFlag_);
3790 }
3791
SetWakeUpScreen(bool wakeUp)3792 void Ability::SetWakeUpScreen(bool wakeUp)
3793 {
3794 HILOG_INFO("SetWakeUpScreen wakeUp:%{public}d.", wakeUp);
3795 if (abilityWindow_ == nullptr) {
3796 HILOG_ERROR("SetWakeUpScreen error. abilityWindow_ == nullptr.");
3797 return;
3798 }
3799 HILOG_DEBUG("FA mode");
3800 auto window = abilityWindow_->GetWindow();
3801 if (window == nullptr) {
3802 HILOG_ERROR("window nullptr.");
3803 return;
3804 }
3805 window->SetTurnScreenOn(wakeUp);
3806 }
3807
SetDisplayOrientation(int orientation)3808 void Ability::SetDisplayOrientation(int orientation)
3809 {
3810 HILOG_DEBUG("%{public}s called, orientation: %{public}d", __func__, orientation);
3811 if (abilityWindow_ == nullptr) {
3812 HILOG_ERROR("Ability::SetDisplayOrientation error. abilityWindow_ == nullptr.");
3813 return;
3814 }
3815 HILOG_DEBUG("FA mode");
3816 auto window = abilityWindow_->GetWindow();
3817 if (window == nullptr) {
3818 HILOG_ERROR("window is nullptr.");
3819 return;
3820 }
3821 if (orientation == static_cast<int>(DisplayOrientation::FOLLOWRECENT)) {
3822 int defualtOrientation = 0;
3823 if (setWant_) {
3824 orientation = setWant_->GetIntParam("ohos.aafwk.Orientation", defualtOrientation);
3825 } else {
3826 orientation = defualtOrientation;
3827 }
3828 }
3829 if (orientation == static_cast<int>(DisplayOrientation::LANDSCAPE)) {
3830 HILOG_DEBUG("%{public}s, to set LANDSCAPE", __func__);
3831 window->SetRequestedOrientation(Rosen::Orientation::HORIZONTAL);
3832 } else if (orientation == static_cast<int>(DisplayOrientation::PORTRAIT)) {
3833 HILOG_DEBUG("%{public}s, to set PORTRAIT", __func__);
3834 window->SetRequestedOrientation(Rosen::Orientation::VERTICAL);
3835 } else {
3836 HILOG_DEBUG("%{public}s, to set UNSPECIFIED", __func__);
3837 window->SetRequestedOrientation(Rosen::Orientation::UNSPECIFIED);
3838 }
3839 }
3840
GetDisplayOrientation()3841 int Ability::GetDisplayOrientation()
3842 {
3843 HILOG_DEBUG("%{public}s called.", __func__);
3844 if (abilityWindow_ == nullptr) {
3845 HILOG_ERROR("Ability::GetDisplayOrientation error. abilityWindow_ == nullptr.");
3846 return 0;
3847 }
3848 HILOG_DEBUG("FA mode");
3849 auto window = abilityWindow_->GetWindow();
3850 if (window == nullptr) {
3851 HILOG_ERROR("window is nullptr.");
3852 return 0;
3853 }
3854 auto orientation = window->GetRequestedOrientation();
3855 if (orientation == Rosen::Orientation::HORIZONTAL) {
3856 HILOG_DEBUG("%{public}s, get window orientation: LANDSCAPE", __func__);
3857 return static_cast<int>(DisplayOrientation::LANDSCAPE);
3858 }
3859 if (orientation == Rosen::Orientation::VERTICAL) {
3860 HILOG_DEBUG("%{public}s, get window orientation: PORTRAIT", __func__);
3861 return static_cast<int>(DisplayOrientation::PORTRAIT);
3862 }
3863 HILOG_DEBUG("%{public}s, get window orientation: UNSPECIFIED", __func__);
3864 return 0;
3865 }
3866 #endif
3867
StartFeatureAbilityForResult(const Want & want,int requestCode,FeatureAbilityTask && task)3868 ErrCode Ability::StartFeatureAbilityForResult(const Want &want, int requestCode, FeatureAbilityTask &&task)
3869 {
3870 HILOG_DEBUG("%{public}s begin.", __func__);
3871 resultCallbacks_.insert(make_pair(requestCode, std::move(task)));
3872 ErrCode err = StartAbilityForResult(want, requestCode);
3873 HILOG_INFO("%{public}s end. ret=%{public}d", __func__, err);
3874 return err;
3875 }
3876
OnFeatureAbilityResult(int requestCode,int resultCode,const Want & want)3877 void Ability::OnFeatureAbilityResult(int requestCode, int resultCode, const Want &want)
3878 {
3879 HILOG_DEBUG("%{public}s begin.", __func__);
3880 auto callback = resultCallbacks_.find(requestCode);
3881 if (callback != resultCallbacks_.end()) {
3882 if (callback->second) {
3883 callback->second(resultCode, want);
3884 }
3885 resultCallbacks_.erase(requestCode);
3886 }
3887 HILOG_INFO("%{public}s end.", __func__);
3888 }
3889 } // namespace AppExecFwk
3890 } // namespace OHOS
3891