cocos2dx android c++调用java

C++调用java

1.在jni文件中添加一个helloworld/test.cpp(.h)文件  并且在jni中 android.mk中添加对应的路径

2.在对应的cocos2d-x文件中包含此文件 如:"../android/jni/helloworld/test.h"

3.在test.h声明一个方法:

#ifndef TEST_H
#define TEST_H

extern "C"
{
void sendEmailFunction(const char * index);
}
#endif

对应的cpp文件中

void sendEmailFunction(const char * index)
    {
         JniMethodInfo t;
         if(JniHelper::getStaticMethodInfo(t, "com/newtest2/jniHelper", "GetInfo", "(Ljava/lang/String;)V"))
         {
             jstring jIndex = t.env->NewStringUTF(index);
             t.env->CallStaticVoidMethod(t.classID, t.methodID,jIndex);
             t.env->DeleteLocalRef(jIndex);
         }
    }
注释:com/newtest2 是包的名字 jniHelper是对应的java文件 GetInfo是对应的方法
(Ljava/lang/String;)V传递一个String参数

 4.在对应的jniHelper.java文件中代码如下

private static Handler mhandler;
    
    public static void init(Handler m)
    {
        jniHelper.mhandler=m;
    }
    
    private static void GetInfo(String info)
    {
        Message msg = mhandler.obtainMessage();
        msg.what =newtest2.NUMBER;
        msg.sendToTarget();
    }
注释:此方法需为static方法
Handler是关键

5.在起始java文件(newtest2.java)中调用jniHelper中的方法  代码如下

public final static int NUMBER=0x0001;
    
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        
        jniHelper.init(mhandler);
    }
     
     private Handler mhandler=new Handler()
     {
        @Override
         public void handleMessage(Message msg) {
            switch(msg.what)
            {
            case newtest2.NUMBER:
                sendEmail();
                
                break;
            
            }
         }     
    }
原文地址:https://www.cnblogs.com/mokey/p/3012935.html