* Copyright (C) 2026 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TIMER_LOCK_OPTIMIZER_H
#define TIMER_LOCK_OPTIMIZER_H
#ifdef RUNNING_LOCK_OPTIMIZE
#include <cstdint>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <vector>
#include "want_agent.h"
#include "want_agent_constant.h"
namespace OHOS {
namespace MiscServices {
using namespace OHOS::AbilityRuntime::WantAgent;
class TimerInfo;
class TimerManager;
class TimerLockOptimizer : public std::enable_shared_from_this<TimerLockOptimizer> {
public:
explicit TimerLockOptimizer(TimerManager* manager);
~TimerLockOptimizer() = default;
bool IsAbilityStartingOperation(WantAgentConstant::OperationType operType);
void Init();
void UpdateRunningApps(const std::string& bundleName, bool isRunning);
void BatchAcquireRunningLock(const std::vector<std::shared_ptr<TimerInfo>>& triggerList);
bool IsAppRunning(const std::string& bundleName);
void RecalcLockForBundle(const std::string& bundleName);
int64_t GetTimerLockExpireTime() const { return timerLockExpireTime_.load(); }
std::string GetBundleNameFromCache(uint64_t timerId) { return targetBundleNameCache_[timerId]; }
void ClearBundleNameCache() { targetBundleNameCache_.clear(); }
private:
struct TimerLockInfo {
uint64_t timerId;
std::string wantBundleName;
int64_t lockExpireTime;
};
void QueryAllRunningApps();
void MergeNewTimers(const std::vector<std::shared_ptr<TimerInfo>>& triggerList, int64_t bootTime);
void SortAndDeduplicate(int64_t bootTime);
void AcquireRunningLockInternal(int64_t expireTime, int64_t bootTime);
std::string ExtractBundleNameFromWantAgent(const std::shared_ptr<WantAgent>& wantAgent);
std::string GetTargetBundleName(const std::shared_ptr<TimerInfo>& timer);
std::string GetBundleNameMultiUser(const std::shared_ptr<TimerInfo>& timer);
TimerManager* const manager_;
std::atomic<bool> isInitialized_{false};
std::set<std::string> runningApps_;
std::mutex appListMutex_;
std::vector<TimerLockInfo> lockInfos_;
std::mutex lockInfosMutex_;
std::atomic<int64_t> timerLockExpireTime_{0};
std::map<uint64_t, std::string> targetBundleNameCache_;
};
}
}
#endif
#endif