Skip to content Skip to main navigation Skip to footer

How to use Branded Mini Games in Android App

No part of this publication may be reproduced, transmitted, transcribed, stored in a retrieval system, or translated into any language, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission from Emoji Games.

All copyrights, confidential information, patents, design rights and all other intellectual property rights whatsoever in nature contained herein are and shall remain the sole and exclusive property of Emoji Games Solutions GmbH. The information furnished herein is believed to be accurate and reliable.

However, no responsibility is assumed by Emoji Games for its use, nor for any infringements of patents or other rights of third parties resulting from its use.

The Branded Mini-Games logo is a registered trademark of Emoji Games Solutions GmbH.

1. Introduction

1.1. Purpose

The purpose of this document is to guide developers who want to integrate a Game provided by Emoji Games into your Android game/app.

1.2. Preparation

  • Development tools on PC: Eclipse, Android SDK.
  • Operating system on mobile device : Android 2.3 or higher.
  • The event_info.dat file created by BMG Event Creator tool (provided by Emoji Games).

event_info.dat file must be uploaded onto the server and you have to get the direct URL of that file.

1.3. Overview

2. Configuration

2.1 Get event_info.dat file

To obtain the event_info.dat file, please contact the Emoji Games tech team at support@brandedminigames.com.

2.2 Upload event_info.dat file to server

After getting the event_info.dat file, you should upload it to your server and get the direct URL of it.

E.g: http://brandedminigames.com/BMGSDK_Demo/event_info.dat

2.3 Update your AndroidManifest.xml file

2.3.1. Add uses-permission

We need access authority to check information about the internet connection and network status. Please add these permissions into the file.

Please insert this code in the “AndroidManifest.xml” of your project:

<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE”/>
2.3.2. Update activity intent-filter

In the main activity of your application, please add a new intent-filter as shown below:

<activity
    …
    android:launchMode=”singleTask”>
    …
    <intent-filter>
        <action android:name=”com.mbizglobal.bmg.PLAY” />
        <category android:name=”android.intent.category.DEFAULT” />
        <category android:name=”android.intent.category.BROWSABLE” />
        <data android:scheme=”The Package Name of your application”/>
</intent-filter>
</activity>

Do not forget the “singleTask” launchMode property, it will deliver the result to the correct activity.

Please set the scheme as the Package Name of your application.

The scheme must be the same as the one you registered on the campaign page in Studio site:

2.3.3. Hardware accelerated

Webview may offer poor performance when playing branded mini game titles. To resolve this problem you must add one more config to your App manifest:

<uses-feature android:glEsVersion=”0x00020000″ />
<application …
            android:hardwareAccelerated=”true” />

3. Implementation

3.1 Download and Decode event_info.dat file from your server

3.1.1. Download Event data file

First, you must have the URL of dat file that contains the branded mini game event.

E.g: http://brandedminigames.com/BMGSDK_Demo/event_info.dat

If you would like to use game demo events for testing, please set the URL to the one above. This is the event information data file for game demo events. Or you can download this event_info.dat file and then upload it on your server. The URL will be your server URL.

In your main Activity, use this code in onCreate(Bundle savedInstanceState) method to download and save dat file data to byte array. You can use Handler or AsyncTask to increase performance:

