summaryrefslogtreecommitdiffstats
path: root/src/corelib/kernel/qjnienvironment.cpp
diff options
context:
space:
mode:
authorVolker Hilsheimer <volker.hilsheimer@qt.io>2023-10-12 16:03:17 +0200
committerVolker Hilsheimer <volker.hilsheimer@qt.io>2023-11-01 15:58:42 +0800
commit6735aa868ffb559f82439c55271251ec54ff509e (patch)
tree62f5cec2537212c4c5ed3b6eb1af867da6f2455b /src/corelib/kernel/qjnienvironment.cpp
parente21d35b9f78d9946de3c9b7d23a19e628182a9d8 (diff)
JNI: add a static getter for a JNIEnv pointer to QJniEnvironment
This further helps reduce the creation of temporary QJniEnivronment instances (with allocated d-pointer) for cases where we simply need to get the JNIEnv for the current thread. Change-Id: I2eda238124be51c755d8910de9dbc9ca8eb92288 Reviewed-by: Tinja Paavoseppä <tinja.paavoseppa@qt.io> Reviewed-by: Qt CI Bot <qt_ci_bot@qt-project.org> Reviewed-by: Assam Boudjelthia <assam.boudjelthia@qt.io> Reviewed-by: Petri Virkkunen <petri.virkkunen@qt.io>
Diffstat (limited to 'src/corelib/kernel/qjnienvironment.cpp')
-rw-r--r--src/corelib/kernel/qjnienvironment.cpp26
1 files changed, 18 insertions, 8 deletions
diff --git a/src/corelib/kernel/qjnienvironment.cpp b/src/corelib/kernel/qjnienvironment.cpp
index 8d4e386a68..5afa1a6484 100644
--- a/src/corelib/kernel/qjnienvironment.cpp
+++ b/src/corelib/kernel/qjnienvironment.cpp
@@ -53,10 +53,20 @@ Q_GLOBAL_STATIC(QThreadStorage<QJniEnvironmentPrivateTLS *>, jniEnvTLS)
QJniEnvironment::QJniEnvironment()
: d(new QJniEnvironmentPrivate{})
{
+ d->jniEnv = getJniEnv();
+}
+
+/*!
+ Returns the JNIEnv pointer for the current thread.
+
+ The current thread will be attached to the Java VM.
+*/
+JNIEnv *QJniEnvironment::getJniEnv()
+{
+ JNIEnv *jniEnv = nullptr;
+
JavaVM *vm = QtAndroidPrivate::javaVM();
- const jint ret = vm->GetEnv((void**)&d->jniEnv, JNI_VERSION_1_6);
- if (ret == JNI_OK) // Already attached
- return;
+ const jint ret = vm->GetEnv((void**)&jniEnv, JNI_VERSION_1_6);
if (ret == JNI_EDETACHED) { // We need to (re-)attach
const QByteArray threadName = QThread::currentThread()->objectName().toUtf8();
@@ -64,12 +74,12 @@ QJniEnvironment::QJniEnvironment()
threadName.isEmpty() ? "QtThread" : threadName.constData(),
nullptr
};
- if (vm->AttachCurrentThread(&d->jniEnv, &args) != JNI_OK)
- return;
-
- if (!jniEnvTLS->hasLocalData()) // If we attached the thread we own it.
- jniEnvTLS->setLocalData(new QJniEnvironmentPrivateTLS);
+ if (vm->AttachCurrentThread(&jniEnv, &args) == JNI_OK) {
+ if (!jniEnvTLS->hasLocalData()) // If we attached the thread we own it.
+ jniEnvTLS->setLocalData(new QJniEnvironmentPrivateTLS);
+ }
}
+ return jniEnv;
}
/*!