Java layer function interaction between c/c ++ and Android using JNI in cocos2d-x

Source: Internet
Author: User

1. JNI

JNI is the abbreviation of Java Native Interface. Java Native Interface (JNI) standards have become part of the java platform since Java1.1. It allows Java code to interact with code written in other languages. JNI was initially designed for locally compiled languages, especially C and C ++, but it does not prevent you from using other languages, as long as the call conventions are supported.

JNI implementation process:

2. Interaction between C ++ and java:

Note: For cross-platform cocos2d-x, unless necessary, otherwise you do not have to go into the details, for example, to use the inherent features of the Android platform, it is necessary to learn more about the use of Jni, and more details about the Android operating system.

3. instance:


(1) obtain the PackageName of the application through the Android sdk API, and then pass it to the c ++ layer function.
(2) Call the java-layer function of Android through the c ++ function. A dialog box is displayed, and click the button to exit the program.

4. Implementation steps:

4.1 Create Project DialogBox with cocos2d-x and match android Environment

Android environment,

4.2 c ++

First in the win32 environment, compile and provide android to call the c ++ interface:

JniTest. h

#ifndef JNI_TEST_H#define JNI_TEST_H#include "cocos2d.h"using namespace cocos2d;void setPackageName(const char *packageName){CCLog("packageName: %s", packageName);}void exitApp(){CCDirector::sharedDirector()->end();}#endif

Call the android API:

HelloWorldScene. cpp

#include "HelloWorldScene.h"#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)#include "../"#endifUSING_NS_CC;void HelloWorld::menuCloseCallback(CCObject* pSender){#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)showTipDialog("exit", "alexzhou,really go?");#endif#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)exit(0);#endif}

Note: you only need to change HelloWorldScene.

Go to the android platform and write the jni-Layer Code:

Test. h

#ifndef TEST_H#define TEST_Hextern "C"{void showTipDialog(const char *title, const char *msg);}#endif
Test. cpp

#include "cocos2d.h"#include 
  #include "platform/android/jni/JniHelper.h"#include "test.h"#include "JniTest.h"#define CLASS_NAME "com/DialogBox/org/JniTestHelper"using namespace cocos2d;extern "C"{void showTipDialog(const char *title, const char *msg){JniMethodInfo t;if(JniHelper::getStaticMethodInfo(t, CLASS_NAME, "showTipDialog", "(Ljava/lang/String;Ljava/lang/String;)V")){jstring jTitle = t.env->NewStringUTF(title);jstring jMsg = t.env->NewStringUTF(msg);t.env->CallStaticVoidMethod(t.classID, t.methodID, jTitle, jMsg);t.env->DeleteLocalRef(jTitle);t.env->DeleteLocalRef(jMsg);}}void Java_com_DialogBox_org_JniTestHelper_setPackageName(JNIEnv *env, jobject thiz, jstring packageName){const char *pkgName = env->GetStringUTFChars(packageName, NULL);setPackageName(pkgName);env->ReleaseStringUTFChars(packageName, pkgName);}void Java_com_DialogBox_org_JniTestHelper_exitApp(JNIEnv *env, jobject thiz){exitApp();}}

Note: extern "C" must be added here, and the statement is compiled in c language. Because c ++ and C generate different function signatures during compilation, you can find relevant information on the Internet, otherwise, a link error occurs during running.

4.3 Java section:

The c ++ function calls the java-layer function and displays a dialog box:

JniTestHelper. java

Package; import org. cocos2dx. lib. cocos2dxHandler. dialogMessage; import android. OS. handler; import android. OS. message; public class JniTestHelper {private static Handler mHandler; public static void init (Handler handler) {JniTestHelper. mHandler = handler;} public static native void setPackageName (String packageName); public static native void exitApp (); // The c ++ function calls the java layer function, display a dialog box private static void showTipDialog (final String title, final String text) {Message msg = mHandler. obtainMessage (); msg. what = DialogBox. SHOW_DIALOG; DialogMessage dm = new DialogMessage (title, text); msg. obj = dm; msg. sendToTarget ();}}
Create a DialogMessage. java that encapsulates the data to be displayed by the dialog:

package;public class DialogMessage {public String title;public String msg;}
Modify the main program DialogBox. java

Public class DialogBox extends Cocos2dxActivity {public static final int SHOW_DIALOG = 0x0001; protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); JniTestHelper. init (mHandler); JniTestHelper. setPackageName (this. getPackageName ();} public Cocos2dxGLSurfaceView onCreateView () {Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView (this); // GuideLayer shocould create stencel buffer glSurfaceView. setEGLConfigChooser (5, 6, 5, 0, 16, 8); return glSurfaceView;} static {System. loadLibrary ("cocos2dcpp");} // function of the displayed dialog box private Handler mHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {switch (msg. what) {case SHOW_DIALOG: DialogMessage dm = (DialogMessage) msg. obj; new AlertDialog. builder (DialogBox. this ). setTitle (dm. titile ). setMessage (dm. message ). setNegativeButton ("cancle", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {dialog. dismiss ();}}). setPositiveButton ("OK", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {dialog. dismiss (); JniTestHelper. exitApp ();}}). create (). show (); break ;}}};}

Compile and run the program. The effect is as follows:


Related Article

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: 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.