About

Welcome to esupersun’s blog! This blog covers general technical discussions on mobile game development (Android and iOS). If you're interested in mobile game programming and like to share your ideas, please visit Apphex Forums to join the top Mobile Game Developers Forum community.

Thursday, August 14, 2014

Android Practical Programming: Implementing Google Play In-app Billing Features within Your App

There are dozens of monetization strategies that mobile app developers can choose from to earn decent revenue. Selling in-app items is probably the most common method that app developers use these days.
Google Play in-app billing service enables the developers to charge for virtual items, additional features, or upgrades to unlock new levels in apps. Your users experience a consistent and familiar purchase flow since it utilizes the same checkout backend service as is used for application purchases.
This article discusses the basic process of implementing Google Play in-app billing features within your Android app.

Adding  in-app items

Begin by signing in to your developer console, click on the “All Applications” icon in the left sidebar, then click on the “In-app Products” section to add your in-app products as shown in figure 1:
Figure 1 Add in-app items

If you do not yet have a Google Play developer account, go to https://play.google.com/apps/publish/signup and follow the signup steps to register a developer account.
Google Play in-app billing supports the following 3 basic product types to give you flexibility in how you monetize your app.
Managed Product. Managed items can be purchased only once per user account on Google Play. Google play permanently stores the transaction information for each item on a per-user basis.
Unmanaged product. Unmanaged products are not managed by Google Play. You are responsible for managing the transaction information and cannot query Google Play to retrieve transaction information. Unmanaged products need to be explicitly consumed.
Subscription. A subscription is a product type offered in in-app billing that lets you sell content, services, or features to users from inside your app with recurring monthly or annual billing.

Make sure the product IDs (e.g. micbots.xshuttle.item1) you set on Google Play are exactly the same as the ones you named in your app.

//Globals.java
//Google Play services SKUs
//static final String SKU_ITEM_1 = "android.test.purchased";
//Product ids (skus)
static final String SKU_ITEM_1 = "micbots.xshuttle.item1";
static final String SKU_ITEM_2 = "micbots.xshuttle.item2";
Adding the in-app billing library

Next, to use the in-app billing features, you must add the IInAppBillingService.aidl file to your Android project. This file defines the interface to the Google Play service.
You can find the file either in the code project (built for Android Games: Practical Programming by Example, Quickstart 2, X Shuttle) or the samples coming with the Google Play Services SDK.
Then, add this line in the AndroidManifest.xml file as your app needs the permission to communicate with the billing service.


<uses-permission android:name="com.android.vending.BILLING" />


Binding your activity to the in-app billing service

With the in-app billing library added, now it’s time to set up synchronous communication with Google Play.
Create an IabHelper instance in your activity's onCreate method, passing in the Context for the activity and a string containing the public license key.


IabHelper skuHelper;

//Initializes product SKUs, called in onCreate()
protected void initSKU(){
    try {    
      
          skuHelper = new IabHelper(this, base64EncodedPublicKey);
      
          //Enables debug logging (for a production application, you
          //should set this to false).
          skuHelper.enableDebugLogging(BuildConfig.DEBUG);
      
          //Starts setup. This is asynchronous and the specified listener
          //will be called once setup completes.
          //Log.d(TAG, "Starting setup.");
          skuHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
              public void onIabSetupFinished(IabResult result) {
                 
                  //If disposed of, quit.
                  if (skuHelper == null) return;
      
                  // IAB is fully set up. Now, let's get an inventory
                  //of stuff we own.
                  //Log.d(TAG, "Setup successful. Querying inventory.");
                  skuHelper.queryInventoryAsync(mGotInventoryListener);
              }
          });
    }
    catch(Exception ex) {
       //ex.printStackTrace();          
    }
}


Once the setup is complete, you can use the skuHelper reference to communicate with the Google Play service.
Handling SKUs and launching purchase flow
When the user clicks screen to purchase the product items in the game, the game logic will launch the purchase flow by calling skuProcess() method.

