|
31 | 31 | #undef max |
32 | 32 | #elif defined(ANDROID) || defined(ANDROID_HOST) |
33 | 33 | #include <jni.h> |
| 34 | +#ifdef OLP_SDK_ANDROID_AUTO_INITIALIZE_CARES |
| 35 | +#include <ares.h> |
| 36 | +#include <olp/core/logging/Log.h> |
| 37 | +#endif |
34 | 38 | #endif |
35 | 39 |
|
36 | 40 | #include "ContextInternal.h" |
37 | 41 |
|
38 | 42 | namespace { |
39 | 43 | 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 |
41 | 48 |
|
42 | 49 | namespace olp { |
43 | 50 | namespace context { |
@@ -84,6 +91,11 @@ void Context::init() { |
84 | 91 | void Context::deinit() { |
85 | 92 | #if defined(ANDROID) || defined(ANDROID_HOST) |
86 | 93 | auto cd = Instance(); |
| 94 | + |
| 95 | +#ifdef OLP_SDK_ANDROID_AUTO_INITIALIZE_CARES |
| 96 | + ares_library_cleanup(); |
| 97 | +#endif |
| 98 | + |
87 | 99 | // Release the global reference of Context. |
88 | 100 | // Technically not needed if we took the application context, |
89 | 101 | // but good to release just in case. |
@@ -128,6 +140,34 @@ void Context::init(JavaVM* vm, jobject context) { |
128 | 140 | assert(0); |
129 | 141 | } |
130 | 142 | 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 | + |
131 | 171 | initialize(); |
132 | 172 | } |
133 | 173 |
|
|
0 commit comments