Code Bit: How to use JNI in Cocos2dx Android?

Thank you, Bojun for helping me understand all this 🙂

You can first read up the Cocos2dx documentation on this: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/How_to_use_jni

Basically JNI is this thing that allows you to call Java code from C++ and vice versa.

I’m gonna post a very round about code that I think shows how to do it both ways.

First off, in Java (my class name is sample.java), I have two additional methods:

public static native void printSomething();

public static void printSomethingFromJava()
{    printSomething();
}

The printSomething method corresponds to a method in my C++, while printSomethingFromJava is a method that is called from my C++.

So far so good?

And then in C++ (HelloWorld.cpp), I have the method that corresponds to the printSomething method in Java:

void Java_com_purple_sample_sample_printSomething(JNIEnv *env, jobject obj)
{    CCNotificationCenter::sharedNotificationCenter()->postNotification(“printSomethingInCPP”, NULL);
}

Basically, when you call printSomething in sample.java, this method is called.

So there, we can call a method in C++ from Java.

Notice the CCNotification (thank you so much, Bojun for teaching me this). Since I can’t call anything in HelloWorld, because it’s not part of the scene, I need to use CCNotification to call any methods from Hello World.

In order for a CCNotification to be called you need to add an observer first, so somewhere in HelloWorld’s init method:

CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::printSomethingInCPP), “printSomething”, NULL);

printSomethingCPP is a method in HelloWorld that essentially adds a CCLabel to our scene:

void HelloWorld::printSomethingInCPP()
{    CCLabelTTF* pLabel = CCLabelTTF::create(“Hello World”, “Thonburi”, 34);

    // ask director the window size
    CCSize size = CCDirector::sharedDirector()->getWinSize();

    // position the label on the center of the screen
    pLabel->setPosition( ccp(size.width / 2, size.height/2) );

    // add the label as a child to this layer
    this->addChild(pLabel);
}

Still following?

So now, we can call a method in C++ from Java, and we use CCNotification to call another method that’s in the HelloWorld scene.

Next up! Calling a Java method from C++.

Remember the printSomethingFromJava method? That is a method that we will call from our C++.

So in C++, I created a method named printSomethingFromJava, and it contains some of these:

void HelloWorld::printSomethingFromJava()
{    JniMethodInfo t;
    if(JniHelper::getStaticMethodInfo(t, “com/purple/sample/sample”, “printSomethingFromJava”, “()V”))
    {    t.env->CallStaticVoidMethod(t.classID, t.methodID);
        // delete reference
        t.env->DeleteLocalRef(t.classID);
    }
}

Now, this code is what calls the printSomethingFromJava method in Java.

I call the printSomethingFromJava method in HelloWorld.cpp in its init method, somewhere after the CCNotificaton Add Observer.

This blog has a list of methods, return calls etc. for Android JNI: http://blog.csdn.net/lizhiguo0532/article/details/7219357.

Okay, so it’s a little confusing, basically what my code does is, HelloWorld (C++) calls a method in sample (java), and sample (java) then calls a method in HelloWorld (C++).

Why do I do this? It’s just an exercise that was pretty helpful for me (I think) to understand the confusing thing that is JNI.

*bows*

Thoughts while reading Cocos2d-X by Example Beginner’s Guide Chapters 1 & 2

