HowTo: native Android plugins for Unity3D

Categories:Lab, Technology, Tutorial

This article is part 2 of the series on Creating native mobile plugins, you can find part 1 here.
In the previous part we talked about the way to create, code and implement a Unity3D native plugin for iOS.
This time we will be covering the Android platform and creating a native Unity3D plugin for that platform.

This article will cover the creation an .AAR file.

The AAR file type is primarily associated with ‘Axis Archive’ by Apache Software Foundation. Compressed file package for Apache Axis 2 which contains classes and data for a Web Service. The AAR is a JAR (Java Archive) file and is therefore based on the standard ZIP file format.

Now that we have that covered,
let’s start creating our native plugin.

 

1. Toolset

  • A computer
  • Android Studio Editor software
  • An Android device to test/compile on
  • Android coding knowledge, as I am not covering the language itself.

 

2. Android project setup

A. Open Android Studio and create a new Android Project.

Give your project a name and a namespace.

project_creation_01
Select the supported platforms for your application.

project_creation_02

Finally “Finish” the project setup.

Your project has now been created.
B. Create a new Android Module, of type “Android Library”

Go to “File” -> “New” -> “New Module…”
This will bring up the module creation window.

Select “Android Library”.

Android_module_01

 

Give your library a name, and a namespace…

Android_module_02

Now finish your library creation.

 

3. The Android part

Now that your project has been setup, let’s look at the android/java code of our native plugin.
In contrast of Objective-C, a Java class only has 1 file. So no header and body files.

We want our native plugin to print a string passed from Unity3D.

First thinks first,
Select your module src folder:  projectFolder -> moduleFolder – > src – >main -> java -> yourPlugin_folder
right click and select “New” -> Java Class.

For our example we will use our class “Bridge“.

package plugins.twnkls.com.mylibrary;

//import needed packages / classes.
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
import android.util.Log;
import android.os.Looper;

//extend android application.
public class Bridge extends Application
{
    // our native method, which will be called from Unity3D
    public void PrintString( final Context ctx, final String message )
    {
        //create / show an android toast, with message and short duration.
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ctx, message, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 

The above piece of code takes 2 parameters,
1. the current android context
2. the message that will be shown.

It’s very simple and pretty straight forward.
That’s it for our plugin code.

5. Compiling your Native Library

Now that we have our plugin code and module setup, let’s have a look at getting our native plugin compiled.
For this you have to make sure that the minimum support SDK is the same as you have specified inside Unity3D.
By default unity sets it’s minimum SDK version to 9.

unity_android_version

* You can find this setting in the Android Build Settings panel inside Unity3D

 

Thus you have to make sure that your Android project has that same version as it’s minimum SDK version.
To change the minimum SDK version for our Android Module, go to “File” – > “Project Structure”
Once there, select your Android Module and select the tab “Flavors”. You can change the minimum SDK version here.

AndroidStudio_android_version

 

To compile our Android Module press the “Make Project” button ( CTRL + F9 ) in your toolbar.
btn_make_project

Once the action is done, you are ready to use your native Android plugin.
Open your module folder in your OS explorer and go to the “outputs / aar ” folder.
Here you will find the release and debug versions of your native plugin.
For this example we will use the release version.

6. Implementing the native plugin inside Unity3D.

Open your Unity3D project and make sure you have the following folder structure :
Assets / Plugins / Android

Place your native android .AAR file inside this folder.

Now let’s write some code to call the plugin.

//basic imports.
using UnityEngine;
using System.Collections;

//standard unity behaviour.
public class AndroidCaller : MonoBehaviour {

       //method that calls our native plugin.
       public void CallNativePlugin()
       {
              // Retrieve the UnityPlayer class.
              AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

             // Retrieve the UnityPlayerActivity object ( a.k.a. the current context )
              AndroidJavaObject unityActivity = unityPlayerClass.GetStatic("currentActivity");

            // Retrieve the "Bridge" from our native plugin.
            // ! Notice we define the complete package name.
             AndroidJavaObject bridge = new AndroidJavaObject("plugins.twnkls.com.mylibrary.Bridge");

             // Setup the parameters we want to send to our native plugin.
             object[] parameters = new object[2];
             parameters[0] = unityActivity;
             parameters[1] = "This is an call to native android!";

              // Call PrintString in bridge, with our parameters.
              bridge.Call("PrintString", parameters);
       }
}

Add “CallNativePlugin” to a button click inside Unity3D, and you’re ready to test your native plugin!

To test your project, attach an Android device to your computer and run your project on your device. After clicking the button you should see an native Android Toast showing your passed text.
Here’s a screenshot of what your app should look like.

Screenshot_2016-06-16-11-41-56

You are now an Android plugin master! :)
Happy coding!

3 comments on “HowTo: native Android plugins for Unity3D

  1. techikon on said:

    I really love this post. Thanks for your sharing. Hope that I could read more and more useful article like this. Keeping moving forward

  2. Ibtehal on said:

    You are the best thank you very much

  3. Robin KollauRobin Kollau on said:

    Good to hear this post is helping you guys out! :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

What is 6 + 4 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)