Featured Articles
Article in Android App Development category.
Understanding Android NDK with Kotlin Part 3: Callbacks Continued
Learn how to call Kotlin code from native code, with our expert Android developer's guide on Kotlin and Android NDK: Callbacks continued.
In the previous article, we saw how Kotlin code interacts with CPP, a simple Hello World Application. We got to know some basics on the changes in the CMake
and the gradle
file, we also looked at how to call native code from Kotlin.
In this article, we are going to find out how to call Kotlin from native code.
Do we really need to call Kotlin code from native?
The first question that comes to mind when doing the Kotlin and Android NDK is do we really need to call Kotlin code for the native c/cpp code?
The answer is yes! We need callbacks, we want to know the result of the tasks we performed using the native code, be it using the FFmpeg libraries to decode some image/video or any interceded operation. We can get the callbacks in the form of some progress which can be used to update the UI. This helps in keeping the UI interactive during some CPU intensive operations.
How to call Kotlin code From Native
This is the very next question that came to my mind. Well before going to the sample on how it's done, let's see what all methods and properties are available for us to use.
Static Properties and Methods
JniEnv
has different methods to access the value of static fields.
Let's take the example of the NativeStore that we created in the previous article, which is a wrapper around native functions.
Accessing a static field
Here we created a booleanField
variable inside the companion object. Accessing the Boolean
value in the native code can be done as:
To get the Id of the static field we used the function GetStaticFieldID
.
Accessing a Static Method
Similar to accessing the static fields we can access the static methods from the native code. To get the Id of a static method we use jmethodID GetStaticMethodID(JNIEnv *env, jclass class,
function.
const char *name, const char *sig)
In NativeStore code lets add a function which returns the sum of two values passed to it.
Instance’s Properties and Methods
Similar to the previous examples we can use the Instance’s Properties and Methods.
Conclusion
In this article, we saw how we can call methods in Kotlin directly in the CPP code. This knowledge can be extended to creating callbacks, such as updating UI about some video/audio processing through ffmpeg etc.
TL;DR
You might have noticed the “Z” in function,getStaticFieldId
those are the type signatures used in native code.