• Twitter
  • Facebook
  • Google+
  • Instagram
  • Youtube

Android Native Plugin for Unity3D

Author:- Tushar Sonu Lambole


1. Before start this steps will require UnityPlayer classes.Jar



in Mac will find at location "/Applications/Unity/Unity.app/Contents/PlaybackEngines/
AndroidPlayer/bin"

2. Right-click on the project in Eclipse, go to Properties > Java Build Path > Libraries



3. Create new classActivity paste the following code 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class RootActivity extends UnityPlayerActivity {
 static UnityPlayerActivity instance;

 public static UnityPlayerActivity getInstance() {
  return instance;
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {

  instance = this;
  super.onCreate(savedInstanceState);
 }

 public void showMessage(final String message) {
  this.runOnUiThread(new Runnable() {

   @Override
   public void run() {
    Toast.makeText(RootActivity.this, message, Toast.LENGTH_LONG)
      .show();
   }
  });
 }

 public void SocialMessageAdvanced(String message, String subject,
   String url, String img) {
  
  //showMessage(img);

  Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);

  if (url != null && url.length() > 0) {
   if (message == null) {
    message = url;
   } else {
    message = message + " " + url;
   }
  }

  try {
   doSendIntent(message, subject, img);
  } catch (IOException e) {
   e.printStackTrace();
  }

  UnityPlayer.currentActivity.startActivity(sendIntent);
 }

 private void doSendIntent(String text, String subject, String image)
   throws IOException {
  final Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
  if (text != null && text.length() > 0) {
   sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, text);
  }
  if (subject != null && subject.length() > 0) {
   sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
  }
  if (image != null && image.length() > 0) {
   sendIntent.setType("image/*");
   sendIntent.putExtra(Intent.EXTRA_STREAM,
     Uri.fromFile(new File(image)));
   UnityPlayer.currentActivity.startActivity(sendIntent);

  } else {
   sendIntent.setType("text/plain");
   UnityPlayer.currentActivity.startActivity(sendIntent);
  }
 }

 public void SocialMessage(String message) {
  Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
  sendIntent.setType("text/plain");
  sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
  UnityPlayer.currentActivity.startActivity(sendIntent);
 }
}

4. Right click on project and export as JAR file.

5. Open Unity3D application and paste the JAR from step 4 at location Assets/Plugins/Andoid

6. Open AndroidManifest.xml of unity3D file and make the changes as follows.
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.qualcomm.QCARUnityPlayer"
    android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <uses-feature android:name="android.hardware.camera" />
    <supports-screens
        android:smallScreens="true"
        android:normalScreens="true"
        android:largeScreens="true"
        android:anyDensity="true" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />
        
    <application
  android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        android:debuggable="false">
        <activity android:name="com.qualcomm.QCARUnityPlayer.QCARPlayerProxyActivity"
                  android:label="@string/app_name"
                  android:screenOrientation="portrait"
                  android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|
orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
           
        </activity>
        <activity android:name="com.qualcomm.QCARUnityPlayer.QCARPlayerActivity"
                  android:label="@string/app_name"
                  android:screenOrientation="portrait"
                  android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|
orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
        </activity>
        <activity android:name="com.qualcomm.QCARUnityPlayer.QCARPlayerNativeActivity"
                  android:label="@string/app_name"
                  android:screenOrientation="portrait"
                  android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|
orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            <meta-data android:name="android.app.lib_name" android:value="unity" />
            <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="false" />
        </activity>
        <activity android:name="com.unity3d.player.VideoPlayer"
                  android:label="@string/app_name"
                  android:screenOrientation="portrait"
                  android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|
orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
        </activity>
  <activity
            android:name="com.tushar.androidunityplugin. RootActivity"
            android:label="@string/app_name" >
    
   <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
   
  </activity>
    </application>
</manifest>




7. Create new c# script in Unity3D as "AndroidMapInterface"

using UnityEngine;
using System.Collections;

