blob: 3d42b53e74b50dc5928de00b2843aa8bd3a44734 [file] [log] [blame]
Mikhail Naganovd8f24412024-03-20 18:15:42 -07001/*
2 * Copyright (C) 2024 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#pragma once
18
19#include <memory>
20#include <string>
21
22#include <android/binder_auto_utils.h>
23#include <android/binder_manager.h>
24
25namespace android {
26
27template<class Intf>
28std::shared_ptr<Intf> getServiceInstance(const std::string& instanceName) {
29 const std::string serviceName =
30 std::string(Intf::descriptor).append("/").append(instanceName);
31 std::shared_ptr<Intf> service;
32 while (!service) {
33 AIBinder* serviceBinder = nullptr;
34 while (!serviceBinder) {
35 // 'waitForService' may return a nullptr, hopefully a transient error.
36 serviceBinder = AServiceManager_waitForService(serviceName.c_str());
37 }
38 // `fromBinder` may fail and return a nullptr if the service has died in the meantime.
39 service = Intf::fromBinder(ndk::SpAIBinder(serviceBinder));
40 }
41 return service;
42}
43
44} // namespace android