Open external Android app from within Android app

You can open any external Android application from within your Android application by pressing a button (or any other event). All you need to know is the namespace of the application you want to launch.

For this functionality use following code snippet:

public class MainActivity extends Activity {

private Button openAppButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

openAppButton = (Button) findViewById(R.id.openApp);
openAppButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

Intent i = new Intent();
PackageManager manager = getPackageManager();
i = manager.getLaunchIntentForPackage("launching.app.namespace");
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
}

});
}

}

In this code replace „launching.app.namespace“ with the namespace of the app you want to launch. If you don’t know the namespace of the app you can go to Google Play and search for the app. Inside the URL the namespace is mentioned as the „id“. For example, Google Maps has following URL:

 https://play.google.com/store/apps/details?id=com.google.android.apps.maps

As you can see, the value of id is „com.google.android.apps.maps“ – this is the app’s namespace.

 

Wrapping a MGWT Webapp with PhoneGap into a Native Android App

Here is an example how to make a simple MGWT Webapp and wrap it with PhoneGap into a native Android application. With MGWT to you can create fantastic mobile web applications with the look and feel of native mobile Android or iOS apps.

  • Install Eclipse IDE
  • Install GWT plugin into Eclipse
  • Download the MGWT jar file
  • Download the PhoneGap (Cordova) jar file
  • Create a new GWT project („HelloWorld“) with Eclipse (the official „Getting started“ documentation for GWT can be found here).
  • Add following jar files into the /libs folder of the newly created GWT project:
    mgwt.jar
    gwtphonegap.jar
  • Add these lines of code into the HelloWorld.gwt.xml file:
    <!-- Other module inherits -->
    <inherits name="com.googlecode.mgwt.MGWT"/>
    <inherits name='com.googlecode.gwtphonegap.PhoneGap' /><set-property name="user.agent" value="safari" />
    <set-configuration-property name="mgwt.css" value="pretty" />
    
  • Develop your GWT app as you wish using the MGWT library (the MGWT „Getting started“ documentation to be found here). Here is a simple and easy example:
    public class HelloWorld implements EntryPoint {public void onModuleLoad() {
    // set viewport and other settings for mobile
    MGWT.applySettings(MGWTSettings.getAppSetting());// build animation helper and attach it
    AnimationHelper animationHelper = new AnimationHelper();
    RootPanel.get().add(animationHelper);// build some UI
    LayoutPanel layoutPanel = new LayoutPanel();
    Button button = new Button("Hello World! Woohoo!");
    layoutPanel.add(button);// animate
    animationHelper.goTo(layoutPanel, Animation.SLIDE);}}
    
  • Create new native Android project with Eclipse. With this we are going to wrap the MGWT project into a native app.
  • Add the PhoneGap (or Cordova) jar file into the newly created Android project’s /libs folder.
  • Create subfolders /assets/www in that project. Make sure to add the PhoneGap.js (JavaScript) file into the /assets/www folder!
  • Create a simple index.html file in the /assets/www folder. Here a simple example of the html file:
    <head>
    <title>Cordova</title>
    <script type="text/javascript" charset="utf-8" src="cordova-2.3.0.js"></script>
    </head>
    <body>
    <h1>Hello World</h1>
    <h2>PhoneGap works!</h2>
    </body>
    </html>
    
  • Add following permissions to the Android project’s manifest file:
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />
    
  • Change the MainActivity class of the Android project that it looks like this:
    public class MainActivity extends DroidGap {@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);
    super.loadUrl("file:///android_asset/www/index.html");
    }@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
    }}
    
  • Build the Android project and see if the index.html file is being displayed after launching the app.
  • Compile (Google ->GWT Compile) the MGWT project. The compiled code can be found inside of the /war folder of the MGWT project.
  • Copy all the content of the /war folder of the MGWT project into the /assets/www folder in the Android project.
  • In the Android project in the MainActivity class change this line of code:
    super.loadUrl("file:///android_asset/www/index.html");
    

    to this

    super.loadUrl("file:///android_asset/www/HelloWorld.html");
    

    (or however the main html file of the MGWT project is named)

  • Run the Android project again. Now you should see the content of the MGWT app displayed acting like a native Android application. If that looks okay you can export the project to an APK file! Done!

Android SDK: Add a repeating AlarmManager to the autostart (displaying messages in the Notification Bar)

Add a repeating AlarmManager to the Android autostart (displaying messages in the Notification Bar)