URL url = new
            URL(“http://brandedminigames.com/BMGSDK_Demo/event_info.dat”);
InputStream in = url.openStream();
byte[] inputBytes = IOUtils.toByteArray(in);
3.1.2. Decode data

When we receive byte array from data file in server, we can not use it because this byte array has been encoded.

  • The algorithm is “AES-128”
  • Key is “brandedminigames”

Use this code to decode the data:

String ALGORITHM = “AES”;
String TRANSFORMATION = “AES”;
String KEY = “brandedminigames”;
Key secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(cipherMode, secretKey);
byte[] outputBytes = cipher.doFinal(inputBytes);
String outputString = new String(outputBytes, “UTF-8”);

Now we have outputString, it is the pure JSON string, so we will parse this string to JSONArray, JSONObject.

try {
    JSONArray jsonArr = new JSONArray(outputString);
    for (int i = 0; i < jsonArr.length(); i++) {
     JSONObject jobj = jsonArr.getJSONObject(i);
      
     // Checking event period
     String start = jobj.optString(“start”);
     String end = jobj.optString(“end”);        
     Date startDay = sdf.parse(start);          
     Date endDay = sdf.parse(end);
      
     // End of day
     Calendar c = Calendar.getInstance();
     c.setTime(endDay);
     c.set(Calendar.HOUR_OF_DAY, 23);
     c.set(Calendar.MINUTE, 59);
     c.set(Calendar.SECOND, 59);        
     endDay = c.getTime();
   
     if (endDay.compareTo(startDay) < 0) {
         continue;
     }
     Date today = new Date();
     if (today.compareTo(startDay) < 0) {
         continue;
     }
     if (today.compareTo(endDay) > 0) {
         continue;
     }
     // Checking event status
     if (jobj.optInt(“status”) != 1)
         continue;
     int mScore = 0;
     try {
         mScore = Integer.parseInt(jobj.optString(“maxScore”));
     } catch (Exception e) {
     }  
       /*
       * Now, save all fields above to your data struct (such as ArrayList)
 /*
       *jobj.optString(“campaignId”),
     *jobj.optString(“start”),
     *jobj.optString(“end”),
     *jobj.optInt(“status”),
     *jobj.optString(“url”),
     *jobj.optString(“title”),
     *jobj.optString(“desc”),
     *jobj.optInt(“maxScore”)
 
 
       */
    }
} catch (ParseException e) {
    //Exception is thrown when event_info.dat error
    //You handle exception by yourself
} catch (Exception e) {
    //You handle exception by yourself
}

Because you can create many events using BMG Event Data Tool, the event information that you decoded from binary data to JSON data is an array list. You can select the specific event in the array list and use it. Specifically, it is a JSON Array that contains one or many JSON Objects. If there are many events, you could use ArrayList to save them.

JSON Object information:

Field nameDescription
startEvent start time. Format ‘MM/dd/yyyy’
endEvent end time. Format ‘MM/dd/yyyy’
statusEvent status.0: Disable1: Enable
urlEvent game url
titleEvent title
descEvent description
maxScoreMaximum possible score from this event game
campaignIdID of current campaign

3.2 Save event info in memory

You have received event data. It is a good idea to save these events to your memory for further usage. I recommend using a Java global list. By doing it this way, you do not need to get event information from the server again.

3.3 Build URL from original URL in memory

After retrieving and decoding data from event_info.dat file is complete, in order to play the branded mini game you must build a URL based on the URL received in the previous step:

(String url = jobj.optString(“url”)).

The new url looks like:

String query = “?”;
if (url.contains(“?”))
   query = “&”;
uri = Uri.parse(url +
            query +
            “app_user=” + userId +
            “&route=” +
                   mainContext.getApplicationContext().getPackageName());

“app_user”: is string format. This should be an email address or ID of the user that will be taken from your application after the user has logged in. This information will be used to identify each user that has joined the Event mini game, and through this parameter the winner can be detected at the end of the Event. If the user is not logged in or has no account, you should generate a random value. This parameter is mandatory. E.g random value:

String userId = “Guest_” + UUID.randomUUID().toString().substring(0, 8);

3.4 Play the game

3.4.1. Play game with external browser

You can call browser to play branded mini game with the URI above, using this code:

Intent browserIntent = new Intent(Intent.ACTION_VIEW);
PackageManager packageManager = mainContext.getPackageManager();
browserIntent.setDataAndType(uri, “text/html”);
List<ResolveInfo> list =
                 packageManager.queryIntentActivities(browserIntent, 0);
 
 
//Call native android browser
for (ResolveInfo resolveInfo : list) {
    String activityName = resolveInfo.activityInfo.name;
     
    if (activityName.toLowerCase().contains(“com.android.browser”) ||
         activityName.toLowerCase().contains(“com.google.android.browser”) ||
         activityName.toLowerCase().contains(“com.sec.android.app.sbrowser”) ||
         activityName.toLowerCase().contains(“com.htc.sense.browser”)) {
        browserIntent =
                packageManager.getLaunchIntentForPackage(resolveInfo.activityInfo.packageName);
        ComponentName comp =
                new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
        browserIntent.setAction(Intent.ACTION_VIEW);
        browserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
        browserIntent.setComponent(comp);
        browserIntent.setData(uri);
        mainContext.startActivity(browserIntent);               
        return;
    }
}
 
 
//or call external browser (Chrome)
for (ResolveInfo resolveInfo : list) {
    String activityName = resolveInfo.activityInfo.name;
    if (activityName.toLowerCase().contains(“com.google.android.apps.chrome”)) {
        browserIntent =
                packageManager.getLaunchIntentForPackage(resolveInfo.activityInfo.packageName);
        ComponentName comp =
                new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
        browserIntent.setAction(Intent.ACTION_VIEW);
        browserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
        browserIntent.setComponent(comp);
        browserIntent.setData(uri);
        mainContext.startActivity(browserIntent);               
        return;
    }
}

After finishing the game, you will be directed to the leaderboard. At that page, you can click the Complete button to return to your app because this href of the Complete button is the android schema.

3.4.2. Play game with WebView

If you do not want to use an external browser, you can define your own Activity that contains only WebView to play your branded mini game.

Of course, you still have to build the URL to play, similar to section 3.3 Build URL from original URL in memory.

You can implement BMGWebView Activity like this in code:

public class BMGWebView extends Activity {
    private WebView webView;
    @SuppressLint(“SetJavaScriptEnabled”) @Override
    protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     requestWindowFeature(Window.FEATURE_NO_TITLE);
     String url = getIntent().getStringExtra(“url”);
     if (url == null || url.equals(“”))
         finish();
     LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
     webView = new WebView(this);
     WebSettings s = webView.getSettings();
     s.setJavaScriptEnabled(true);
     s.setSupportMultipleWindows(false);
     s.setJavaScriptCanOpenWindowsAutomatically(false);
     s.setDomStorageEnabled(true);
     s.setDatabaseEnabled(true);
     s.setLightTouchEnabled(true);
     s.setLoadWithOverviewMode(false);
     s.setUseWideViewPort(true);
     s.setPluginState(WebSettings.PluginState.ON);
     s.setBuiltInZoomControls(false);
     s.setSupportZoom(false);
     s.setAllowFileAccess(true);
     s.setAppCachePath(this.getCacheDir().getAbsolutePath());
     s.setCacheMode(WebSettings.LOAD_DEFAULT);
     addContentView(webView, params);
     webView.setWebChromeClient(new WebChromeClient(){  
     });
      
     webView.setWebViewClient(new WebViewClient(){
         @Override
         public boolean shouldOverrideUrlLoading(WebView view,
                                                     String url) {
             if (url.startsWith(“intent:#Intent;”)){
                 url = url.replace(“intent:#Intent;”, “”);
                 String[] tokens = url.split(“;”);
                HashMap<String, String> map = new HashMap<String,
                                                               String>();
                for(int i=0;i<tokens.length;i++)
                {
                    String[] strings = tokens[i].split(“=”);
                    if(strings.length==2)
                    map.put(strings[0],
                              strings[1].replaceAll(“%2C”, “,”));
                }
                //get data
                String action = map.get(“action”);
                int scoreInt = 0;
                int rankInt = 0;
                try {
                     scoreInt =
                                  Integer.parseInt(map.get(“i.score”));
                     rankInt =
                                  Integer.parseInt(map.get(“i.rank”));
                } catch (Exception e) {
                }
                        //Now you have scoreInt, rankInt
                    //You can handle your code here
             }
             return super.shouldOverrideUrlLoading(view, url);
         }
     });
     webView.loadUrl(url);
    }
}

Now, after building the URL, call BMGWebView by using this code:

Intent webIntent = new Intent(mainContext, BMGWebView.class);
webIntent.putExtra(“url”, uri.toString());
mainContext.startActivity(webIntent);

3.5 Get Game Result

With WebView, you can get the game result in WebViewClient implementation inside BMGWebView.

If you use an external browser, you will have to implement a new method in your main activity.

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (intent.getAction().equal(“com.mbizglobal.bmg.PLAY”)) {
         //get rank: intent.getIntExtra(“rank”, 0);
       //get score: intent.getIntExtra(“score”, 0);
    }
}

Result data:

Field nameDescription
rankThe latest ranking number on the leaderboard
scoreThe latest game score

3.6 Show Game Result with your own UI

In the previous step, you got the “rank” and “score” values. You can define your own GUI such as dialog, page,… to render game result, to reward your main game.

3.7 How to give a reward to your application user based on event game score

If your application or service uses its own point system (such as score, mileage or virtual money), you can convert the user’s score to your application’s own point system. There are two ways to convert the event game score:

Way 1)

– maxScore in section 3.1.2 Decode data can be used to get the maximum possible score that can be obtained in the current event game. The max score will be needed to convert the event game score to your own point system. Please refer to the table below :

Allowed max reward point in your application. (A)Max score in the specific event game. (B)The constant to convert.(A / B = C)User’s scorein event game (D)Converted reward pointin your application (C * D)
1004,0000.0253,60090
4501,5000.3350105
10,0002,00051,3506,750

Way 2)

– The score range in the specific event game can be adjusted by Emoji Games’ Service Operation team. If you would like to adjust the score range of a specific event game in order to use it directly for your reward point system, please contact Emoji Games’ Service Operation team at support@brandedminigames.com.

Submit a query

Leave us a message