10

For example, let's say that in Android, I need to call the static method android.os.SystemClock.elapsedRealtime(), which returns a long, from a portion of native code. In the mylib.c file, I have

JNIEXPORT jlong JNICALL 
Java_com_mpackage_MyClass_nativeMethod(JNIEnv *env, jobject obj){

  jclass cls = (*env)->GetObjectClass(env, obj);
  jmethodID mid = (*env)->GetStaticMethodID(env, cls, "android.os.SystemClock.elapsedRealtime", "(V)J");

  if (mid == 0)
    return 0L;

  return CallStaticLongMethod(cls, mid);
}

In the java MyClass.class, I have among others

static {System.loadLibrary("myLib");}
native long nativeMethod();

but when I call it, I get the following error:

ERROR/AndroidRuntime(628): java.lang.NoSuchMethodError:
android.os.SystemClock.elapsedRealtime()

at the declaration of mid line. I think this is straightforward but I'm new to jni.

Can someone point out my mistake(s)?

Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Tom
  • 1,144
  • 1
  • 11
  • 23

1 Answers1

8

Looks like your usage of the JNI API is not proper. First you should get the class reference of android.os.SystemClock. The obj passed as a parameter, is an object of MyClass. You should use (*env)->FindClass(env, "android/os/SystemClock") to get a jclass for the SystemClock. Then call (*env)->GetStaticMethodID(env, cls,"elapsedRealtime", "(V)J"); to get the method id. Take a look at the JNI tutorial for further details

bobby
  • 2,629
  • 5
  • 30
  • 56
  • 2
    I had found this myself a few minutes ago! However, I had to specify the name fo the class like `(*env)->FindClass(env, "android/os/SystemClock")`. Thanks! – Tom Aug 30 '11 at 05:35