Jnihelper call Java static and non-static method summary (that is, COCOS2DX in the call Android platform display third-party ads)

Source: Internet
Author: User

Calling a non-static method is the first way to call a static method to get the Java class object to call and then by calling
Minfo.env->callvoidmethod (Activityobj, Minfo.methodid); method takes the object and the method and arguments to invoke, if any


) passes a non-static method in a Java class object;


Java class:


How to adjust in C + +
public static Object rtnactivity () {
System.out.println ("----------rtnactivity");
return mainactivity;
}

public void Showad () {
LOG.I ("Test", "Jnihelper do ... show ad");
Ad
Display in-stream ads, can not call Loadspot Independent use
Spotmanager.getinstance (mainactivity.this). Showspotads (
Mainactivity.this, New Spotdialoglistener () {
@Override
public void onshowsuccess () {
LOG.I ("Spotad", "show success");
}


@Override
public void onshowfailed () {
LOG.I ("Spotad", "Show failure");
}


});
}
Replace the red part with the ad you want to show.

C + + calls CPP:


Determine whether the Android platform is currently active;
#if (Cc_target_platform = = cc_platform_android)

Define the information structure of the JNI function;
Jnimethodinfo Minfo;
Returns a bool value indicating whether this function was found;
BOOL Ishave = Jnihelper::getstaticmethodinfo


(Minfo, "org/cocos2dx/hellocpp/mainactivity", "Rtnactivity", "() ljava/lang/object;");
Jobject activityobj;
if (Ishave) {
Callstaticobjectmethod calls the Java function and assigns the return value to Activityobj
Activityobj = Minfo.env->callstaticobjectmethod (Minfo.classid, Minfo.methodid);
}


2. Find the Displaywebview interface, get its function information, and call it with jobj;
Define the information structure of the JNI function;
Ishave = Jnihelper::getmethodinfo (Minfo, "org/cocos2dx/hellocpp/mainactivity", "Showad",


"() V");


if (!ishave)
{
Cclog ("Jni:showad function does not exist;");
}
Else
{
Call the Displaywebview function and pass in the parameter
Minfo.env->callvoidmethod (Activityobj, Minfo.methodid);
}

#endif

See Split Line section for a Java non-static method to invoke parameters

-----------------Gorgeous split-line---------------------------------------------

Main ideas
Get the Java virtual machine through JNI, get the JNI environment of the current program, get the Java class information that needs to be called through the JNI environment, and get the function information in the Java class that needs to be called. The corresponding Java functions are invoked using the class information and function information through the JNI environment.
It seems a bit complicated, but don't worry, there is a Jnihelper class in cocos2d-x (the copyright of the header file is: cocos2d-x.org, it is provided by Google or the Cocos2d-x group of its own package I do not know), It has encapsulated the work.




Use of the Jnihelper class
Add the following header file:


#include "Platform/android/jni/jnihelper.h"
The interface you need to use is as follows:


static bool Getstaticmethodinfo (Jnimethodinfo &methodinfo, const char *classname, const char *methodname, const char * Paramcode);
static bool Getmethodinfo (Jnimethodinfo &methodinfo, const char *classname, const char *methodname, const char *PARAMC ODE);
On the implementation we only need to use the above two interfaces, we can get all the functions of the Java class information. The acquisition of the JNI environment and the various error handling are already encapsulated in these two interface implementations.
First the code, then the meaning of each parameter and how to use it:


function Information Structure body
Jnimethodinfo Minfo;
BOOL Ishave = Jnihelper::getstaticmethodinfo (reference to Minfo,/*jnimethodinfo */
Path for "Com/omega/myapp",/* class */
"Getjavaactivity",/* Function name */
"() Ljava/lang/object;"); * Function Type Shorthand */
Jobject activityobj;
if (Ishave)
{
Callstaticobjectmethod calls the Java function and assigns the return value to Activityobj
Activityobj = Minfo.env->callstaticobjectmethod (Minfo.classid, Minfo.methodid);
}
OK, very simple. The code above is a typical use of a Java class static function called in C + + using JNI. There are only two steps:


