Creating an Android Plugin for Unity

Reuben
2 min readSep 28, 2017

--

I’m playing around with thought of having a Myo-enabled VR game using Google cardboard and unity

The problem: Myo does not have support for android in it’s Unity SDK

They have a native android SDK and I tried to import the SDK directly into Unity, but it didn’t work.

My next step was to start building my own SDK. But wait, how would I build it in a way that is compatible with Unity. I googled around hoping to find what I needed. Google never failed me so far and I found this really great article. The challenge here though is that they used Apache Ant. I’m an not an expert Android developer, so when I installed Android Studio, I was disappointed. No Ant Build support. Only Gradle. :(

Unity though has documentation on how to import native Android aar/jar plugin. Yes!

I started playing around by making a simple Android library that would return a string back, so I could understand how it works. My class has two functions, a method and a static function.

public class AndroidPluin {

DatePickerDialog diag ;
private static OnDateSetListener listener;

public AndroidPluin(OnDateSetListener listener){
this.listener = listener;
}

public static String getTextFromPluginStatic(int number){
Log.d(“AndroidPluin”,”getTextFromPluginStatic = “+number);
return “return static number is “+number;
}

public void getMessageCallback(){
Log.d(“AndroidPluin”,”getMessageCallback”);
this.listener.CallFunc();
}

public String getTextFromPlugin(int number){
Log.d(“AndroidPluin”,”getTextFromPlugin = “+number);
return “return number is “+number;
}

}

To call the static function in Unity

using (var androidPlugin = new AndroidJavaClass (“com.reuben.unityplugin.AndroidPluin”)) {
if (isStatic) {
var opS = androidPlugin.CallStatic<string> (“getTextFromPluginStatic”, (int)mainSlider.value);
Debug.Log (“Static output = “+opS);
outputText.text = opS;
} }

I also added an interface to see how I would need to implement it in Unity

public interface OnDateSetListener {
void CallFunc();
}

To implement this interface in Unity

class DateCallback : AndroidJavaProxy
{
public DateCallback() : base(“com.reuben.unityplugin.OnDateSetListener”) {}
void CallFunc()
{
Debug.Log (“onCallFunc”);
}
}

Now to call this in Unity

AndroidJavaObject jo = new AndroidJavaObject (“com.reuben.unityplugin.AndroidPluin”, new DateCallback());

var opJNI = jo.Call<string> (“getTextFromPlugin”, (int)mainSlider.value);
Debug.Log (“JNI output = “ + opJNI);
outputText.text = opJNI;

jo.Call(“getMessageCallback”);

The only thing remaining was to build the android plugin. Once this was built, I created the following folder structure Assets/Plugins/Android and imported the aar file there. After that just build and run! :)

https://github.com/alt-ctrl-dev/UnityCustomSDK

--

--