Android uses C to callback Java via JNI

Source: Internet
Author: User

Many occasions have such a demand, because the previous Java call C interface, did not make a callback, today spent a large half a day to run through the process, record, for later use. Here is a grumble, those who share the code on the Internet, I ask you really can work properly? And check to find out are the several, we reproduced the spirit of commendable AH

JNI Related header file code

/* Don't EDIT this file-it are machine generated */#include/* Header for Class Com_example_ndktest_callbacktest */#ifnde F _included_com_example_ndktest_callbacktest#define _included_com_example_ndktest_callbacktest#ifdef __ Cplusplusextern "C" {#endif/** class:com_example_ndktest_callbacktest* method:start* Signature: () V*/jniexport void Jnicall Java_com_example_ndktest_callbacktest_start (jnienv *, jobject); #ifdef __cplusplus} #endif #endif




Specific implementation code

 #include <stdlib.h> #include <pthread.h> #include <jni.h> #include <android/log.h> #include " Com_example_ndktest_callbacktest.h "#define LOG_TAG" JNI "#define LOGD (...) __android_log_print (Android_log_debug, Log_tag, __va_args__) jmethodid mid;jclass objclass;jobject mobj;pthread_t thread; JAVAVM *m_vm;//initialization will be redeployment once, in this method holds a reference to the JVM jniexport jint jnicall jni_onload (JAVAVM *vm, void *reserved) {    m _vm=vm;    jnienv* env = null;    Jint result = -1;    if (M_VM) {        LOGD ("M_VM init Success");   }else{        LOGD ("M_VM init failed");   }  & nbsp if ((*VM)->getenv (VM, (void**) &env, jni_version_1_4)! = JNI_OK) {        return result;  & nbsp }    return jni_version_1_4;} jnienv* getjnienv (int* needsdetach) {    jnienv* env = null;    Jint result = -1;    if ((*m_ VM)->getenv (M_VM, (void**) &env, jni_version_1_4)! = JNI_OK) {        int status = (*M_VM)->attachcurrentthread (M_VM, &env, 0); & nbsp       if (Status < 0) {            LOGD ("Failed to attach current thread");             return null;       }        *NEEDSDETAC h = 1;   }    LOGD ("GetEnv Success");    return env;} void *thread_run () {     LOGD ("thread Start");    int needsdetach;    JNIENV *evn= Getjnienv (&needsdetach);    LOGD ("Start NoOp callback");    int i;    for (i = 0; i < 100;  i++) {        jstring jstr = (*EVN), Newstringutf (EVN, "I am Fengfei");         LOGD ("Invoke callback");        (*EVN)->callvoidmethod (EVN, Mobj, Mid, Jstr);        Jthrowable exception = (*EVN)->exceptionoccurreD (EVN);        if (exception) {            (*EVN)->exceptiondescribe ( EVN);       }        sleep (2);     }    if (Needsdetach) & nbsp       (*M_VM)->detachcurrentthread (M_VM);} Jniexport void Jnicall Java_com_example_ndktest_callbacktest_start (jnienv *evn, Jobject object) {LOGD ("call start");    //cannot be used in a child thread    //jclass Tclass = (*EVN)->findclass (EVN, "Com/example/ndktest/callbacktest" );   //This notation can be used in sub-threads     objclass= (*EVN)->getobjectclass (EVN, Object);    mid = (*EVN)- >getmethodid (EVN, Objclass, "callback", "(ljava/lang/string;) V");   //jni function Parameters Jobject or its subclasses, whose parameters are Local reference. The Local reference is only valid in this JNI function, and when the JNI function returns, the referenced object is freed and its life cycle is over. For future use, you will need to create a global reference based on this local reference. The Global reference is not automatically released by the system and is recycled only when the program explicitly calls Deleteglobalreference. (JNI multithreading mechanism)     mobj=(*EVN)->newglobalref (EVN, object);    pthread_create (&thread, NULL, thread_run, NULL);} 

Java code (how to generate. So, see Android NDK use)

Package Com.example.ndktest;public class Callbacktest {static {    system.loadlibrary ("callback");} Public native void Start ();p ublic Void callback (String str) {    System.out.println (str);}



Android uses C to callback Java via JNI

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.