Calling non-static java method?

Calling non-static java method?


I know to call a static method from c++ you use
cocos2d::JniHelper::callStaticVoidMethod(“org.cocos2dx.cpp/AppActivity”, “shareMyScore”, score);

but why does it have to be static ? is there a way for it to be non-static because in some of my java methods its not letting me use certain objects since they are not declared static, so I would like to make the java method non-static if possible ?


It’s only possible, if you have an instance pointer of the class. Because you c++ environment doesn’t know about the Java world, it not that trivial. See for example

I didn’t tested it, but it should be possible to call a static method in your Activity and within it, you have a pointer to your Activity instance (Cocos2dxHelper.getActivity()). With that you are able to call any non static function. Maybe this will help you.


Thanks @mars3142 !


This is the reason I wanted to but maybe there’s a way to make it work with static method ? I did get it to work with static but then I got a warning that making a android context class referenced to static will cause memory leak so I have to figure something else out


Because Cocos2dxHelper.getActivity() is currently holding the Activity/Context, it could already be a memory leak. I’m also not happy with that, but it’s working for years :wink:

PS: Regarding to your SO post. You should create a public function in your activity and call it from the Activity like ((MyActivity) Cocos2dHelper.getActivity().showConsent(). This should work.


That’s true didn’t think about that it could already be a memory leak, there’s not any other way of doing it that would prevent a memory leak ?, could we see on android studio if memory leaks are being created ? , thanks I will try that method when I get home hopefully it works


The Activity will created new on orientation change. If you lock your game to one orientation, if’s nearly impossible to leak the activity. You can make a memory dump in the profiler view and check if your Activity has more than 1 instance, but before you dump the memory, force the garbage collector multiple time so it can clean up the memory first.


I think in case orientation change should be no leak as variable will be assigned with new value and old will be freed.


which variable will be assigned with new value ?


private static Cocos2dxActivity sContext = null;