This is a tutorial on how you can set an AlarmManager to continue doing its task even after the user has rebooted his phone. In this example the AlarmManager will repeatedly display a message in the notification bar of your Android phone after you rebooted it.

  • Create a new Android application in Eclipse called „OnBootCompletedAlarmManagerExample“. The namespace is on.boot.completed.
  • The content of the main Activity looks like this:

    OnBootCompletedExampleActivity.java

    import android.app.Activity;
    import android.app.NotificationManager;
    import android.content.Context;
    import android.os.Bundle;
    
    public class OnBootCompletedExampleActivity extends Activity {
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    }
    
    @Override
    protected void onResume() {
    super.onResume();
    
    // Clear the Notification Bar after you've clicked on the message in the Notification Bar
    NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nMgr.cancelAll();
    }
    }
    
  • Create a new class called Autostart.java which extends BroadcastReceiver:

    Autostart.java

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;
    
    public class Autostart extends BroadcastReceiver {
    
    /**
    * Listens for Android's BOOT_COMPLETED broadcast and then executes
    * the onReceive() method.
    */
    @Override
    public void onReceive(Context context, Intent arg1) {
    Log.d("Autostart", "BOOT_COMPLETED broadcast received. Executing starter service.");
    
    Intent intent = new Intent(context, StarterService.class);
    context.startService(intent);
    }
    }
    

    In the AndroidManifest.xml file we are going to add this class as a receiver. See the details for that further below. This class will listen to the broadcast call the Android OS sends after the boot sequence has finished (meaning after the phone started up).

  • Create another class called StarterService.java:

    StarterService.java

    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.os.IBinder;
    import android.util.Log;
    import android.widget.Toast;
    
    public class StarterService extends Service {
    private static final String TAG = "MyService";
    
    /**
    * The started service starts the AlarmManager.
    */
    @Override
    public void onStart(Intent intent, int startid) {
    Intent i = new Intent(this, NotificationBarAlarm.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
    
    // Repeat the notification every 15 seconds (15000)
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 15000, pi);
    
    Toast.makeText(this, "My Service started", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onStart");
    }
    
    @Override
    public IBinder onBind(Intent intent) {
    return null;
    }
    
    @Override
    public void onDestroy() {
    Toast.makeText(this, "My Service stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    }
    }
    

    When the class Autostart receives the BOOT_COMPLETED broadcast from Android OS it will start the StarterService which then starts the AlarmManager which holds the PendingIntent object „pi“ which contains the NotificationBarAlarm class. NotificationBarAlarm displays a message in the Notification Bar of the Android device.

  • Next create a class called NotificationBarAlarm.java. As mentioned above this class is sending a message to the phone’s Notification Bar. The AlarmManager we called in the above class will call NotificationBarAlarm in an interval of 15 seconds after the phone has been rebooted.

    NotificationBarAlarm.java

    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.net.Uri;
    import android.util.Log;
    
    public class NotificationBarAlarm extends BroadcastReceiver {
    
    NotificationManager notifyManager;
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    Log.d("NotificationAlarm", "onReceive");
    
    notifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    
    // This Activity will be started when the user clicks the notification
    // in the notification bar
    Intent notificationIntent = new Intent(context, OnBootCompletedExampleActivity.class);
    
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    Notification notif = new Notification(R.drawable.ic_stat_rooster_col, "A new notification just popped in!", System.currentTimeMillis());
    
    // Play sound?
    // If you want you can play a sound when the notification shows up.
    // Place the MP3 file into the /raw folder.
    notif.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.jingle);
    
    notif.setLatestEventInfo(context, "Notification Title", "Notification Text", contentIntent);
    
    notifyManager.notify(1, notif);
    }
    }
    
  • And finally we update the AndroidManifest.xml with the changes we need to do in order for the application to work how we want:

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="on.boot.completed"
        android:installLocation="internalOnly"
        android:versionCode="12"
        android:versionName="1.1.8" >
    
        <uses-sdk
            android:minSdkVersion="7"
            android:targetSdkVersion="9" />
    
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
        <application
            android:icon="@drawable/icon_w_bg"
            android:label="@string/app_name" >
            <activity
                android:name="on.boot.completed.OneFunFactADayActivity"
                android:label="@string/app_name"
                android:screenOrientation="portrait"
                android:theme="@android:style/Theme.NoTitleBar" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name="EditPreferences"
                android:screenOrientation="portrait"
                android:theme="@android:style/Theme.Black.NoTitleBar" >
            </activity>
    
            <receiver android:name=".background.NotificationBarAlarm" />
            <receiver
                android:name="on.boot.completed.AutoStart"
                android:enabled="true"
                android:exported="true" >
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                </intent-filter>
            </receiver>
    
            <service
                android:name=".background.StarterService"
                android:enabled="true"
                android:exported="true" />
        </application>
    
    </manifest>
    

    A few notes about AndroidManifest.xml:

    • It’s very important to add
      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

      before the <application> tag.

    • If the app is installed on the SD Card the autostart will not work! That’s why it’s important that we add
      android:installLocation="internalOnly"

      after package=“on.boot.completed“

    • Also add
      <action android:name="android.intent.action.QUICKBOOT_POWERON" />

      in addition to

      <action android:name="android.intent.action.BOOT_COMPLETED" />

      to the receiver. Some HTC devices won’t catch the BOOT_COMPLETED broadcast.

That’s all. Now build and run your app. After it has been started reboot your phone. The application’s notification service should start automatically after the device has booted up and display a message in the notification bar every 15 seconds.

Here you can download the working Android project:

Repeating AlarmManager after reboot example

Android SDK: Add application to the autostart

Add your Android application to the autostart

To add an Android application to the device’s autostart is actually pretty easy. But if some minor but important settings are wrong the autostart function doesn’t work. Here comes a fully functional example which opens your Android application after the device has finished its booting sequence.

  • Create a new Android application in Eclipse called „OnBootCompletedExample“. The namespace is on.boot.completed.
  • Leave the main Activity as is:

    OnBootCompletedExampleActivity.java

    import android.app.Activity;
    import android.os.Bundle;
    
    public class OnBootCompletedExampleActivity extends Activity {
    	/** Called when the activity is first created. */
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    	}
    }
    
  • Create a new class called Autostart.java which extends BroadcastReceiver:

    Autostart.java

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;
    
    public class Autostart extends BroadcastReceiver {
    
    	/**
    	 * Listens for Android's BOOT_COMPLETED broadcast and then executes
    	 * the onReceive() method.
    	 */
    	@Override
    	public void onReceive(Context context, Intent arg1) {
    		Log.i("Autostart", "BOOT_COMPLETED broadcast received. Executing following code:");
    
    		Intent intent = new Intent(context, StarterService.class);
    		context.startService(intent);
    	}
    }
    

    In the AndroidManifest.xml file we are going to add this class as a receiver. This class will listen to the broadcast call the Android OS sends after the boot sequence has finished (meaning after the phone started up).

  • Create another class called StarterService.java which will extend Service:

    StarterService.java

    import android.app.Service;
    import android.content.Intent;
    import android.os.IBinder;
    import android.util.Log;
    import android.widget.Toast;
    
    public class StarterService extends Service {
    	private static final String TAG = "MyService";
    
    	@Override
    	public IBinder onBind(Intent intent) {
    		return null;
    	}
    
    	@Override
    	public void onDestroy() {
    		Toast.makeText(this, "My Service stopped", Toast.LENGTH_LONG).show();
    		Log.d(TAG, "onDestroy");
    	}
    
    	/**
    	 * The started service opens the Activity.
    	 */
    	@Override
    	public void onStart(Intent intent, int startid) {
    		Intent intents = new Intent(getBaseContext(), OnBootCompletedExampleActivity.class);
    		intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    		startActivity(intents);
    
    		Toast.makeText(this, "My Service started", Toast.LENGTH_LONG).show();
    		Log.d(TAG, "onStart");
    	}
    }
    

    When the class Autostart receives the BOOT_COMPLETED broadcast from Android OS it will start the StarterService which then starts the Android Activity „OnBootCompletedExampleActivity“.

  • And finally we update the AndroidManifest.xml with the changes we need to do in order for the application to work how we want:

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="on.boot.completed"
        android:installLocation="internalOnly"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="7"
            android:targetSdkVersion="7" />
    
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:name="on.boot.completed.OnBootCompletedExampleActivity"
                android:label="@string/app_name"
                android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <receiver android:name="on.boot.completed.Autostart" >
                <intent-filter>
                    <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </receiver>
    
            <service
                android:name="on.boot.completed.StarterService"
                android:enabled="true"
                android:exported="true" />
        </application>
    
    </manifest>
    

    A few notes about AndroidManifest.xml:

    • It’s very important to add
      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

      before the <application> tag.

    • If the app is installed on the SD Card the autostart will not work! That’s why it’s important that we add
      android:installLocation="internalOnly"

      after package=“on.boot.completed“

    • Also add
      <action android:name="android.intent.action.QUICKBOOT_POWERON" />

      in addition to

      <action android:name="android.intent.action.BOOT_COMPLETED" />

      to the receiver. Some HTC devices won’t catch the BOOT_COMPLETED broadcast.

