Skip to content Skip to sidebar Skip to footer

Communication Between C++ And Java In Android

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 n

Solution 1:

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 importsjstring 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);

    constchar* 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);
}

Solution 2:

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.

Post a Comment for "Communication Between C++ And Java In Android"