AndroidJavaClass and AndroidJavaObject question

I have a class named MyClass,it inherited from UnityPlayerActivity,it also has a method

public int getValue(){
return 20;
}

I want to use AndroidJavaObject to get this value of this method.
my code as following:

using(AndroidJavaObject obj=new AndroidJavaObject("com.mxr.test.MyClass")){	
value=obj.Call<int>("getValue");	
}

but,when I run it,I can’t get the value,
any body can help me? thanks a lot

Did you managed to solve this? I assume that it must be a really noob question because it has no answer, but I am right now trying to understand all this and I am facing the same problem. Could you give me a hand? Thx in advance!

Yes! I got the same problem! Did you sort it out? thanks!

1 Answer

1

When you inherit from UnityPlayerActivity, I suppose you also use this as the main activity for the game (also involves creating a new AndroidManifest.xml that declares that your activity will be used).

In this case, when you launch your game on Android, the OS will create an instance of the Activity class for you and call its relevant callbacks (e.g: onCreate, onResume, etc).

In your code, you attempt to create an AndroidJavaObject with the name of the class you given your new Activity.

However, according to the AndroidJavaObject constructor documentation:

Construct an AndroidJavaObject based
on the name of the class.

This essentially means locate the
class type, allocate an object and run
the specified constructor.

This means you are attempting to create another instance of your class. IIRC, you cannot instantiate an Activity class yourself as it has no public constructor (it is created for you by the Android OS).

Therefore, what happens in your case i guess is that Unity “swallows” some error and doesn’t do anything.

What you’d like to do is keep some static field that stores a reference to the created activity object, and then use that to call methods on it.

See this answer for more details: AndroidJavaClass. Call returns null ptr. - Questions & Answers - Unity Discussions