While developing unity games in C# targeting android platform, we always want to use few native android features in our game. These features can be showing notifications on certain actions in the game or can be sharing the high score with other players and inviting them to try our game using android native share. Android gives us all the possibilities to achieve these native android functionalities in unity app using C#.

This post was originally posted at https://agrawalsuneet.github.io/blogs/native-android-in-unity/ and reposted on Medium on 22th Jun 2018.

Let’s take a very basic example of native android functionality ie showing a Toast using unity app.

For all those who are not familiar with what a toast is, toast is a simple message popup that appears at the bottom side (by default) of the screen with a custom message and for a long or short duration.
A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.

To show this toast in native android we need a simple call to the Toast class static method makeText which return us a Toast class object and then call show method on that object.

//Java Code
Context context = getApplicationContext();
CharSequence text = "This is a toast";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

makeText accepts three arguments,
1. Context: the reference of current activity or application
2. Text to show (CharSequence): text needs to be displayed
3. Duration (int): duration for which the toast needs to be displayed

The duration value can choose between Toast.LENGTH_LONG or Toast.LENGTH_SHORT.

Now in order to show the same code in unity app, we need use the same Toast class of android but how?

using AndroidJavaClass and AndroidJavaObject.

Please continue reading at https://agrawalsuneet.github.io/blogs/native-android-in-unity/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store