Search code examples
androidjava-native-interface

Android - calling JNI native function from different package


I'm just messing around with a Ndk tutorial I found. The native code uses one "package", while the activity is in another. When this mismatch occurs, I can't call the native function without getting an unsatisfied link exception. I know the "why's" I just don't know the resolution.

Here is the sample .c code that I've placed in my jni folder:

#include <string.h>
#include <jni.h>

jstring Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
  return (*env)->NewStringUTF(env, "Hello from native code!");
}

Notice that this .c code's package translates to com.mindtherobot.samples.ndkfoo.NdkFooActivity.

If I create a new activity that matches that Package/Class, I can call the invokeNativeFunction just fine. However, what if I can't match it? What if instead I need to run it from com.mydomain.activity?

I figured I could maybe change things around, such that my native declaration looked like this:

package com.mydomain;

public class Activity {
    private native String com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction();
}

But that's a no-go. Just to be clear, I know how to make this work if I change my package to match what is compiled in the .c code; however, I need to be able to call a method from a different package... is this possible?


Solution

  • You need to make a basic class with the sole functionality of talking to C, not an activity. Then activities can instantiate this class, or possibly even statically call it, whenever they need to talk to C.