声明:因网易博客将关闭,移到此
这里主要在cocos2d-x中调用android中类的静态函数,如果是普通函数就自己探索了
说多无益,直接上代码
cocos2d-x部分
#ifndef __HELPER_H__
#define __HELPER_H__
#include <iostream>
namespace MGame
{
class PlatformHelper
{
public:
static PlatformHelper *shared();
void doAction(const std::string& key, const std::string& message);
};
}
#endif // __HELPER_H__
#include "PlatformHelper.h"
#include "cocos2d.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#include "platform/android/jni/JniHelper.h"
#include <android/log.h>
#endif
//===================== android ======================
#define ANDROID_CLASS_NAME "org/cocos2dx/Game/JavaHelper"
#define ANDROID_FUNCTION_NAME "doAction"
#define ANDROID_PARAM_TYPE "(Ljava/lang/String;Ljava/lang/String;)V"
namespace MGame
{
static PlatformHelper * s_PlatformHelperShared = NULL;
PlatformHelper *PlatformHelper::shared()
{
if (s_PlatformHelperShared == NULL)
s_PlatformHelperShared = new PlatformHelper;
return s_PlatformHelperShared;
}
void PlatformHelper::doAction(const std::string& key, const std::string& message)
{
// android
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
USING_NS_CC;
JniMethodInfo methodInfo;
bool isHave = JniHelper::getStaticMethodInfo(methodInfo, ANDROID_CLASS_NAME,
ANDROID_FUNCTION_NAME,
ANDROID_PARAM_TYPE);
if (isHave)
{
jstring key_arg = methodInfo.env->NewStringUTF(key.c_str());
jstring msg_arg = methodInfo.env->NewStringUTF(message.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, key_arg, msg_arg);
}
else
{
}
#else
#endif
}
}
java部分
package org.cocos2dx.Game;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
public class JavaHelper {
private static Context s_context;
/**
* 初始化内容信息
* @param context
*/
public static void initContext(Context context){
s_context = context;
}
public static void doAction(String key, String message){
Message msg = new Message();
msg.what = Integer.parseInt(key);
msg.obj = message;
handler.sendMessage(msg);
}
static Handler handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
}
String message = (String)msg.obj;
Toast.makeText(s_context, message, Toast.LENGTH_SHORT).show();
}
};
}
剩下的就是在
public class Game extends Cocos2dxActivity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
JavaHelper.initContext(this);
}
基本做法就是这样只,而java调用cocos2d-x的话,后面在看