//Handles SKUs, launches purchase flow
protected void skuProcess(int itemId){
       //avoids duplicate purchases
             
       skuHelper.launchPurchaseFlow(this, getSKU(itemId), REQUEST_SKU,
                mPurchaseFinishedListener, getString(R.string.shop_pc));
Implementing the purchase finished listener
.
The purchase finished listener will check the SKU of the purchased item to make sure it matches the one specified in the purchase request. In the event of a successful purchase, the method will consume the purchase by discarding the previous data to allow make new purchase with the same ID. If the purchase is not consumed, future attempts to purchase the item will throw complaints.
Remaining with the main activity file, implement this method as follows:

IabHelper.OnIabPurchaseFinishedListener
mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {

       public void onIabPurchaseFinished(IabResult result, Purchase purchase)
       {
           
            //Log.d(TAG, "Purchase successful.");

            if (purchase.getSku().equals(SKU_ITEM_1)) {
                savePrefs(PROMOTYPE_1);
                //Log.d(TAG, "item1 purchased");
                alert(R.string.shop_msg, getString(R.string.shop_item1_msg));
            }
            else if (purchase.getSku().equals(SKU_ITEM_2)) {
                savePrefs(PROMOTYPE_2);
                alert(R.string.shop_msg, getString(R.string.shop_item2_msg));
            }
       }
};

Releasing the labHelper instance

The last task is to make sure the object skuHelper is released when the activity is done.
//Unbinds from the In-app Billing service when the activity is done
@Override
public void onDestroy() {
   super.onDestroy();
   if(mHelper != null) {
       mHelper.dispose();
       mHelper = null;
   }
}

Project screenshots

As previously outlined, we added 2 product items in our project: Deluxe Pack and Lite Pack. The former is a managed item that can be purchased only once per user account on Google Play, while the latter is an unmanaged item that can be purchased many times.
As illustrated in figure 2 and 3, you can design your customized shop view using ViewPager, a layout manager that allows the user to flip left and right through pages of products to pick up the right one they may like.

Figure 2 In-app managed item


Figure 3 In-app unmanaged item 
When the user clicks to purchase items on the product pages, the game logic will launch the purchase flow by calling the in-app billing service as illustrated in figure 4.


Figure 4 Purchase deluxe pack
When the purchase is complete, the user will receive a congratulations message displaying the benefits he/she obtained (figure 5).


Figure 5 Purchase completed
As the managed item can be purchased only once per user account, an alert will pop up to prompt the user that he/she already owns the item if it’s tapped again (figure 6).
Figure 6 Purchase alert

Summary

Google Play in-app billing service enables the developers to charge for virtual items, additional features, or upgrades to unlock new levels in apps. It supports 3 basic types of items: managed, unmanaged, or subscription based. No matter what kind of items you configure in your app, your users will experience a consistent and familiar purchase flow since it utilizes the same checkout backend service as is used for application purchases.
This article worked through the basic steps involved in integrating Google Play in-app billing features into your Android app.


Purchase the full edition of this Android Games Practical Programming publication (Quickstart 2) on Amazon Bookstore: eBook ($9.90), Paperback ($34.50)
eStore: Android Games - Practical Programming By Example (X Shuttle)

Android Practical Programming: Monetizing Your Android Apps with Google Play Ads

Google Admob is one of the easiest and fastest monetization platforms that most app developers utilize. This article shows you how to integrate Google Play Services SDK into your app to make revenue by offering in-app ads.

Installing the latest Android SDK packages

A prerequisite to monetizing your apps with Admob ads is that you get the latest Android SDK packages installed on your development computer.
In Eclipse or Android Studio, Click on SDK Manager  in the toolbar to download the latest SDK tools (figure 1):
§  Android SDK Tools
§  Android SDK Platform-tools
§   Android SDK Build-tools (highest version)
§  A system image for the emulator, such as ARM EABI v7a System Image
§  Android Support Repository
§  Android Support Library
§  Google Repository
§  Google Play services
§  Google Play Billing Library

Figure 1 Download the latest SDK packages
Adding the Google Play services library

As Admob is now a part of Google Play services, developers who use Google Play API services also need to add the services library into their apps.
After you’ve downloaded the latest SDK tools, try to locate the Google Play services library project. By default, it’s placed at the folder <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/. Copy the library to your development workspace as you should not reference the library directly from the Android SDK directory.
In Eclipse or Android Studio, click File>Import, select Android>Existing Android Code into Workspace, then browse to your development workspace, locate the subfolder “google-play-services-lib” and import it as illustrated in figure 2.


Figure 2 Import Google Play services library

Then, right click Your project>Properties, select “Android” properties group at left and locate the Library properties at right, then add “google-play-services_lib” reference as shown in figure 3.


Figure 3 Import Google Play services library

Setting up the manifest

After you’ve added the Google Play services library as a dependency for your project, open the manifest file AndroidManifest.xml and add the following tag as a child of the <application> element:

<meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version"/>

It also requires that an “AdActivity” is declared in your app’s AndroidManifest.xml:

<activity android:name="com.google.android.gms.ads.AdActivity"
              android:configChanges="keyboard|keyboardHidden|orientation"/>

Moreover, making ad requests requires internet and network access permissions:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Implementing setAds() methods

Before adding this method, you must import the Google Mobile Ads package com.google.android.gms.ads in the main activity:


import com.google.android.gms.ads.*;


Remaining in the main activity file, declare a few variables as follows:

//Admob ads
String adId; //google advertising id
boolean limitAdTrack; //limit ads tracking
AdView adView;
AdRequest adRequest;
§  adId is a user-specific, unique, resettable Id for advertising, provided by Google Play services. It is an anonymous identifier for advertising purposes and enables users to reset their identifier or opt out of interest-based ads within Google Play apps.
§  limitAdTrack is a Boolean flag that indicates whether or not the user opts out of interest-based ads within Google Play apps.
§  adView is a view that holds the Admob html5 ads.
§  adRequest is an Admob AdRequest object that contains information about the ad to fetch. The information is primarily for targeting, though parameters can also be set to control ad formats and such.
Now create an AdView instance and set its size and unitId in the method:

protected void setAds(){
       // Creates an ad
       adView = new AdView(this);
       adView.setAdSize(AdSize.BANNER);
       adView.setAdUnitId(getString(R.string.ad_unit_id));          
}


Implementing loadAds() methods

To implement your customized loadAds() method, add all emulators and your own device as test devices, then call Admob loadAd() method. You can check logcat output for the hashed device Id to get test ads on a physical device.

protected void loadAds(AdView adView) {        
      
       try {
           adRequest = new AdRequest.Builder()                
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .addTestDevice(getString(R.string.device_id))
                .build();
           adView.loadAd(adRequest);           
       }
       catch(Exception ex) {
           //ex.printStackTrace();             
       }
}

 Calling setAds() and loadAds() methods

With the setAds() and loadAds() methods implemented above, it’s time to call them in the main activity.


//Adds the AdView to the view hierarchy.
if(showAds) {
       final LinearLayout layoutAdAchieve
            = (LinearLayout) findViewById(R.id.layout_ad_achieve);
       setAds();
       layoutAdAchieve.addView(adView);
       layoutAdAchieve.setGravity(
            Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
       loadAds(adView);
}

That’s it! Now you can run your app and see how the Admob ads show up on the screen (figure 4).

 Figure 4 Display Admob ads

It may take a while for Admob Ads to appear on the screen as it is being set up for the very first time, it should be faster in subsequent loads.

Summary

AdMob is Google’s mobile advertising platform specifically intended for mobile apps. It enables your apps to generate revenue by offering in-app Admob ads.
This article walked through the basic steps involved in integrating Google Play Services SDK into your app to make revenue by showing in-app ads.



Purchase the full edition of this Android Games Practical Programming publication (Quickstart 2) on Amazon Bookstore: eBook ($9.90), Paperback ($34.50)