Saturday, October 5, 2013

Admob Android Plugin for Unity3d

Standard
Hello All:

Sometimes it is good to earn some money even by publishing free games and applications. This is where advertisements come handy. In this post I will explain how to create a unity3d plug-in to show ads using Google's Admob.

If you are new to plugins for Unit3d, please read these two posts Android Plug-in #1 and Android Plug-in #2.In order to use Admob advertisement SDK in your application or game you will need Admob publisher's id. You can register for Admob account on Admob . Once you have registered for Admob account, you can download the sdk here

As mentioned in earlier post on Android plugin, this plugin will also have two parts
  1. Java code to interact with Admob SDK in .jar
  2. C# wrapper to show the ads

Step #1:
  1. Create an android application project using eclipse.
  2. Add Admob sdk to libs folder.
  3. Create a class AdmobViewManager and paste the below code in it
     
                    package com.ashwanik.admobunityplugin;
    
    import android.app.Activity;
    import android.view.Gravity;
    import android.view.View;
    import android.widget.RelativeLayout;
    import android.widget.RelativeLayout.LayoutParams;
    
    import com.google.ads.AdRequest;
    import com.google.ads.AdSize;
    import com.google.ads.AdView;
    
    public class AdmobViewManager {
     static final int adViewId = 0x7f080001;
    
     static public void showAds(final Activity activity, final String publisher,
       final String testDevice) {
      activity.runOnUiThread(new Runnable() {
       @SuppressWarnings("deprecation")
       public void run() {
        AdView adBanner = (AdView) activity.findViewById(adViewId);
        if (adBanner == null) {
         RelativeLayout layout = new RelativeLayout(activity);
         activity.addContentView(layout, new LayoutParams(
           LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
         layout.setGravity(Gravity.BOTTOM
           | Gravity.CENTER_HORIZONTAL);
         adBanner = new AdView(activity, AdSize.SMART_BANNER, publisher);
         adBanner.setId(adViewId);
         layout.addView(adBanner);
        }
        AdRequest adRequest = new AdRequest();
        if (testDevice != null)
         adRequest.addTestDevice(testDevice);
        adBanner.loadAd(adRequest);
       }
      });
     }
    
     public static void hideOrShowBanner(final Activity activity,
       final boolean isShow) {
    
      activity.runOnUiThread(new Runnable() {
       @Override
       public void run() {
        AdView adBanner = (AdView) activity.findViewById(adViewId);
        if (adBanner != null) {
    
         adBanner.setVisibility(isShow ? View.VISIBLE : View.GONE);
        }
    
       }
      });
    
     }
    }
                    
  4. Export the jar as mentioned in earlier posts. No need to include libs folder in the jar.
Step #2:
  1. Create a unity project 
  2. Add a C# script AdmobViewManager and paste following code in it
     
             using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System;
    using System.Linq;
    
    public class AdmobViewManager : MonoBehaviour
    {
        public static AdmobViewManager Instance;
        public string admobPublisherId = "Your admob publisher id";
        public string testDeviceId = "test device id";
        public float refreshTime = 30.0f;
       
        void Awake()
        {
            Instance = this;
        }
    
        public void HideOrShowAds(bool isShow)
        {
    #if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_WEBPLAYER
            AndroidJavaClass plugin = new AndroidJavaClass("com.ashwanik.admobunityplugin.AdmobViewManager");
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject activity = unityPlayer.GetStatic
    <androidjavaobject>("currentActivity");
            plugin.CallStatic("hideOrShowBanner", activity, isShow);
    #endif
        }
    
      
    
        IEnumerator Start()
        {
    #if UNITY_ANDROID &amp;&amp; !UNITY_EDITOR &amp;&amp; !UNITY_WEBPLAYER
            AndroidJavaClass plugin = new AndroidJavaClass("com.ashwanik.admobunityplugin.AdmobViewManager");
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject activity = unityPlayer.GetStatic<androidjavaobject>("currentActivity");
            while (true) {
                plugin.CallStatic("showAds", activity, admobPublisherId, testDeviceId);
                yield return new WaitForSeconds(refreshTime);
            }
    #else
            return null;
    #endif
        }
    }
    
                                  
    
  3. Create one more script GuiTest and paste below code in it
     
                        using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System;
    using System.Linq;
    public class GuiTest : MonoBehaviour
    {
        bool isAdsShown = true;
        #region Variables
    
        #endregion
    
        #region Methods
    
        void OnGUI()
        {
            string text = isAdsShown ? "Hide Ads" : "Show Ads";
            if (GUI.Button(new Rect(100, 100, 300, 300), text))
            {
                AdmobViewManager.Instance.HideOrShowAds(!isAdsShown);
                isAdsShown = !isAdsShown;
            }
        }
    
        #endregion
    }
    
                        
  4. Attach these two scripts to Main Camera and save the scene.
  5. Select Main Camera and give your publisher's id
  6. Add .jar which is generated in Step #1 to /Assets/Plugins/Android folder.
  7. Add Google Admob Sdk in /Assets/Plugins/Android/libs (create libs folder)
  8. Add androidmanifest.xml file to /Assets/Plugins/Android and replace the code with following code
                  
    
      
      
      
      
        
          
            
            
          
        
        
        
        
          
          
        
        
        
        
        
      
      
      
    
                  
  9. Save the scene and attach device to PC and build the application in Unity3d. You should see Ads in your mobile.
  10. To get test device id, open logcat in eclipse and search for text: test
You can download sample project here.
Hope this helps. Happy coding!!!
Thanks

Thanks for printing this post. Hope you liked it.
Keep visiting and sharing.
Thanks,
Ashwani.

0 comments :

Post a Comment