1 /*
2  * Copyright (c) 2023 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 "bundle_resource_event_subscriber.h"
17 
18 #include <thread>
19 
20 #include "app_log_wrapper.h"
21 #include "bundle_constants.h"
22 #include "bundle_resource_callback.h"
23 #include "common_event_support.h"
24 
25 namespace OHOS {
26 namespace AppExecFwk {
27 namespace {
28 const std::string OLD_USER_ID = "oldId";
29 }
BundleResourceEventSubscriber(const EventFwk::CommonEventSubscribeInfo & subscribeInfo)30 BundleResourceEventSubscriber::BundleResourceEventSubscriber(
31     const EventFwk::CommonEventSubscribeInfo &subscribeInfo) : EventFwk::CommonEventSubscriber(subscribeInfo)
32 {}
33 
~BundleResourceEventSubscriber()34 BundleResourceEventSubscriber::~BundleResourceEventSubscriber()
35 {}
36 
OnReceiveEvent(const EventFwk::CommonEventData & data)37 void BundleResourceEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data)
38 {
39     std::string action = data.GetWant().GetAction();
40     BundleResourceCallback callback;
41     if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
42         int32_t oldUserId = Constants::UNSPECIFIED_USERID;
43         std::string oldId = data.GetWant().GetStringParam(OLD_USER_ID);
44         if (oldId.empty() || !OHOS::StrToInt(oldId, oldUserId)) {
45             APP_LOGE("oldId:%{public}s parse failed", oldId.c_str());
46             oldUserId = Constants::UNSPECIFIED_USERID;
47         }
48         int32_t userId = data.GetCode();
49         // when boot, user 0 or -1 switch to user 100, no need to flush resource rdb
50         if ((oldUserId == Constants::DEFAULT_USERID) || (oldUserId == Constants::INVALID_USERID)) {
51             APP_LOGI("switch userId %{public}d to %{public}d, no need to process", oldUserId, userId);
52             return;
53         }
54         APP_LOGI("switch userId %{public}d to %{public}d", oldUserId, userId);
55         std::thread userIdChangedThread(OnUserIdChanged, oldUserId, userId);
56         userIdChangedThread.detach();
57     }
58     // for other event
59 }
60 
OnUserIdChanged(const int32_t oldUserId,const int32_t newUserId)61 void BundleResourceEventSubscriber::OnUserIdChanged(const int32_t oldUserId, const int32_t newUserId)
62 {
63     BundleResourceCallback callback;
64     callback.OnUserIdSwitched(oldUserId, newUserId);
65 }
66 }  // namespace AppExecFwk
67 }  // namespace OHOS
68