• Twitter
  • Facebook
  • Google+
  • Instagram
  • Youtube

Employment

Education

Skills & Things about me

Android Native Plugin for Unity3D

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");

IOS Native plugin for Unity3D

IOS Native plugin for Unity3D

Author:- Tushar Sonu Lambole

1. In xcode project create new File as File-->New-->File..
Select Cocoa Touch in left panel, in right panel Select "Objective-C class"

2. Click Next Name file as "XploarIOSPlugin" You can Use any file name just remember to rename "XploarIOSPlugin" to your file name in below code.

3. Open "XploarIOSPlugin.h" file and paste the below code 


#import "UnityAppController.h"

@interface XploarIOSPlugin : UIViewController
{
    UINavigationController *navController;
}


struct ConfigStruct {
    char* tittle;
    char* message;
};

struct SocialSharingStruct {
    char* text;
    char* url;
    char* image;
    char* subject;
};


#ifdef __cplusplus
extern "C" {
#endif
    
    void showAlertMessage(struct ConfigStruct *confStruct);
    void showSocialSharing(struct SocialSharingStruct *confStruct);
    
#ifdef __cplusplus
}
#endif


@end

4. Open "XploarIOSPlugin.mm" file and paste the below code 

#import "XploarIOSPlugin.h"

@implementation XploarIOSPlugin{
}

//Grab the Unity3D ViewController (UnityGetGLViewController())

#ifdef UNITY_4_0

//Unity4

#import "iPhone_View.h"

#else

//Unity3.5

extern UIViewController* UnityGetGLViewController();

#endif

+(id) withTittle:(char*)tittle withMessage:(char*)message{

return [[XploarIOSPlugin alloc] withTittle:tittle withMessage:message];

}

-(id) withTittle:(char*)tittle withMessage:(char*)message{

self = [super init];

if( !self ) return self;

ShowAlertMessage([[NSString alloc] initWithUTF8String:tittle], [[NSString alloc] initWithUTF8String:message]);

return self;

}

void ShowAlertMessage (NSString *tittle, NSString *message){

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:tittle

message:message

delegate:nil

cancelButtonTitle:@"OK"

otherButtonTitles: nil];

[alert show];

}

+(id) withText:(char*)text withURL:(char*)url withImage:(char*)image withSubject:(char*)subject{

return [[XploarIOSPlugin alloc] withText:text withURL:url withImage:image withSubject:subject];

}

-(id) withText:(char*)text withURL:(char*)url withImage:(char*)image withSubject:(char*)subject{

self = [super init];

if( !self ) return self;



NSString *mText = [[NSString alloc] initWithUTF8String:text];

NSString *mUrl = [[NSString alloc] initWithUTF8String:url];

NSString *mImage = [[NSString alloc] initWithUTF8String:image];

NSString *mSubject = [[NSString alloc] initWithUTF8String:subject];


NSMutableArray *items = [NSMutableArray new];

if(mText != NULL && mText.length > 0){

[items addObject:mText];

}

if(mUrl != NULL && mUrl.length > 0){

NSURL *formattedURL = [NSURL URLWithString:mUrl];

[items addObject:formattedURL];

}
if(mImage != NULL && mImage.length > 0){

// For image from Web Url

if([mImage hasPrefix:@"http"])

{

NSURL *urlImage = [NSURL URLWithString:mImage];

// NSLog(@"Enter urlImage");

NSData *dataImage = [NSData dataWithContentsOfURL:urlImage];

// NSLog(@"Enter data %d",dataImage.length);

UIImage *imageFromUrl = [UIImage imageWithData:dataImage];

// NSLog(@"Enter data %f",imageFromUrl.size.height);

[items addObject:imageFromUrl];

}else{



// For image in local storage

NSFileManager *fileMgr = [NSFileManager defaultManager];



// Point to Document directory

NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];


NSString *imagePath = [[documentsDirectory stringByAppendingString:@"/"] stringByAppendingString:mImage];

// NSLog(@"Image Path %@",imagePath);

if([fileMgr fileExistsAtPath:imagePath]){

NSData *dataImage = [NSData dataWithContentsOfFile:imagePath];

// NSLog(@"Enter data %d",dataImage.length);

UIImage *imageFromUrl = [UIImage imageWithData:dataImage];

// NSLog(@"Enter data %f",imageFromUrl.size.height);

[items addObject:imageFromUrl];

}else{
ShowAlertMessage(@"Error", @"Cannot find image");
}
}
}

UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:Nil];

[activity setValue:mSubject forKey:@"subject"];

UIViewController *rootViewController = UnityGetGLViewController();
[rootViewController presentViewController:activity animated:YES completion:Nil];

return self;
}

# pragma mark - C API
XploarIOSPlugin* instance;

void showAlertMessage(struct ConfigStruct *confStruct) {
instance = [XploarIOSPlugin withTittle:confStruct->tittle withMessage:confStruct->message];
}

void showSocialSharing(struct SocialSharingStruct *confStruct) {
instance = [XploarIOSPlugin withText:confStruct->text withURL:confStruct->url withImage:confStruct->image withSubject:confStruct->subject];
}

@end

Here your IOS code part ends. Copy the both the files "XploarIOSPlugin.h" and "XploarIOSPlugin.m" and paste at the location /Assets/Plugins/iOS of your Unity3D project.

---- In Unity3d ----------

1. Create new c# script name it as "IOSBridge" and paste the below cod



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

public struct SocialSharingStruct
{
    public string text;
public string url;
public string image;
public string subject;
}

[DllImport ("__Internal")] private static extern void showSocialSharing(ref SocialSharingStruct conf);



#endif


public static void CallSocialShare(string title, string message)
{
#if UNITY_IPHONE
//IPHONE - Display the UIViewController
ConfigStruct conf = new ConfigStruct();
conf.tittle  = title;
conf.message = message;
showAlertMessage(ref conf);

#endif
}
public static void CallSocialShareAdvanced(string defaultTxt, string subject, string url, string img)

{
#if UNITY_IPHONE
//IPHONE - Display the UIViewController
SocialSharingStruct conf = new SocialSharingStruct();
conf.text = defaultTxt; 
conf.url = url;
conf.image = img;
conf.subject = subject;

showSocialSharing(ref conf);

#endif
}

2. Call above method CallSocialShare("This is Alert Tittle"," This is Message Text");

CallSocialShareAdvanced("AR Battle Tank"," AR Battle Tank Application link","https://play.google.com/store/apps/details?id=com.tushar.ARBattleTank","01.jpg");

"01.jpg" can be replace with any web url of image like 
"http://blog.gettyimages.com/wp-content/uploads/2013/01/Siberian-Tiger-Running-Through-Snow-Tom-Brakefield-Getty-Images-200353826-001.jpg"






Page 1 of 3123Next