That’s all. Now build and run your app. After it has been started turn off your phone and turn it back on and the app should start automatically after the device has booted up.

Here you can download the working Android project:
OnBootCompletedExample

Unity 3D: Displaying a Fluct (Zucks AdNet) banner in a Unity Android game

Tutorial how to display an Fluct (Zucks AdNet) banner in an existing Unity Android project scene

Seems like using a simple Android JAR files inside a Unity Android project is not such a simple thing to do. I finally managed to get Zucks AdNet working in an existing Unity Android game. For this example I was using Unity for Windows version 3.5.2 and the latest Android plugin for Eclipse.

Prerequisites

I assume that you have a working installation of Eclipse with the Android plugin on your computer. If not, please follow this tutorial to get your workspace ready: Download the Android SDK.

The Eclipse/Android part

  • Register for an account at the Fluct website and download the ZucksAdnetSDK.jar file. In my example I am using version 1.1.3 of Fluct/ZucksAdnet.
  • Create a new Android project. Make sure that the namespace (the package name) is identical to the namespace of your Unity Android project. You can set the namespace in Unity through Build Settings > Player Settings > Android tab > Other Settings > „Bundle Identifier“. In my example I am using my.android.game.
  • Copy the ZucksAdnetSDK.jar file into the /libs folder of the project (you might have to create that folder manually).
  • Search inside of your Unity installation directory for the file classes.jar. Copy this file also into the /libs folder of your Eclipse project.
  • Create a class called ZucksUnityActivity.java. The class will look like this:

    package my.android.game;
    
    import net.zucks.zucksAdnet.sdk.ZucksAdnetUserInfo;
    import net.zucks.zucksAdnet.sdk.ZucksAdnetView;
    import android.os.Bundle;
    import android.view.Gravity;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.LinearLayout;
    
    import com.unity3d.player.UnityPlayer;
    import com.unity3d.player.UnityPlayerActivity;
    
    public class ZucksUnityActivity extends UnityPlayerActivity {
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    	}
    
    	public static void showBanner() {
    
    		UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    			public void run() {
    
    				ZucksAdnetUserInfo userInfo = ZucksAdnetUserInfo.getInstance(UnityPlayer.currentActivity.getApplicationContext());
    				userInfo.setGender(0); // 0 = male, 1 = female
    				userInfo.setAge(28);
    
    				// And this is the same, but done programmatically
    				LinearLayout layout = new LinearLayout(UnityPlayer.currentActivity.getApplicationContext());
    				layout.setOrientation(LinearLayout.VERTICAL);
    				
    				// DEFINE HERE IF THE BANNER SHALL BE DISPLAYED ON TOP OR ON BOTTOM OF THE SCREEN
    				layout.setGravity(Gravity.BOTTOM);
    				UnityPlayer.currentActivity.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    
    				ZucksAdnetView zucksView = new ZucksAdnetView(UnityPlayer.currentActivity);
    				layout.addView(zucksView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    			}
    
    		});
    
    	}
    
    }
    

    It’s important that you are using the ZucksAdnetUserInfo object. When I tried it without using this class the banner did not show up. The class extends UnityPlayerActivity instead of Activity. Also we created the static function showBanner() and left the onCreate() function nearly empty. Also we have to wrap the whole content of this function into

    UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    	public void run() {
    		...
    	}
    }
    

    otherwise we would get an error or a crash in Unity when we call the function. Also some content inside that function is a bit different in order to make it work with Unity.

  • Export the project to a JAR file. Click the right mouse button in the package explorer in Eclipse on your project and choose Export… > Java/JAR File > (standard settings) enter a name for the JAR file > Finish

Now you’re done with the part in Eclipse. Now we have to add that plugin into Unity.

