How can I access Native Android Classes with parameters?

Hi,

I’m building an Android application in Unity 3D and I need to use a jar file. I need to call a special method inside that jar file and the main calss extends Activity :

 public static void extendWindow(Window w, boolean extend)

Now, I can call any java methods inside android with :

 AndroidJavaClass pluginClass = new AndroidJavaClass("com.myplugin.My_Plugin");
        GetComponent<Text>().text = pluginClass.CallStatic<string>("getMessage");

But how can I create that Window w object inside Android activity and send it as a parameter to Android Java?

pluginClass.CallStatic(“extendWindow”,“Window w”, true);

This is not working, any suggestions?

You have 2 different options to achieve this. Both options use the AndroidJavaObject and AndroidJavaClass classes:

  1. Create another method (in Java) that will simplify things, for example, by creating the Window object in Java. This means you shouldn’t have to worry about creating native Android types in your Unity code (their creation might be a bit long and error prone when done from Unity). In your Unity code you’d call the “simpler” method which will in turn create a Window and pass that to the method in the .jar library that you want to use.
  2. Create a Window object from Unity and pass that as a parameter to the method in your .jar library.

Let’s go with option #2. A bit about AndroidJavaObject - this is a helper class that allows interacting with Java classes in Android. When you construct an object instance, you’re effectively calling the class’s Java constructor with the passed arguments.

In your example, what you’re trying to do is create an instance of the android.view.Window class. Looking at the documentation, there’s only 1 constructor that looks like this: Window (Context context)

So, the Unity you should be using may look something like this:
// Create a reference to the plugin class
AndroidJavaClass pluginClass = new AndroidJavaClass(“com.myplugin.My_Plugin”);

// Get Unity's main activity (Context)
var actClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) 
var context = actClass.GetStatic<AndroidJavaObject>("currentActivity");

// Create an android.view.Window instance (should pass a Context as a parameter)
AndroidJavaObject window = new AndroidJavaObject("android.view.Window", context);
pluginClass.CallStatic<string>("extendWindow", window);

A couple of things to note:

  1. I haven’t tested this code, but it should work.
  2. AndroidJavaObjects implement a Dispose method to dispose of native JNI resources. all calls for creating such objects must be wrapped in proper using (…) clauses in production code to avoid any issues.