4

I want to call a java method from C++ file in native code in Android. I know, we can achieve this from JNI but in that case the, I need to initiate the call from Java, which will not fit in my requirements.

I need to call a method written in Java from main() function in C++.

So is there any other approach to achieve this without JNI?

If I can achieve exact this thing using JNI, please let me know how?

Thanks in advance.

Thank You, Maulik

MMJ
  • 519
  • 1
  • 9
  • 26

2 Answers2

2

Did you check this:
https://developer.android.com/ndk/samples/sample_hellojni.html I basically learned from there. Or:
1. https://github.com/sureshjoshi/android-ndk-swig-example.
2. https://github.com/googlesamples/android-ndk.
A simple search would have gotten you in all these places.
EDIT Now, once you are done with this and it works well next you call from C/C++:
Calling a java method from c++ in Android. The Snippet that should help you is:

#include <string.h>
#include <jni.h>
//other imports

jstring get_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "MainActivity class");
    jclass clazz = (*env)->FindClass(env, "com/org/android/ui/activities/MainActivity");
    jmethodID mCurrentActivityId = (*env)->GetMethodID(env, clazz, "getCurrentActivityName", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, mCurrentActivityId, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}
Community
  • 1
  • 1
Andrei T
  • 2,985
  • 3
  • 21
  • 28
  • I checked them, but the thing is they uses JNI to call C to JAVA and vice versa and in JNI we need to initiate the call first in Java and and then we can call from C to JAVA. What I want is to call from C to JAVA without initiating it in JAVA. – MMJ Sep 14 '15 at 17:48
1

For this, you can create an Android service with a server socket. And you can create the C++ Application which is implementing the client socket.

C++ App (Client socket) <----> Android service (Server socket)

In this way also you can implement a request/response mechanism from the C++ app and Android App/service.

Ronak Patel
  • 130
  • 1
  • 10