The Unity part

  • Copy the created JAR file inside your Unity Android project into the folder /Plugins/Android/
  • Also copy the ZucksAdnetSDK.jar file into the same folder /Plugins/Android/
  • Complete the AndroidManifest.xml file inside your Unity Android project located at: \Assets\Plugins\Android\AndroidManifest.xml. The content of this file will look like this:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
    	android:installLocation="preferExternal"
        android:versionCode="1"
        android:versionName="1.0">
    	
        <supports-screens
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"/>
    
        <application
    		android:icon="@drawable/app_icon"
            android:label="@string/app_name"
            android:debuggable="true">
    		
    		<!-- FLUCT/ZUCKS SDK -->
    		<meta-data android:name="MEDIA_ID" android:value="000000999"  />
    						
            <activity android:name="com.unity3d.player.UnityPlayerProxyActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerNativeActivity"
                      android:label="@string/app_name"
                      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="true" />
            </activity>
            <activity android:name="com.unity3d.player.VideoPlayer"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>	
    
    		<activity android:name="my.android.game.ZucksUnityActivity"></activity>	
        </application>
    
    	<!-- PERMISSIONS -->
    	<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    	<uses-permission android:name="android.permission.GET_TASKS"></uses-permission>
    	<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    	
    </manifest>
    

    Replace the value of MEDIA_ID in the manifest file with the ID you received on the Fluct website when you registered. Also make sure the package name (namespace) is correct and identical to the namespace in your Eclipse project. Note that if you are already using other Android plugins this manifest file might be looking a bit different than in my example.

  • To finally display the ad banner inside a scene of your Unity Android game create or modify a C# script with the following content:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System;
    
    public class Startup : MonoBehaviour
    {
    	public static AndroidJavaClass ZucksAdnetSDKJavaClass;
    	
    	void Start() {
    		
    		if( Application.platform == RuntimePlatform.Android ) {
    			// Initialize Fluct/ZucksAdnetSDK
    			ZucksAdnetSDKJavaClass = new AndroidJavaClass("my.android.game.ZucksUnityActivity");
    			
    			// ZucksAdnetSDK display banner
    			ZucksAdnetSDKJavaClass.CallStatic("showBanner");
    		}
    		
    	}
    }
    

    The banner will now be displayed either at the top or bottom of your phone’s screen depending on what you defined in the source code in the Eclipse project. Note that this code will only be executed on an actual Android device and the banner will not show up in the Unity player! „showBanner“ has to be identical to the function name you were using inside your Eclipse project.

  • If the Unity Android game crashes when you are trying to display a Fluct banner check the error log. If the error has anything to do with a missing database table „tbl_user_info“ then open the ZucksAdnetSDK.jar file with WinZip or WinRAR and copy all the *.sql files from the /assets folder to the /Plugins/Android/assets folder in your Unity Android project and try again.

In the end the screen will look similar like in this screenshot on the right side.

Well that’s all! I hope the tutorial helped you getting Smaad working in your game! Please leave your comments and questions below.

Unity 3D: Integrating Smaad SDK „More Games“ Android Activity in a Unity Android game

Tutorial on how to integrate Smaad SDK in a Unity Android game

This is a tutorial on how to implement Smaad SDK in a Unity Android project. Smaad SDK is some sort of a Japan-only equivalent of Tapjoy and also displays a full screen Activity with a list of „other apps“ for the user to check out. I’m using Smaad SDK for this example because I had to implement this for a customer project.

Prerequisites

I assume that you have a working installation of Eclipse with the Android plugin on your computer. If not, please follow this tutorial to get your workspace ready: Download the Android SDK.

The Eclipse/Android part

  • Register for an account at the Smaad website and download the Smaad JAR file.
  • Create a new Android project. Make sure that the namespace (the package name) is identical to the namespace of your Unity Android project. You can set the namespace in Unity through Build Settings > Player Settings > Android tab > Other Settings > „Bundle Identifier“. In my example I am using my.android.game.
  • Copy the Smaad JAR file (the name of it might be MoreApps.jar) into the /libs folder of the project (you might have to create that folder manually).
  • Search inside of your Unity installation directory for the file classes.jar. Copy this file also into the /libs folder of your Eclipse project.
  • To test if the ads are being displayed we first create a regular Android class called SmaadActivity.java. The content of this class looks like this:

    package my.android.game;
    
    import jp.gmotech.MoreApps.MoreAppsActivity;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    
    public class SmaadActivity extends Activity {
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    
    		Intent i = new Intent(getApplication(), MoreAppsActivity.class);
    		i.putExtra("MoreAppsZoneId", "11111111"); // YOUR ZONEID HERE
    		startActivity(i);
    	}
    	
    }
    

    Make sure to change the value of „MoreAppsZoneId“ to your own ZoneId you received from the Smaad website.

  • Update the AndroidManifest.xml file that it looks like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk android:minSdkVersion="7" />
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            
            <activity
                android:name="my.android.game.SmaadActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name="jp.gmotech.MoreApps.MoreAppsActivity"
                android:configChanges="orientation"
                android:theme="@android:style/Theme.NoTitleBar" >
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.BROWSABLE" />
                </intent-filter>
            </activity>
    		
    		<service android:name="jp.gmotech.MoreApps.MoreAppsIntentService" />
        </application>
    
    </manifest>
    

    It’s important that you also add the activity „jp.gmotech.MoreApps.MoreAppsActivity“ to the manifest file since this is being used by Smaad.

  • Build and run the app on your Android phone and you should see the Smaad „more apps“ being displayed. If you don’t see this please refer to the official Smaad tutorials on how to implement this view into the Android app. Once this works continue with this tutorial.
  • Create a class called SmaadUnityActivity.java. You can use your previously created SmaadActivity.java class as a base. The class will look like this:

    package my.android.game;
    
    import jp.gmotech.MoreApps.MoreAppsActivity;
    import android.content.Intent;
    import android.os.Bundle;
    
    import com.unity3d.player.UnityPlayer;
    import com.unity3d.player.UnityPlayerActivity;
    
    public class SmaadUnityActivity extends UnityPlayerActivity {
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    	}
    
    	public static void showSmaadMoreGamesScreen() {
    		UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    			public void run() {
    				Intent intent = new Intent(UnityPlayer.currentActivity.getApplicationContext(), MoreAppsActivity.class);
    				intent.putExtra("MoreAppsZoneId", "11111111"); // YOUR ZONEID HERE
    				UnityPlayer.currentActivity.startActivity(intent);
    			}
    
    		});
    	}
    
    }
    

    Make sure to change the value of „MoreAppsZoneId“ to your own ZoneId you received from the Smaad website. This class extends UnityPlayerActivity instead of Activity in order to make it work inside Unity. Also we created the static function showSmaadMoreGamesScreen() and left the onCreate() function nearly empty. To make it work inside Unity we have to wrap the whole content of the function showSmaadMoreGamesScreen() into these lines of code:

    UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    	public void run() {
    		...
    	}
    }
    

    If we don’t do this we would get an error or even a crash in Unity when we call this function. Also some content inside that function is a bit different in order to make it work with Unity. Please have a careful look at the above code.

  • Not entirely sure if the following step is needed but just do it anyways: Add this line to the AndroidManifest.xml file inside the „application“ tags:
    <activity android:name="my.android.game.SmaadUnityActivity" android:screenOrientation="portrait" ></activity>
    
  • Export the project to a JAR file. Click the right mouse button in the package explorer in Eclipse on your project and choose Export… > Java/JAR File > (standard settings) enter a name for the JAR file > Finish

