jlcarretero
jlcarretero

Reputation: 11

Android native daemon call to Java method via JNI

I have an Android Java Class:

package com.test.Testing;

public class MainActivity extends Activity {

    static {
        System.loadLibrary("testcontrol");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);             
    }

    public void tryBack() {
       Log.v("test", "callback called");
    }    
}

I have too, a native shared library called "libtestcontrol" with JNI_OnLoad and one method that I'm trying to use for call Java tryBack method:

JavaVM * global_vm;

jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv jvm_env;

    if ((*vm)->GetEnv(vm, (void **) &jvm_env, JNI_VERSION_1_6) != JNI_OK) {
        alog_error ("JNI_ONLOAD Failed to get the environment using GetEnv()");
        return -1;
    }       
    // *** Supposed to cache vm_global. I've tried too vm_global=vm  ****
    (*jvm_env)->GetJavaVM(jvm_env, &vm_global);

    if (vm_global == NULL) {
        alog_error ("JNI_ONLOAD: vm_global is NULL");
    }
    else {
        alog_error ("JNI_ONLOAD: vm_global is NOT NULL <- by here");     
    }
    return JNI_VERSION_1_6;
}

void makeCallto_tryBack(){       
    if (vm_global == NULL)
        alog_error ("MAKECALL: vm_global is NULL <- by here");
    else {
        alog_error ("MAKECALL: vm_global is NOT NULL");

        if ((*vm_global)->AttachCurrentThreadAsDaemon(vm_global, &jvm_env, NULL) != 0) {
            alog_error ("JNI Failed to attach thread as daemon");
        //
        // Rest of code for execute Java call to tryCallback
        //
        //  if ((*vm_global)->GetEnv(vm_global, (void**) &jvm_env, JNI_VERSION_1_6) != JNI_OK) {
        //      alog_error ("Failed to get the environment using GetEnv()");
        // }
        // (....)

    }
}

At last, I have a standalone C daemon inited at init.rc that shares library "libtestcontrol" and after some time calls to makeCallto_tryBack method from shared library.

void periodicProccess(){

    makeCallto_tryBack();

  // (...)
}

What happens then, is that "vm_global" reference is always NULL in makeCalltoTryCallback() method, altough is inited correctly not null in JNI_Onload. In other words, there is no persistence of JavaVM vm_global variable after JNI_OnLoad. How can I solve this?

Upvotes: 1

Views: 890

Answers (1)

Alex Cohn
Alex Cohn

Reputation: 57203

Your periodicProcess() runs in a separate process , that's why it does not share the global variables with a Java app. You need some IPC mechanism here.

Upvotes: 1

Related Questions