From://http://www.eoeandroid.com/thread-150995-1-1.html
In a thread created in the NDK, only static Java APIs are allowed to be called. When Env->findclass () is called in the thread, the system emits an exception.
There are more detailed invocation instructions in Http://android.wooyd.org/JNIExample.
The sample code is as follows:
JAVA Code:
public class Simple_test extends Activity {
...
public static void Printndklog (String slog) {
LOG.E ("NDK", slog);
}
}
C + + code:
static javavm* G_JAVAVM = NULL;
static Jobject g_interfaceobject = 0;
static void Getinterfaceobject (JNIEnv *env, const char *path, Jobject *objptr) {
Jclass CLS = env->findclass (path);
if (!CLS) {
Return
}
Jmethodid constr = Env->getmethodid (CLS, "<init>", "() V");
if (!CONSTR) {
Return
}
Jobject obj = Env->newobject (cls, constr);
if (!obj) {
Return
}
(*objptr) = Env->newglobalref (obj);
}
int Jniload (javavm* JVM, void* reserved)
{
G_JAVAVM = JVM;
JNIEnv *env;
if (jvm->getenv (void**) &env, jni_version_1_6)! = JNI_OK) {
return-1;
}
Getinterfaceobject (env, "Com/myndk/simple_test", &g_interfaceobject);
return jni_version_1_6;
}
void Jniunload (javavm* JVM, void* reserved)
{
JNIEnv *env;
if (jvm->getenv (void**) &env, jni_version_1_6)! = JNI_OK) {
Return
}
Env->deleteglobalref (G_interfaceobject);
}
void Printndklog (const char *format, ...)
{
Va_list arg_ptr;
Char slogbuff[1024];
Va_start (arg_ptr, format);
vsprintf (slogbuff, format, arg_ptr);
Va_end (ARG_PTR);
if (G_JAVAVM = = NULL)
Return
int status;
JNIEnv *env = NULL;
BOOL isattached = false;
Status = G_javavm->getenv ((void**) &env, jni_version_1_6);
if (Status < 0)
{
Status = G_javavm->attachcurrentthread (&env, NULL);
if (Status < 0)
{
Return
}
IsAttached = true;
}
Jclass cls = Env->getobjectclass (G_interfaceobject);
if (CLS! = 0)
{
Jmethodid mid = Env->getstaticmethodid (CLS, "Printndklog", "(ljava/lang/string;) V");
if (Mid! = 0)
{
Jstring jstrmsg = Env->newstringutf (Slogbuff);
Env->callstaticvoidmethod (CLS, Mid, jstrmsg);
}
}
if (isattached)//from native thread
{
G_javavm->detachcurrentthread ();
}
}
How to invoke the Java API in the NDK C + + thread