Now you’re done with the part in Eclipse. Next we have to add the created plugin into Unity.

The Unity part

  • Copy the created JAR file inside your Unity Android project into the folder /Plugins/Android/
  • Also copy the Smaad JAR (MoreApps.jar) file into the same folder /Plugins/Android/
  • Complete the AndroidManifest.xml file inside your Unity Android project located at: \Assets\Plugins\Android\AndroidManifest.xml. The content of this file will look like this:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
    	android:installLocation="preferExternal"
        android:versionCode="1"
        android:versionName="1.0">
        <supports-screens
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"/>
    
        <application
    		android:icon="@drawable/app_icon"
            android:label="@string/app_name"
            android:debuggable="true">
    
            <activity android:name="com.unity3d.player.UnityPlayerProxyActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerNativeActivity"
                      android:label="@string/app_name"
                      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="true" />
            </activity>
            <activity android:name="com.unity3d.player.VideoPlayer"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>	
    
            <activity android:name="my.android.game.SmaadUnityActivity"></activity>
    		
    		<activity android:name="jp.gmotech.MoreApps.MoreAppsActivity" android:configChanges="orientation" android:theme="@android:style/Theme.NoTitleBar" >
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.BROWSABLE" />
                </intent-filter>
            </activity>
    
            <service android:name="jp.gmotech.MoreApps.MoreAppsIntentService" />
        </application>
    
    	<!-- PERMISSIONS -->
    	<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    	<uses-permission android:name="android.permission.GET_TASKS"></uses-permission>
    	<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    	
    </manifest>
    
    

    Make sure the package name (namespace) is correct and identical to the namespace in your Eclipse project. Note that if you are already using other Android plugins this manifest file might be looking a bit different than in my example.

  • Finally we need to create a C# script in Unity to access that Android plugin:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System;
    
    public class Startup : MonoBehaviour
    {
    	public static AndroidJavaClass smaadJavaClass;
    	
    	void Start() {		
    		if( Application.platform == RuntimePlatform.Android ) {
    			// Initialize Smaad
    			smaadJavaClass = new AndroidJavaClass("my.android.game.SmaadUnityActivity");
    		}		
    	}
    	
    	void OnGUI () {
    		if( Application.platform == RuntimePlatform.Android ) {
    			if(GUI.Button(new Rect(10, 300, 150, 120), "Show SMAAD Screen")){
    				smaadJavaClass.CallStatic("showSmaadMoreGamesScreen");
    			}
    		}
    	}
    }
    

    Smaad SDK "More Games" activity

    For testing purposes we created a button inside the OnGUI() Unity function. If you press that button the Smaad Activity will be displayed. Note that this code will only be executed on an actual Android device and the button will not show up in the Unity player! „showSmaadMoreGamesScreen“ has to have the same name like the function you were using inside your Eclipse project.

In the end the screen will look similar like in this screenshot on the right side.

Well that’s all! I hope the tutorial helped you getting Smaad working in your game! Please leave your comments and questions below.

Unity 3D: Display an AdMob banner in an existing Unity Android game scene

Tutorial on how to display an AdMob banner in an existing Unity Android project scene

Seems like using a simple Android JAR files inside a Unity Android project is not such a simple thing to do. I finally managed to get AdMob working in an existing Unity Android game. For this example I was using Unity for Windows version 3.5.2 and the latest Android plugin for Eclipse.

Prerequisites

I assume that you have a working installation of Eclipse with the Android plugin on your computer. If not, please follow this tutorial to get your workspace ready: Download the Android SDK.

