This steps are valid for Necessitas Alpha 3 Update 4
Add your java class inside org.kde.necessitas.origo (i will refer in this article as JavaManager.Java)
Edit qtmain_android.cpp
Replace
static JavaVM *m_javaVM = NULL;
static JNIEnv *m_env = NULL;
static jobject objptr;
with
JavaVM *m_javaVM = NULL;
static JNIEnv *m_env = NULL;
jobject objptr;
//new pointer to my Java class
jobject customClassPtr;
//my class
static const char * const customClass = “org/kde/necessitas/origo/JavaManager”;
Add next lines to your file
static int registerNativeMethodsCustom(JNIEnv* env, const char* className, JNINativeMethod* gMethods, int numMethods)
{
jclass clazz=env->FindClass(className);
if (clazz == NULL)
{
__android_log_print(ANDROID_LOG_FATAL,”Qt”, “Custom Native registration unable to find class ‘%s’”, className);
return JNI_FALSE;
}
jmethodID constr = env->GetMethodID(clazz, “”, “()V”);
if(!constr) {
__android_log_print(ANDROID_LOG_FATAL,”Qt”, “Custom Native registration unable to find constructor for class ‘%s’”, className);
return JNI_FALSE;
}
jobject obj = env->NewObject(clazz, constr);
customClassPtr = env->NewGlobalRef(obj);
// if (env->RegisterNatives(clazz, gMethods, numMethods) < 0)
// {
// __android_log_print(ANDROID_LOG_FATAL,”Qt”, “Custom RegisterNatives failed for ‘%s’”, className);
// return JNI_FALSE;
// }
return JNI_TRUE;
}
static int registerNativesCustom(JNIEnv* env)
{
if (!registerNativeMethodsCustom(env, customClass, methods, sizeof(methods) / sizeof(methods[0])))
return JNI_FALSE;
return JNI_TRUE;
}
Add next lines to Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* /*reserved*/)
if (!registerNativesCustom(m_env))
{
__android_log_print(ANDROID_LOG_FATAL, “Qt”, “Custom registerNatives failed”);
return -1;
}
Prepare and call your java class from your file. Prepare your C++ class adding next lines:
extern JavaVM *m_javaVM;
extern jobject objptr;
extern jobject customClassPtr;
Now, in your method call the Java method:
JNIEnv* env;
if (m_javaVM->AttachCurrentThread(&env, NULL)<0)
{
qCritical()< return;
}
jclass applicationClass = env->GetObjectClass(customClassPtr);
qDebug()<
if (applicationClass) {
jmethodID playMediaFileMethodID = env->GetMethodID(applicationClass,”playMediaFile”, “(Ljava/lang/String;)V”);
jstring path = env->NewStringUTF(“my song”);
env->CallStaticVoidMethod(applicationClass, playMediaFileMethodID, path);
}
m_javaVM->DetachCurrentThread();
WARNING
1. The qtmain_android.cpp cand be changed by any Necessitas updates
2. You must change the qtmain_android.coo in both armabi and armabi-v7a
3. Any suggestions and/or questions are welcome.
Source: here.
Recent Comments