Using JNI in Openframeworks Android (Part II)
In this second post (visit part I for an introduction), we’ll see how to call native Openframeworks code from a Java Android method.
In order to carry out this kind of communication it is mandatory to edit two files from our Openframeworks Android project: “OFActivity.java” (in the java side) and “ofApp.cpp” (in the C++ side).
We’ll begin by editing the C++ side, adding the following method:
extern "C"{ JNIEXPORT void JNICALL Java_cc_openframeworks_activitiesOF_OFActivity_callCmethod(JNIEnv *, jobject){ /** * This code runs when "callCmethod" function is called in OFActivity.java (Java side) */ ofLog() << "C++ Method called from Java" << endl; } }
In the method’s header, we see the Openframeworks Android package’s path. The ending of this path should be ‘callCmethod‘. This is the method we’ll need to call in the Java side (OFActivity.java), in the following way:
- Let’s declare a method header of the method which has been called ‘callCmethod‘ as this method has to match with the one declared in the C++ side:
public native void callCmethod();
- We’ll use this method in the onClick of an Android’s native button (which are included in the Android’s SDK). The button needs to be added in the Openframeworks layout with the eclipse’s editor.
In this case, we have called the function onClick with the property ‘showOFlogMessage’. In the Java side (OFActivity.java) we’ll add the following code:
public void showOFlogMessage(View view){ /** * Call native method (code in C++, stored at ofApp.cpp) */ callCmethod(); }
Therefore, when we run our application and we click the Android’s button which is located over our Openframeworks screen, we’ll be calling the code which is located in the ofApp.cpp. In the example attached to this tutorial, when we run the program, we’ll se in the console:
ofLog() << "C++ Method called from Java" << endl;
This first communication option has allowed us to call Openframeworks sentences during while running elements of the Java Android’s code. This method will be usefull to call an OF Activity from a native Android context. In this way, we’ll be able to run more complex applications coded with OF while keeping the control from a Java Interface.
In the next post, we’ll talk about how to call Android’s SDK native code from Openframeworks.