Skip to content

Commit 403f8c5

Browse files
Auto-initialize C-ares on request (#1645)
Android requires having a separate call for C-ares initialization, doing it automatically on Context initialization saves a lot of issues. No separate CMake option since it's not intended for direct use. Relates-To: OCMAM-647 Signed-off-by: Andrey Kashcheev <[email protected]>
1 parent 6b902ab commit 403f8c5

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

olp-cpp-sdk-core/src/context/Context.cpp

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,20 @@
3131
#undef max
3232
#elif defined(ANDROID) || defined(ANDROID_HOST)
3333
#include <jni.h>
34+
#ifdef OLP_SDK_ANDROID_AUTO_INITIALIZE_CARES
35+
#include <ares.h>
36+
#include <olp/core/logging/Log.h>
37+
#endif
3438
#endif
3539

3640
#include "ContextInternal.h"
3741

3842
namespace {
3943
std::atomic_flag gDeInitializing = ATOMIC_FLAG_INIT;
40-
}
44+
#ifdef OLP_SDK_ANDROID_AUTO_INITIALIZE_CARES
45+
constexpr auto kLogTag = "Context";
46+
#endif
47+
} // namespace
4148

4249
namespace olp {
4350
namespace context {
@@ -84,6 +91,11 @@ void Context::init() {
8491
void Context::deinit() {
8592
#if defined(ANDROID) || defined(ANDROID_HOST)
8693
auto cd = Instance();
94+
95+
#ifdef OLP_SDK_ANDROID_AUTO_INITIALIZE_CARES
96+
ares_library_cleanup();
97+
#endif
98+
8799
// Release the global reference of Context.
88100
// Technically not needed if we took the application context,
89101
// but good to release just in case.
@@ -128,6 +140,34 @@ void Context::init(JavaVM* vm, jobject context) {
128140
assert(0);
129141
}
130142
cd->context = env->NewGlobalRef(context);
143+
144+
#ifdef OLP_SDK_ANDROID_AUTO_INITIALIZE_CARES
145+
{
146+
OLP_SDK_LOG_INFO(kLogTag, "Auto-initializing C-ares");
147+
148+
ares_library_init_jvm(cd->java_vm);
149+
150+
jclass context_class = env->GetObjectClass(context);
151+
jmethodID system_service_method =
152+
env->GetMethodID(context_class, "getSystemService",
153+
"(Ljava/lang/String;)Ljava/lang/Object;");
154+
jclass context_class_static = env->FindClass("android/content/Context");
155+
jfieldID service_field = env->GetStaticFieldID(
156+
context_class_static, "CONNECTIVITY_SERVICE", "Ljava/lang/String;");
157+
jstring connectivity_service =
158+
(jstring)env->GetStaticObjectField(context_class_static, service_field);
159+
jobject connectivity_manager = env->CallObjectMethod(
160+
context, system_service_method, connectivity_service);
161+
162+
if (connectivity_manager != NULL) {
163+
ares_library_init_android(connectivity_manager);
164+
OLP_SDK_LOG_INFO(kLogTag, "Successfuly auto-initialized C-ares");
165+
} else {
166+
OLP_SDK_LOG_WARNING(kLogTag, "Failed to auto-initialize C-ares");
167+
}
168+
}
169+
#endif
170+
131171
initialize();
132172
}
133173

0 commit comments

Comments
 (0)