blob: 26e99f95d32a1b4b8f513637710b78a96b46634c [file] [log] [blame]
Yifan Hong830cdb12021-01-11 20:47:23 -08001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <android-base/logging.h>
18#include <android/binder_ibinder.h>
19
20#include <health-impl/Health.h>
21#include <utils/Errors.h>
22
23#include "LinkedCallback.h"
24
25namespace aidl::android::hardware::health {
26
Yifan Hong70197262023-07-06 17:08:41 -070027::android::base::Result<std::unique_ptr<LinkedCallback>> LinkedCallback::Make(
Yifan Hong830cdb12021-01-11 20:47:23 -080028 std::shared_ptr<Health> service, std::shared_ptr<IHealthInfoCallback> callback) {
29 std::unique_ptr<LinkedCallback> ret(new LinkedCallback());
30 binder_status_t linkRet =
31 AIBinder_linkToDeath(callback->asBinder().get(), service->death_recipient_.get(),
32 reinterpret_cast<void*>(ret.get()));
33 if (linkRet != ::STATUS_OK) {
34 LOG(WARNING) << __func__ << "Cannot link to death: " << linkRet;
Yifan Hong70197262023-07-06 17:08:41 -070035 return ::android::base::Error(-linkRet);
Yifan Hong830cdb12021-01-11 20:47:23 -080036 }
37 ret->service_ = service;
38 ret->callback_ = std::move(callback);
39 return ret;
40}
41
42LinkedCallback::LinkedCallback() = default;
43
44LinkedCallback::~LinkedCallback() {
45 if (callback_ == nullptr) {
46 return;
47 }
48 auto status =
49 AIBinder_unlinkToDeath(callback_->asBinder().get(), service()->death_recipient_.get(),
50 reinterpret_cast<void*>(this));
51 if (status != STATUS_OK && status != STATUS_DEAD_OBJECT) {
52 LOG(WARNING) << __func__ << "Cannot unlink to death: " << ::android::statusToString(status);
53 }
54}
55
56std::shared_ptr<Health> LinkedCallback::service() {
57 auto service_sp = service_.lock();
58 CHECK_NE(nullptr, service_sp);
59 return service_sp;
60}
61
62void LinkedCallback::OnCallbackDied() {
63 service()->unregisterCallback(callback_);
64}
65
66} // namespace aidl::android::hardware::health