1. Get information about Java functions, ClassID, Methodid, etc.
2. Select an interface in the jnienv to make a function call
Getstaticmethodinfo parameter explanation
Two interface parameters, the same meaning is the same, explained below:
Jnimethodinfo a reference to the &methodinfo Jnimethodinfo object, the JNIEVN, ClassID, and Methodid are written to the reference in the function execution.
const char *classname the path to the class, write the full package name of the class, and use the code as above.
The const char *methodname function name, the function name is written on the line.


const char *paramcode function type shorthand
This parameter needs to be described separately, in the form of: (parameter) return type.
For example: no parameter, void return type function, abbreviated as () V
The types in Java correspond to the following abbreviations:


Parameter type parameter shorthand
Boolean Z
BYTE B
Char C
Short S
int I
Long J
Float F
Double D
void V
Object ljava/lang/string; L use/split the full path of the class
Array [ljava/lang/string; [Signature [I
Functions with multiple parameters
If the function has more than one parameter, simply parallel the shorthand. Note the semicolon at the end of the object with the array type parameter shorthand, example:
IIII//4 functions of int type parameter
Iljava/lang/string;i//shaping, String type, shaping combination (int x, string a, int y)


function calls via JNIEnv
JNIEVN has a series of callstatic[return type]method, call[return type]method interfaces that need to be called for different function return type selection.
[Return type] is different from the function return type, corresponding to a different function name.
For example:
Callstaticvoidmethod ——— Void
Callvoidmethod ——— Void
The corresponding relationship is as follows:


Function name function return value type
void void
Object Jobject
Boolean Jboolean
Byte Jbyte
Char Jchar
Short Jshort
Int Jint
Long Jlong
Float jfloat
Double jdouble
Parameter passing
When invoking a Java function with parameters, the corresponding arguments need to be passed in. Parameters need to be added sequentially to ClassID, Methodid, and type conversions are required. For example:


Jint JX = 10;
Jint JY = 10;
Minfo.env->callstaticvoidmethod (Minfo.classid, Minfo.methodid, JX, JY);
The parameter type conversion relationship is as follows:


C + + type Java type
Boolean Jboolean
BYTE jbyte
Char Jchar
Short Jshort
int Jint
Long Jlong
Float Jfloat
Double jdouble
Object Jobject
Class Jclass
String jstring
Object[] Jobjectarray
Boolean[] Jbooleanarray
Byte[] Jbytearray
Char[] Jchararray
Short[] Jshortarray
Int[] Jintarray
Long[] Jlongarray
Float[] Jfloatarray
Double[] Jdoublearray
Conversion of String type
In fact, our most commonly used parameter types are mainly built-in data types, string string types. The data type can be converted directly to type J, but the string type needs to be handled as follows:


Jstring jmsg = Minfo.env->newstringutf ("http://www.baidu.com");
Minfo.env->callstaticvoidmethod (Minfo.classid, Minfo.methodid, jmsg);
Calls to non-static functions
A call to a non-static function is a call type of a static function, but a Java class object needs to be obtained through a static function.
Example:


C + + code
1. Get activity Static Object
Jnimethodinfo Minfo;
BOOL Ishave = Jnihelper::getstaticmethodinfo (Minfo,
"Com/omega/myapp",
"Getjavaactivity",
"() Ljava/lang/object;");
Jobject activityobj;
if (Ishave)
{
Call the static function getjavaactivity to get the Java class object.
Activityobj = Minfo.env->callstaticobjectmethod (Minfo.classid, Minfo.methodid);
}


2. Find the Displaywebview interface, get its function information, and call it with Jobj
Ishave = Jnihelper::getmethodinfo (Minfo, "Com/omega/myapp", "Displaywebview", "(IIII) V");


if (!ishave)
{
Cclog ("Jni:displaywebview function does not exist");
}
Else
{
Call this function
Jint JX = (int) TlX;
Jint JY = (int) TlY;
Jint jwidth = (int) webwidth;
Jint jheight = (int) webheight;
Call the Displaywebview function and pass in the parameter
Minfo.env->callvoidmethod (Activityobj, Minfo.methodid, JX, JY, Jwidth, jheight);
}
Detailed Sample Code
Finally, put a more detailed JNI usage code, basically covering all the usage.


Jnimethodinfo Minfo;//jnihelper


/* Test method */
/*bool Ishave = Jnihelper::getstaticmethodinfo (Minfo, "Com/cocoa/hiworld", "Logingree", "() V"); //
if (Ishave) {
Cclog ("with Showtext");
Minfo.env, Callstaticvoidmethod (Minfo.classid,minfo.methodid);
}else
{
Cclog ("no Method Showtext");
}*/


/* Share */
/*//converts a string in C + + to a string in Java
Char str[] = "Test";
BOOL Ishave = Jnihelper::getstaticmethodinfo (Minfo, "Com/cocoa/hiworld", "Sharesina", "(ljava/lang/string; ljava/lang/string;) V "); //
if (Ishave) {
Cclog ("with share");
Jstring jstr = Minfo.env->newstringutf ("Test1 share");
jstring JST = Minfo.env->newstringutf ("/data/data/com.cocoa/cy.png");
jstring JST = Minfo.env->newstringutf ("");
Minfo.env, Callstaticvoidmethod (MINFO.CLASSID,MINFO.METHODID,JSTR,JST);
}else
{
Cclog ("No Method share");
}*/
/* Set HIGH Score */
/*jint ind = 0;
Jlong lsre = 2202l;
BOOL Ishave = Jnihelper::getstaticmethodinfo (Minfo, "Com/cocoa/hiworld", "Sethighscore", "(IJ) V");
if (Ishave) {
Minfo.env, Callstaticvoidmethod (MINFO.CLASSID,MINFO.METHODID,IND,LSRE);
}*/
/* Achievement Unlocking */
/*jint aind = 0;
BOOL Ishave = Jnihelper::getstaticmethodinfo (Minfo, "Com/cocoa/hiworld", "UnLock", "(I) V");
if (Ishave) {
Minfo.env, Callstaticvoidmethod (Minfo.classid,minfo.methodid,aind);
}*/
/* Test method */
BOOL Ishave = Jnihelper::getstaticmethodinfo (Minfo, "Com/cocoa/hiworld", "Rtnactivity", "() ljava/lang/object;");
Jobject jobj;
if (Ishave) {
Jobj = Minfo.env->callstaticobjectmethod (Minfo.classid, Minfo.methodid);
}
Cclog ("jobj existence");
/* Test method, non-static no parameter return value method */
/*ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld", "Showtext", "() V");
if (Ishave) {
Minfo.env, Callvoidmethod (Jobj,minfo.methodid);
}*/
/* Test method, non-static string parameter with Java type no return value method */
/*ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld", "Showtext", "(ljava/lang/string;) V");
if (Ishave) {
Jstring jmsg = Minfo.env->newstringutf ("msg okey!");
Minfo.env, Callvoidmethod (jobj,minfo.methodid,jmsg);
}*/
/* Test method, return string of Java type, string and int parameter method of Java type */
/*ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld", "Showtext", "(ljava/lang/string;i) Ljava/lang/String ;");
if (Ishave) {
Jstring jmsg = Minfo.env->newstringutf ("msg okey! return string ");
Jint index = 0;
Minfo.env, Callobjectmethod (Jobj,minfo.methodid,jmsg,index);
}*/
/* Test method, return Java type string[], Java type string[] and int parameter method */
/*ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld", "Showtext", "([Ljava/lang/string;i) [Ljava/lang/] String; ");
if (Ishave) {
Jobjectarray args = 0;
Jstring str;
Jsize len = 5;
Const char* sa[] = {"Hi,", "world!", "JNI", "is", "Fun"};
int i = 0;
args = Minfo.env->newobjectarray (Len,minfo.env->findclass ("java/lang/string"), 0);
For (I=0;inewstringutf (Sa[i]);
Minfo.env->setobjectarrayelement (ARGS,I,STR);
}
Minfo.env->getstringarrayregion (ARGS,0,10,BUF);
Jintarray jmsg = {n/a};
Minfo.env->newstringutf ("Msg okey! return string ");
Jint index = 0;
Minfo.env, Callobjectmethod (Jobj,minfo.methodid,args,index);
}*/
/* Test method, no return type, Java type int[] and int parameter method */
/*ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld", "Testarr", "([II) V");
if (Ishave) {
Jint buf[]={7,5,8,9,3};
Jintarray Jintarr; Defining Jint Arrays
Jintarr = Minfo.env->newintarray (5);
Minfo.env->setintarrayregion (JINTARR,0,5,BUF);
Jint index = 0;
Minfo.env, Callvoidmethod (Jobj,minfo.methodid,jintarr,index);
}*/
/* Test method, no return type, Java type byte[] and int parameter method */
Ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld", "Testarr", "([BI) V");
if (Ishave) {
Jbyte buf[]={7,5,8,9,3};
Jbytearray Jbytearr; Defining Jbyte Arrays
Jbytearr = Minfo.env->newbytearray (5);
Minfo.env->setbytearrayregion (JBYTEARR,0,5,BUF);
Jint index = 0;
Minfo.env, Callvoidmethod (Jobj,minfo.methodid,jbytearr,index);
}
private static Hiworld Hiworld = null;
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Hiworld = this;
if (detectOpenGLES20 ()) {
Get the Packagename,it ' s used to set the resource path
String PackageName = Getapplication (). Getpackagename ();
Super.setpackagename (PackageName);
Set content
Setcontentview (R.layout.game_demo);
GetWindow (). Setfeatureint (Window.feature_custom_title,
R.layout.window_title);


Mglview = (Cocos2dxglsurfaceview) Findviewbyid (R.id.game_gl_surfaceview);
Mglview.settextfield ((Cocos2dxedittext) Findviewbyid (R.id.textfield));
Mglview.seteglcontextclientversion (2);
Mglview.setcocos2dxrenderer (New Cocos2dxrenderer ());
task = new TimerTask () {
@Override
public void Run () {
Hiworld.shoot (Hiworld);
LOG.E ("-------------------", "-------------------");
Invoke a method in C + +
System.out.println ("------------------------"
+ stringZjy1 ());
}
};
Timer = new timer ();
Timer.schedule (task, 5000);
} else {
LOG.D ("Activity", "don ' t support gles2.0");
Finish ();
}


static {
System.loadlibrary ("Game");
}


How to adjust in C + +
public static Object rtnactivity () {
System.out.println ("----------rtnactivity");
return hiworld;
}


Methods for use in C + +, passing string types
public void Showtext (Final String msg) {
Add to main thread
Hiworld.runonuithread (New Runnable () {
public void Run () {
System.out.println ("----------msg:" +msg);
}
});
}
Methods used in C + + to pass string types and int types
public string Showtext (final string msg,final int index) {
Add to main thread
Hiworld.runonuithread (New Runnable () {
public void Run () {
System.out.println ("----------msg:" +msg+ "; index= "+index);
}
});
Return "Okey string Showtext (final string msg,final int index)";
}
Methods used in C + +, string[] types and int types
Public string[] Showtext (final string[] msg,final int index) {
String[] Strarr = {"1", "2", "3", "4", "5"};
Add to main thread
Hiworld.runonuithread (New Runnable () {
public void Run () {
for (String _str:msg) {
System.out.println ("----------string[] msg:" +_str+ "; index= "+index);
}
}
});
return strarr;
}
Methods used in C + +, int[] types and int types
public void Testarr (final int msg[],final int index) {
Add to main thread
Hiworld.runonuithread (New Runnable () {
public void Run () {
System.out.println ("----------int[] msg len:" +msg.length);
for (int _bl:msg) {
System.out.println ("----------int[] msg:" +_bl+ "; index= "+index);
}
}
});
}
Methods used in C + +, int[] types and int types
public void Testarr (final byte msg[],final int index) {
Add to main thread
Hiworld.runonuithread (New Runnable () {
public void Run () {
System.out.println ("----------byte[] msg len:" +msg.length);
for (int _bl:msg) {
System.out.println ("----------byte[] msg:" +_bl+ "; index= "+index);
}
}
});
}

Jnihelper call Java static and non-static method summary (that is, COCOS2DX in the call Android platform display third-party ads)

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