Packt published a new book on Cocos2d-X, “Cocos2d-X by Example Beginner’s Guide” by Roger Engelbert (http://www.packtpub.com/cocos2d-x-by-example/book)

Cocos2d-X by Example Beginner's Guide

First off, book cover is adorable.

Second, the book’s spiel says no programming knowledge required, oh really now? Anyway, I know Cocos2d, but I don’t know Cocos2dx nor C++, the language for Cocos2dx, so here I go. If I can make some cookie cutter games at the end of this review then…

I’m just going to spurt words while I read the blog and maybe give an overall summary and reviews at the end of this post. You can ignore the italicized parts, those are just random ramblings.

#nowplaying Lana Del Rey’s Young and Beautiful #onloop after watching “The Great Gatsby” last night.

Chapter 1 covers Installation. Installing Cocos2dx and whatnots.

The book assumes that you are on a Mac and you have Xcode, which yeah, I am and iOS dev and all, I have Xcode.

Okay, the book gives pretty clear instructions on where to download Cocos2dx. now, I just need a few minutes to download them.

Cram my Crash Course for Creativity assignment till then.

Okay, the instructions for installing are pretty clear. Although my Terminal had some other suggestions for how to properly install it. Anyway, that’s done. So when I create a new project in Xcode now I’ll be able to see the different Cocos2dx templates, awesome.

Just “built” and run my first Cocos2dx program, okay, the coconut head is silver and blue now. Looks kinda funky like Pepsi Blue.

Anyway, he did a brief run through on how to run the Cocos2dx samples so that we could see all the infinite possibilities, okay not really infinite, but it’s a pretty long list of sample tests.

And then, he says might need to spend some money on additional tools. He recommend and uses four tools.

TexturePacker, although you can also use Zwoptex as a free alternative. TexturePacker’s Andreas Löw actually used to offer (not sure if he still does, try tweeting him) licenses for bloggers. So yah, I have a free copy of TexturePacker.

ParticleDesigner, which will ease the process of making particles. No, I don’t have that. I’ll probably look for some free alternatives, the author didn’t mention or recommend any.

A tool to help build bitmap fonts, he recommended Glyph designer (not free), bmGlyph (cheaper, but yah, still not free) and FontBuilder (yeah, free). According to him “It is not extremely hard to build a Bitmap font by hand, not nearly as hard as building a particle effect from scratch, but doing it once is enough to convince you to get one of these tools fast.” Back in my Cocos2d days I used Hiero (free) and Photoshop (self advertise: blog on How to Make Fancy Labels using Cocos2d http://purplelilgirl.tumblr.com/post/2854271507/how-to-make-fancy-labels-using-cocos2d).

And according to him, no contest cfxr for sound effects. Free!

And we are done with Chapter 1. We installed Cocos2dx, and run a few sample projects and got to know the structure of basic Cocos2dx applications, so on to Chapter 2.

Chapter 2 gives an intro of C++ and Cocos2dx.

“This chapter will be aimed at two types of developers: the original Cocos2d developer who is scared of C++ but won’t admit it to his friends; and the C++ coder who never even heard of Cocos2d and finds Objective-C funny looking.”

I’m the first type, but I’m not afraid to admit that I’m afraid of C++. I am terrified of C++. If you give me an exam in C++, I will (and have, twice) submit an empty exam sheet (surprisingly passed one of those exams, I think the examiner took pity on account of my C++ phobia).

Can you tell that I’m stalling?

First the author goes through the basics of Cocos2d, if you know Cocos2d then you’re good to go. So far…

And then comes the dreaded C++ bits.

He says, “Don’t worry. The C part is easy, the first plus goes by really fast, but that second plus, Oh, boy.” Er… Oh boy…

I like the way the author talks in this book, kind of entertaining in a way.

He said to open your favorite text editor, because he doesn’t want code hinting and autocomplete features to get in the way. What? How did you think I finished a game in XNA without little knowledge in XNA, and completely zero knowledge in C#?! Code hinting and autocomplete, seriously.

My favorite text editor – TextEdit, because it comes bundled with a Mac. if I were on my PC laptop, I’d say Notepad, because that’s bundled there. I used to write websites in Notepad, those were the days… Yah, still stalling.

C++ syntax. Okay, so far, apprehensive.

Instantiation and Memory Management. Two words, no ARC. “so Objective-C developers who have forgotten memory management might have a problem here.” Uh oh.

The rule regarding memory management with C++ is very simple: if you new, you must delete.” Okay, I get that. And it supposedly has some other options and commands that’s similar to Objective C without ARC, okay.

 And then he continues with how to instantiate stuff. Okay, so far so good. And a little about the Cocos2dx equivalent of Objective C stuff. Okay, understood.

And summary. He says, “hopefully non C++ developers have learned that there is nothing to fear”. Um.. so far, not completely convinced, but I think I can manage.

He ends this chapter with “and furthermore Cocos2dx is awesome!” (fan boy) and “So let’s create a game already!”. 

Yes, lets. But maybe I’ll continue reading this tomorrow.