"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to correctly call Java methods through JNI in Android?

How to correctly call Java methods through JNI in Android?

Posted on 2025-04-21
Browse:522

How To Correctly Call Java Methods From C   in Android Using JNI?

Calling Java Methods from C in Android

In the context of Java Native Interface (JNI) in Android, it is possible to invoke Java methods from C code during the execution of a native method called from Java. Here's a detailed analysis of a code snippet you provided, highlighting the issue and providing a solution:

Problem:
Your native code is attempting to call the "messageMe" method from the "the/package/MainActivity" class using the "CallObjectMethod" function. However, the error message "java.lang.NoSuchMethodError: messageMe" indicates that the method is not found.

Analysis:
The issue lies in the way you are passing the object to the "CallObjectMethod" function. In your code, you are passing the "jstr" object, which is a Java string, instead of the "obj" object, which is the instance of the MainActivity class.

Solution:
To call object methods from C , you need to pass the object itself to the "CallObjectMethod" function. The corrected code below shows the modification:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

Additional Notes:

  • If your Java method is a void method, as in your case, you should use "CallVoidMethod" instead of "CallObjectMethod" in your C code.
  • If you need to return a result from your Java method, you will also need to modify the JNI signature in your header file and the return type in your Java code.

By addressing the issue described above, you should be able to successfully call Java methods from C in your Android application.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3