public class AndroidMapInterface : MonoBehaviour {

 // Use this for initialization
 void Start () {

  //Initialize AndroidBridge
  AndroidBridge.Initialize();
  
  //Register Action
  AndroidBridge.OnXploarShowEvent += onXploarShowEvent;
  
 }

 public void CallSocialShare(string text)
 {
  AndroidBridge.CallSocialShare(text);
 }

 public void CallSocialShareAdvanced(string text, string subject, string url, string img)
 {
  AndroidBridge.CallSocialShareAdvanced(text, subject,url,img);
 }
 void onXploarShowEvent(string eventStr){
  Debug.Log("AndroidXploarInterface - onXploarShowEvent:"+eventStr);
  
 }

 void OnDestroy() {
  AndroidBridge.OnXploarShowEvent -= onXploarShowEvent;
 }
}




8. Create new C# script paste code

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System;

public class AndroidBridge : MonoBehaviour {

 public static event Action<string> OnXploarShowEvent;

 #if UNITY_IPHONE
  public struct ConfigStruct
  {
      public string tittle;
   public string message;
  }
  [DllImport ("__Internal")] private static extern void showAlertMessage(ref ConfigStruct conf);
  
 #endif

 // Init the class instance
 static AndroidBridge instance;
 public static void Initialize()
 {
  Debug.Log("Application Init");
  if (instance == null)
  {
   GameObject newGameObject = new GameObject("XploarBridge");
   newGameObject.AddComponent<AndroidBridge>();
   instance = newGameObject.GetComponent<AndroidBridge>();
  }
 }

 //Callback from Java or Objective-C which notifies an event
 //param : "EVENT_OPENED", "EVENT_CLOSED"
 //Method name starts small "o" and Event name is capital "O"
 void onXploarShowEvent(string eventStr){
  //Debug.Log("EasyCodeScanner - onScannerEvent eventStr=:"+eventStr);
  if (OnXploarShowEvent != null)
        {
            OnXploarShowEvent(eventStr);
        }
 }

 public static void CallSocialShare(string defaultTxt)
 {
  if (instance==null) 
  {
   Debug.Log("instance is null");
   Debug.LogError("AndroiddBridge - launchSilverpointMap error : ScriptObject  must be initialized before.");
   return;
  }
  
  
  #if UNITY_ANDROID 
    AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); 
   
    AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"); 
     
    //Invoke the "SocialMessage" method in our Android Plugin Activity
    jo.Call("SocialMessage", defaultTxt);
  #endif
  
  #if UNITY_IPHONE 
   //IPHONE - Display the UIViewController
   ConfigStruct conf = new ConfigStruct();
   conf.tittle  = "Alert Message Tittle";
   conf.message = "First Attempt to call IOS plugin";
   showAlertMessage(ref conf);
  #endif
  
 }

 public static void CallSocialShareAdvanced(string defaultTxt, string subject, string url, string img)
 {
  if (instance==null) 
  {
   Debug.Log("instance is null");
   Debug.LogError("AndroiddBridge - error : ScriptObject  must be initialized before.");
   return;
  }
  
  
  #if UNITY_ANDROID 
    AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); 
   
    AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"); 
     
    //Invoke the "SocialMessage" method in our Android Plugin Activity
    jo.Call("SocialMessageAdvanced", defaultTxt, subject, url, img);
  #endif
 }
}

9. Attach "AndroidMapInterface" script to the any gameobject

10. Call the methods as follows

AndroidMapInterface androidInterface = objectHavingScript.GetComponent<AndroidMapInterface>();
androidInterface.CallSocialShareAdvanced("Text",
"Subject","https://play.google.com/store/apps/details?id=com.tushar.ARBattleTank",

Application.persistentDataPath+"/Pic.jpg");

Contact

Get in touch with me


Adress/Street

B/1, Keshar Gaurav BLD, Gujarathi Baug, Shahapur

Phone number

+(91) 9423026579

Website

http://tusharlambole.blogspot.com/