diff --git a/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.cpp b/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.cpp new file mode 100644 index 000000000000..a3689d5d0949 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include + +namespace facebook::react { + +jobject getApplication(JNIEnv* env) { + auto activityThreadClass = env->FindClass("android/app/ActivityThread"); + auto currentApplicationMethodID = env->GetStaticMethodID( + activityThreadClass, "currentApplication", "()Landroid/app/Application;"); + return env->CallStaticObjectMethod( + activityThreadClass, currentApplicationMethodID); +} + +jni::alias_ref getContext() { + auto env = facebook::jni::Environment::ensureCurrentThreadIsAttached(); + auto application = getApplication(env); + return facebook::jni::wrap_alias( + static_cast(application)); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.h b/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.h new file mode 100644 index 000000000000..8db809186f31 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.h @@ -0,0 +1,19 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include + +namespace facebook::react { + +jobject getApplication(JNIEnv* env); + +jni::alias_ref getContext(); + +} // namespace facebook::react