首页 > 代码库 > Cocos2d-x通过Jni实现Cocos2d-x界面跳转到新的Activity
Cocos2d-x通过Jni实现Cocos2d-x界面跳转到新的Activity
废话不多说,直接上源码
1、Java层
1)首先在org.cocos2dx.cpp目录下添加新类UserInfoActivity.java,该类自行定义即可,代码如下:
package org.cocos2dx.cpp; import com.pactera.jni.R;//注意路径 import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.content.Intent; public class UserInfoActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.userinfo); Intent intent = getIntent(); String string = intent.getStringExtra("name"); TextView textView = new TextView(this); textView.setTextSize(40); textView.setText(string); setContentView(textView); } }2)AppActivity.java类
package org.cocos2dx.cpp; import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.Cocos2dxGLSurfaceView; import android.content.Intent; import android.os.Bundle; public class AppActivity extends Cocos2dxActivity{ public static final int SHOW_DIALOG = 0x0001; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } //设置OpenGL的相关信息 public Cocos2dxGLSurfaceView onCreateView() { Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this); // GuideLayer should create stencil buffer glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8); return glSurfaceView; } //加载Cocos2d-x的库 static { System.loadLibrary("cocos2dcpp"); } public static void Share(){ //Jni的Java层nativa代码,在Jni目录下的test.cpp实现,并被C++调用 Intent intent = new Intent(); intent.setClass(AppActivity.getContext(), UserInfoActivity.class); intent.putExtra("name", "Hello World"); AppActivity.getContext().startActivity(intent); } }
2、Jni层
jni目录下添加test类的.h和.cpptest.h
#ifndef TEST_H_ #define TEST_H_ extern "C" { //C++调Java的函数接口,该方法在HelloWorldScene中menuCallback函数中使用。 void Share(); } #endiftest.cpp
#include "test.h" #include "cocos2d.h" #include "platform/android/jni/JniHelper.h" #include "../../../Classes/JniTest.h" #include <jni.h> //#define CLASS_NAME "org/cocos2dx/cpp/JniTestHelper" #define CLASS_NAMENEW "org/cocos2dx/cpp/AppActivity" using namespace cocos2d; extern "C" { void Share() { bool hasMethod; JniMethodInfo t; hasMethod = JniHelper::getStaticMethodInfo(t,CLASS_NAMENEW,"Share","()V"); if(hasMethod) { log("Share function"); if(t.methodID) { t.env->CallStaticVoidMethod(t.classID,t.methodID); log("function share() was called"); }else{ log("function share was not called"); } }else { log("function share was not found"); } } }
3、C++层
void HelloWorld::menuCloseCallback(Ref* pSender) { #if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) Share(); #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }
4、注意事项
添加平台判断头文件#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "../proj.android/jni/hellocpp/test.h" #endif
5、运行结果
Cocos2d-x通过Jni实现Cocos2d-x界面跳转到新的Activity
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。