Bidirectional link between java application and an unreal game

In case someone else needs this here is how it’s done. This link between c++ and java made possible with jni.
The easiest way to access java is to modify game activity class with upl using a tag . For example:

  <gameActivityClassAdditions>
		<insert>

      public void testFunction()
      {
      Log.debug("caled java code");
      }
    </insert>
	</gameActivityClassAdditions>

Then in c++ function you call:

static jmethodID javaMethodId;

SomeClass::SomeClass()
{

	JNIEnv* env = FAndroidApplication::GetJavaEnv();
	javaMethodId = FJavaWrapper::FindMethod(env, 
        FJavaWrapper::GameActivityClassID, "testFunction", "()V", false);
	FJavaWrapper::CallVoidMethod(env, FJavaWrapper::GameActivityThis, javaMethodId);
}

You need to know the sinature of java function, you can find it here.
This is a common knowledge that could be found, I just summarised it. What I couldn’t find is how to call back from java to c++ and here is how you do it.
Again using simply game activity you add function declaration of c++ method in java as described previously:

      private static native void howToGetString(String code);

In c++(I used the same file from where I call java class) you do the following:

#include <jni.h>

static FCriticalSection ReceiversLock;

static FString OurString = "";

#if PLATFORM_ANDROID
extern "C"
{
	JNIEXPORT void Java_com_epicgames_ue4_GameActivity_howToGetString(JNIEnv * jni, jclass clazz, jstring code)
	{
		ReceiversLock.Lock();
		const char* charsId = jni->GetStringUTFChars(code, 0);
		OurString = FString(UTF8_TO_TCHAR(charsId));
		jni->ReleaseStringUTFChars(code, charsId);
		ReceiversLock.Unlock();
	}
}
#endif

Now you can call function howToGetString("a string ") and it will call you c++ class. I used it in OnActivityResult to get data from my intent.
Hope this will help someone.

3 Likes