The Eclipse/Android part

  • Download the AdMob JAR file and register for an account if you haven’t done so already.
  • Create a new Android project. Make sure that the namespace (the package name) is identical to the namespace of your Unity Android project. You can set the namespace in Unity through Build Settings > Player Settings > Android tab > Other Settings > „Bundle Identifier“. In my example I am using my.android.game.
  • Copy the AdMob JAR file into the /libs folder of the project (you might have to create that folder manually).
  • Search inside of your Unity installation directory for the file classes.jar. Copy this file also into the /libs folder of your Eclipse project.
  • To test if the ads are being displayed we first create a regular Android class called AdMobActivity.java. The content of this class looks like this:

    package my.android.game;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.LinearLayout;
    
    import com.admob.android.ads.AdManager;
    import com.admob.android.ads.AdView;
    import com.admob.android.ads.SimpleAdListener;
    
    public class AdMobActivity extends Activity
    {
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		Log.i("AdMobTest", "onCreate");
    
    		// super (UnityPlayerActivity) will use setContentView() ...
    		super.onCreate(savedInstanceState);
    
    		// ... so instead of using setContentView(), we call addContentView()
    		// from setupAds()
    		setupAds();
    
    		// Add test devices (check the logcat for the ID string of your
    		// device..)
    		// If you want to display test-ads uncomment this line of code and replace YOUR_DEVICE_ID with your device ID which AdMob displays in your logfile.
    		AdManager.setTestDevices( new String[] { "YOUR_DEVICE_ID" } );
    	}
    
    	private void setupAds() {
    		// And this is the same, but done programmatically
    		LinearLayout layout = new LinearLayout(this);
    		layout.setOrientation(LinearLayout.VERTICAL);
    		layout.setGravity(Gravity.BOTTOM);
    		addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    
    		AdView adView = new AdView(this);
    		layout.addView(adView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    
    		adView.setBackgroundColor(0xff000000);
    		adView.setPrimaryTextColor(0xffffffff);
    		adView.setSecondaryTextColor(0xffcccccc);
    		adView.setKeywords("Android game");
    		adView.setRequestInterval(15);
    
    		// add listener for easier debugging
    		adView.setAdListener(new SimpleAdListener() {
    			@Override
    			public void onFailedToReceiveAd(com.admob.android.ads.AdView adView) {
    				Log.d("AdListener", "onFailedToReceiveAd: " + adView.toString());
    				super.onFailedToReceiveAd(adView);
    			}
    
    			@Override
    			public void onFailedToReceiveRefreshedAd(com.admob.android.ads.AdView adView) {
    				Log.d("AdListener", "onFailedToReceiveRefreshedAd: " + adView.toString());
    				super.onFailedToReceiveRefreshedAd(adView);
    			}
    
    			@Override
    			public void onReceiveAd(com.admob.android.ads.AdView adView) {
    				Log.d("AdListener", "onReceiveAd: " + adView.toString());
    				super.onReceiveAd(adView);
    			}
    
    			@Override
    			public void onReceiveRefreshedAd(com.admob.android.ads.AdView adView) {
    				Log.d("AdListener", "onReceiveRefreshedAd: " + adView.toString());
    				super.onReceiveRefreshedAd(adView);
    			}
    		});
    
    		adView.requestFreshAd();
    	}
    }
    
  • Update the AndroidManifest.xml file in your Eclipse project. It should look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk android:minSdkVersion="7" />
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:name="my.android.game.AdMobActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            
     		<!-- The application's publisher ID assigned by AdMob -->
            <meta-data android:value="YOUR_PUBLISHER_ID" android:name="ADMOB_PUBLISHER_ID" />
    
            <!-- AdMobActivity definition -->
            <activity android:name="com.admob.android.ads.AdMobActivity"
                      android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                      android:configChanges="orientation|keyboard|keyboardHidden" />        
    
        </application>
    
    </manifest>
    

    Make sure to replace YOUR_PUBLISHER_ID with your actual AdMob publisher ID.

  • Build and run the app on your Android phone and you should see the AdMob banner being displayed. If you don’t please refer to the AdMob tutorials how to implement the banner into the Android app. Once this works continue with this tutorial.
  • Create a class called AdMobUnityActivity.java. You can use your previously created AdMobActivity.java class as a base. The class will look like this:

    package my.android.game;
    
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.LinearLayout;
    
    import com.admob.android.ads.AdManager;
    import com.admob.android.ads.AdView;
    import com.admob.android.ads.SimpleAdListener;
    import com.unity3d.player.UnityPlayer;
    import com.unity3d.player.UnityPlayerActivity;
    
    public class AdMobUnityActivity extends UnityPlayerActivity {
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    	}
    
    	public static void setupAdsStatic() {
    		UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    			public void run() {
    
    				// If you want to display test-ads uncomment this line of code and replace YOUR_DEVICE_ID with your device ID which AdMob displays in your logfile.
    				// AdManager.setTestDevices(new String[] { "YOUR_DEVICE_ID" });
    
    				// And this is the same, but done programmatically
    				LinearLayout layout = new LinearLayout(UnityPlayer.currentActivity.getApplicationContext());
    				layout.setOrientation(LinearLayout.VERTICAL);
    				
    				// SET HERE IF YOU WANT THE BANNER TO BE DISPLAYED AT THE TOP OR BOTTOM OF THE SCREEN
    				layout.setGravity(Gravity.BOTTOM);
    				UnityPlayer.currentActivity.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    
    				AdView adView = new AdView(UnityPlayer.currentActivity);
    				layout.addView(adView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    
    				adView.setBackgroundColor(0xff000000);
    				adView.setPrimaryTextColor(0xffffffff);
    				adView.setSecondaryTextColor(0xffcccccc);
    				
    				// SET SOME KEYWORDS FOR THE ADS TO DISPLAY
    				adView.setKeywords("Android game");
    				adView.setRequestInterval(15);
    
    				// add listener for easier debugging
    				adView.setAdListener(new SimpleAdListener() {
    					@Override
    					public void onFailedToReceiveAd(com.admob.android.ads.AdView adView) {
    						Log.d("AdListener", "onFailedToReceiveAd: " + adView.toString());
    						super.onFailedToReceiveAd(adView);
    					}
    
    					@Override
    					public void onFailedToReceiveRefreshedAd(com.admob.android.ads.AdView adView) {
    						Log.d("AdListener", "onFailedToReceiveRefreshedAd: " + adView.toString());
    						super.onFailedToReceiveRefreshedAd(adView);
    					}
    
    					@Override
    					public void onReceiveAd(com.admob.android.ads.AdView adView) {
    						Log.d("AdListener", "onReceiveAd: " + adView.toString());
    						super.onReceiveAd(adView);
    					}
    
    					@Override
    					public void onReceiveRefreshedAd(com.admob.android.ads.AdView adView) {
    						Log.d("AdListener", "onReceiveRefreshedAd: " + adView.toString());
    						super.onReceiveRefreshedAd(adView);
    					}
    				});
    
    				adView.requestFreshAd();
    			}
    
    		});
    
    	}
    }
    

    The class now extends UnityPlayerActivity instead of Activity. Also we created the static function setupAdsStatic() and left the onCreate() function nearly empty. Also we have to wrap the whole content of this function into

    UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    	public void run() {
    		...
    	}
    }
    

    otherwise we would get an error or a crash in Unity when we call the function. Also some content inside that function is a bit different in order to make it work with Unity.

  • Not entirely sure if the following step is needed but just do it anyways: Add this line to the AndroidManifest.xml file inside the „application“ tags:
    <activity android:name="my.android.game.AdMobUnityActivity"></activity>	
    
  • Export the project to a JAR file. Click the right mouse button in the package explorer in Eclipse on your project and choose Export… > Java/JAR File > (standard settings) enter a name for the JAR file > Finish

