1 /*
2 * Copyright (c) 2025 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 "user_switch_reporter.h"
17
18 #include <chrono>
19 #include <cinttypes>
20 #include <hisysevent.h>
21
22 #include "window_manager_hilog.h"
23
24 namespace OHOS {
25 namespace Rosen {
UserSwitchReporter(bool isUserActive)26 UserSwitchReporter::UserSwitchReporter(bool isUserActive)
27 : startTime_(GetCurrentTimeMillis()), isUserActive_(isUserActive) {}
28
~UserSwitchReporter()29 UserSwitchReporter::~UserSwitchReporter()
30 {
31 if (!ReportSwitchDuration()) {
32 TLOGE(WmsLogTag::WMS_MULTI_USER, "User switch duration reporting failed.");
33 }
34 }
35
GetCurrentTimeMillis()36 uint64_t UserSwitchReporter::GetCurrentTimeMillis()
37 {
38 return static_cast<uint64_t>(
39 std::chrono::duration_cast<std::chrono::milliseconds>(
40 std::chrono::system_clock::now().time_since_epoch()
41 ).count()
42 );
43 }
44
ReportSwitchDuration() const45 bool UserSwitchReporter::ReportSwitchDuration() const
46 {
47 auto endTime = GetCurrentTimeMillis();
48 auto duration = static_cast<uint32_t>(endTime - startTime_);
49 TLOGD(WmsLogTag::WMS_MULTI_USER,
50 "startTime: %{public}" PRIu64 ", endTime: %{public}" PRIu64 ", duration: %{public}u ms",
51 startTime_, endTime, duration);
52
53 int32_t ret = HiSysEventWrite(
54 HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
55 "USER_SWITCH_DURATION",
56 HiviewDFX::HiSysEvent::EventType::STATISTIC,
57 "SWITCH_TYPE", static_cast<uint8_t>(isUserActive_),
58 "START_TIME", startTime_,
59 "END_TIME", endTime,
60 "DURATION", duration);
61 if (ret != 0) {
62 TLOGE(WmsLogTag::WMS_MULTI_USER, "Failed to write HiSysEvent, ret: %{public}d", ret);
63 return false;
64 }
65 return true;
66 }
67 } // namespace Rosen
68 } // namespace OHOS
69