Now you’re done with the part in Eclipse. Now we have to add that plugin into Unity 3D.

The Unity part

  • Copy the created JAR file inside your Unity Android project into the folder /Plugins/Android/
  • Also copy the AdMob JAR file into the same folder /Plugins/Android/
  • Complete the AndroidManifest.xml file inside your Unity Android project located at: \Assets\Plugins\Android\AndroidManifest.xml. The content of this file will look like this:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
    	android:installLocation="preferExternal"
        android:versionCode="1"
        android:versionName="1.0">
    	
        <supports-screens
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"/>
    
        <application
    		android:icon="@drawable/app_icon"
            android:label="@string/app_name"
            android:debuggable="true">
    						
            <activity android:name="com.unity3d.player.UnityPlayerProxyActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerNativeActivity"
                      android:label="@string/app_name"
                      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="true" />
            </activity>
            <activity android:name="com.unity3d.player.VideoPlayer"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>	
    
    		<activity android:name="my.android.game.AdMobUnityActivity"></activity>	
    		
    		<!-- The application's publisher ID assigned by AdMob -->
            <meta-data android:value="YOUR_PUBLISHER_ID" android:name="ADMOB_PUBLISHER_ID" />
    
            <!-- AdMobActivity definition -->
            <activity android:name="com.admob.android.ads.AdMobActivity"
                      android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                      android:configChanges="orientation|keyboard|keyboardHidden" />    
    
        </application>
    
    	<!-- PERMISSIONS -->
    	<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    	<uses-permission android:name="android.permission.GET_TASKS"></uses-permission>
    	<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    	
    </manifest>
    

    Make sure the package name (namespace) is correct and identical to the namespace in your Eclipse project. Also change the YOUR_PUBLISHER_ID value with the value of your actual AdMob publisher ID. Note that if you are already using other Android plugins this manifest file might be looking a bit different than in my example.

  • To finally display the ad banner inside a scene of your Unity Android game create or modify a C# script with the following content:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System;
    
    public class Startup : MonoBehaviour
    {
    	public static AndroidJavaClass adMobJavaClass;
    	
    	void Start() {
    		
    		if( Application.platform == RuntimePlatform.Android ) {
    			// Initialize AdMob
    			adMobJavaClass = new AndroidJavaClass("my.android.game.AdMobUnityActivity");
    			
    			// AdMob display banner
    			adMobJavaClass.CallStatic("setupAdsStatic");
    		}
    		
    	}
    }
    

    AdMob banner being displayed in Unity Android project

    The banner will now be displayed either at the top or bottom of your phone’s screen depending on what you defined in the source code in the Eclipse project. Note that this code will only be executed on an actual Android device and the banner will not show up in the Unity player! „setupAdsStatic“ has to be identical to the function name you were using inside your Eclipse project.

Well that’s all! I hope that helped you getting this nasty thing to work! Please leave your comments and questions below.

Saving & loading bitmaps to the Android device storage (internal & external)

In this tutorial I will show how to save a bitmap file to the external and internal storage of an Android device. It’s actually quite easy and only requires a few lines of code for the basic feature. As the source I am using a Bitmap object. If you want to use a image file from your drawable folder you can get it with this line of code:

Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);

If you want to save a thumbnail of an image you can easily change the size of the image with this line of code:

Bitmap thumbnail = Bitmap.createScaledBitmap(originalBitmap, width, height, false);

This will return a new Bitmap object with the desired width and height.

Saving the bitmap to the external storage

To save the Bitmap to the external storage (for example a SD card) use this code:

public final static String APP_PATH_SD_CARD = "/DesiredSubfolderName/";
public final static String APP_THUMBNAIL_PATH_SD_CARD = "thumbnails";

public boolean saveImageToExternalStorage(Bitmap image) {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD + APP_THUMBNAIL_PATH_SD_CARD;

try {
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}

OutputStream fOut = null;
File file = new File(fullPath, "desiredFilename.png");
file.createNewFile();
fOut = new FileOutputStream(file);

// 100 means no compression, the lower you go, the stronger the compression
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();

MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());

return true;

} catch (Exception e) {
Log.e("saveToExternalStorage()", e.getMessage());
return false;
}
}

Note that we have to pass the context to this variable. Otherwise we will not be able to use the getContentResolver() method. If you are using this method in an Activity class you can just delete „context“. Otherwise you can pass the context from an Activity class with „this“.

With the variable APP_PATH_SD_CARD you can set to which sub folder the file shall be saved. The root folder is the root folder of the SD card in the phone. You should name the sub folder with the name of your application so the user can easily find the proper folder of the saved files from your app.

Saving the bitmap to the internal storage

Alternatively you can also save the Bitmap to the internal storage in case the SD card is not available or for whatever other reasons you may have. Files saved to the internal storage are only accessible by the application which saved the files. Neither the user nor other applications can access those files. Also, all these files will be deleted once the application was uninstalled by the user.

public boolean saveImageToInternalStorage(Bitmap image) {

try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = context.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);

// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();

return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}

Note that we have to pass the context to this variable. Otherwise we will not be able to use the openFileOutput() method. If you are using this method in an Activity class you can just delete „context“. Otherwise you can pass the context from an Activity class with „this“.

You can change the value of Context.MODE_PRIVATE to Context.MODE_WORLD_READABLE so that other applications will be able to access those files.

 Reading a bitmap from the storage

With this method you can read a file from the storage. The method first checks for the file in the external storage. If the file is not there or there is no external storage it will look for the file in the internal storage.

First I made a method which checks if the external storage is readable.

public boolean isSdReadable() {

boolean mExternalStorageAvailable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = true;
Log.i("isSdReadable", "External storage card is readable.");
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
Log.i("isSdReadable", "External storage card is readable.");
mExternalStorageAvailable = true;
} else {
// Something else is wrong. It may be one of many other
// states, but all we need to know is we can neither read nor write
mExternalStorageAvailable = false;
}

return mExternalStorageAvailable;
}

We will be using the above method in this following method:

public Bitmap getThumbnail(String filename) {

String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD + APP_THUMBNAIL_PATH_SD_CARD;
Bitmap thumbnail = null;

// Look for the file on the external storage
try {
if (tools.isSdReadable() == true) {
thumbnail = BitmapFactory.decodeFile(fullPath + "/" + filename);
}
} catch (Exception e) {
Log.e("getThumbnail() on external storage", e.getMessage());
}

// If no file on external storage, look in internal storage
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
}
return thumbnail;
}

Note that we have to pass the context to this variable. Otherwise we will not be able to use the getFileStreamPath() method. If you are using this method in an Activity class you can just delete „context“. Otherwise you can pass the context from an Activity class with „this“.

So basically this method only needs the filename and returns a Bitmap object of this image for further use. If you want to use this Bitmap object for your ImageView in your activity you can set the bitmap to this object with this line of code:

myImageView.setImageBitmap(MyBitmapObject);

 

 

Unity 3D: Using Java classes/code

With Unity 3D you can use Java code. Here is a simple example how to use Java classes/code with Unity. Note that this tutorial only works with managed DLL files! If you want to use unmanaged DLL files you best have a look at the tutorial on the Unity 3D page here.

Create the Java class

First we create a Java class for testing:

package android.unity.plugin;

public class MyJava {

public MyJava() {
}

public String sayTokyo() {
return "Tokyo";
}

}

Export it to JAR

Export this class to a JAR file. You can do this with Eclipse in the package explorer by clicking the right mouse button on the class and choose Export -> JAR File. You do notneed to set any special options. Just define your desired dll file name and click export.

Convert it to DLL

Next go to IKVM.NET. Download and install this software. With IKVM you can convert JAR files into DLL files. This is what we need to do in order to be able to use the Java code with Unity.

Make sure to add the /bin path of IKVM to your System Environment Variable. It will look something like this:
C:\Users\de\Development\ikvm-7.0.4335.0\bin

Open a command prompt (CMD) and go to the directory where the previously exported JAR file is located. Then enter following command to convert the JAR file to a DLL file:

C:\Users\de>cd Desktop
C:\Users\de\Desktop>ikvmc -out:MyJava.dll MyJava.jar
C:\Users\de\Desktop>

When this command has been executed you have the MyJava.dll file which now can be used in Unity (this DLL file is a so called „managed dll“ file).

The Unity 3D stuff

Open Unity and import the MyJava.dll to your Assets folder. I copied mine to the Plugins sub folder but as far as I know this is not necessary.

I am not sure if this step is necessary but I did it anyways: Copy all the .dll files from the IKVM folder to the Assets/Plugins folder in Unity.

Create a .cs script – MyManagedJavaPlugin.cs – with Unity with the following content:

using UnityEngine;
using android.unity.plugin;

public class MyManagedJavaPlugin : MonoBehaviour {

void Awake() {
MyJava obj = new MyJava();
print(obj.sayTokyo());
}

}

android.unity.plugin has to be the namespace you used when you created the Java project with Eclipse.

Next you can attach the MyManagedJavaPlugin.cs script to an object in your Unity scene. Hit the play button in Unity and you will see that when the „Awake“ action is happening in Unity the sayTokyo() method will be called. The string „Tokyo“ will then be output in your Unity console.

That’s it for this tutorial. From now on you can modify your script and classes to fit your needs.

Unity 3D: Debugging with the Unity logfile when testing an APK file on an actual device

Normally, if you test your Unity game on your Android phone you are able to see the Unity debug logfile in the Android logcat with Eclipse.

Debug.Log("info");
Debug.LogWarning("warning");
Debug.LogError("error");

However, in case this is not working you can output the game’s logfile to a flat file. Do as follows:

  • Connect to the device using ADB.
  • Use the logcat command:
    adb logcat -d > mylogfile.txt

That will create a text file (mylogfile.txt) which should include any statements you logged (like „information“ from Debug.Log).