How to Add In-app Billing to an Android Game – Part 1

In an earlier article, I wrote about in-app billing inside an Android game app I am working on. This is the first of two follow-up articles in which I explain how to add in-app billing to your game or other app. In this article I will walk you through the steps for the TrivialDrive example program from the Android Developers website. That website provides a sample in-app billing (IAB) app. It shows you how to do simple in-app purchases and subscriptions. To give you an idea of what that app looks like, here are a few screenshots. The sample app has you driving a car. As you drive, you consume gas. The two buttons on the right allow you to purchase gas.

trivial_drive_01trivial_drive_02

After the “buy gas” button is pushed, a new dialog window is displayed. You are asked to confirm the purchase. If you confirm, you are prompted for your password.

trivial_drive_04trivial_drive_05

Instructions

The sample app is fairly easy to get going. The instructions are very good. Start with the instructions on the Android Developers website.

android-developers-01

Their first step, “Download the Sample Application”, is actually two steps. Before loading the sample application code, they ask you to make sure you have the in-app billing library installed. That library is labelled “Google Play Billing Library”, as shown below.

android-sdk-manager

After that they ask you to locate the sample app, which is inside the sdk folder of the place where you installed Android. While you are loading it, you might want to give the project a new name. In the figure below, you see that I changed the name to “TrivialDriveIAB”. It’s also good to check the box labeled “Copy projects into workspace”. Doing that, leaves the original source code unchanged in its original folder, which is good should you want to start over or do another in-app billing project based on the same sample code.

import-trivial-drive-project

After importing the sample project, check that it compiles without errors. If it does not compile, check the project preferences and be sure you are using a new version of Android (e.g. 4.4.2). Rename the project package. You need to do this because every app should have a unique package name. Then go into the AndroidManifest.xml file and change the package there too. You will also have to fix the line in MainActivity that imports the R class. Change that line so it gets R from your new package.

rename-package

At this point, you should switch over to the instructions in the README file that is provided with the sample application.

trivial-drive-readme-01 trivial-drive-readme-02 The README instructions are very well written. You will end up doing all the steps, but the sequence of steps has changed since they wrote the instructions. I found that you need to have your packaged app ready in preliminary form a bit earlier than what they say.  The notes below take this into account.

Follow the README instructions. The first part starts at the Developer Console.

(From README)

ON THE GOOGLE PLAY DEVELOPER CONSOLE

1. Create an application on the Developer Console. You must use version 2, available at https://play.google.com/apps/publish/v2/ or later. In-app billing version 3 is not available in the older versions of Developer Console.

2. In that app, create MANAGED in-app items with these IDs: premium, gas Set their prices to 1 dollar (or any other price you like, but make it a small price since this is just for testing purposes).

3. In that app, create a SUBSCRIPTION items with this ID: infinite_gas Set the price to 1 dollar and the billing recurrence to monthly. Just so you are not immediately charged when you test it, set the trial period to seven days.

4. Make sure your test account (the one you will use to test purchases) is correctly listed in the “testing” section. Your test account CANNOT BE THE SAME AS THE PUBLISHER ACCOUNT. If it is, purchases won’t go through.

A few screenshots and comments follow, related to these steps. For step 1, when you add the application, you can start with the “Prepare Store Listing” button.

dev-console-01

Enter descriptions for the app, set the price to “free”, and add placeholder images for the screenshots and marketing images.

You will find that you won’t be able to get to Step 2 until there is an APK file in place. They stop you part way through when you start to define your in-app products. You will see a screen like this one:

need-apk-with-billing-permission

So it’s best to have an APK file ready. In Eclipse, you use the “Export Android Application” command on the “Export” menu. Exporting an app requires a key file so your app can be signed. Signing your app is easy if you have done it before with another app. If you are a new developer and have not built an APK file before, you have a few things to learn. Good references related to that are: (1) Preparing for Release; (2) Signing Your App; (3) article about the Keytool command. Basically what you are doing is adding a unique digital key to your packaged app. That key is used to look up the information you have defined for in-app products.

When you upload, use the Alpha Testing tab and upload the APK file. The Alpha test version will not be visible in the Google Play store.

dev-console-02

With a preliminary APK file in place, you are ready for defining the in-app products. The screenshots below should give you an idea of what you will do during Steps 2-3.

dev-console-05 dev-console-06

For Step 4, the place to look for the account for testing is under “Account Details”. That is under “Settings” for your developer account. It applies to all apps that you have and not just the TrivialDrive app. Down a bit on the Account Details page is a section named “License Testing”. It is highlighted in the figure below.

dev-console-07

Continuing on to Step 5, the instructions tell you to get the applications public key, which is used to associate your running application with the information you have entered for you in-app products.

5. Grab the application’s public key (a base-64 string) — you will need that next. Note that this is the *application’s* public key, not the developer public key. You can find the application’s public key in the “Services & API” page for your application.

The image below shows where to look for the public key. It is the very long string that is blurred out and highlighted with the orange text.

dev-console-03

After the five steps in the Developer Console, the README instructions switch over to the code in the your TrivialDrive – IAB application in Eclipse.

IN THE CODE

1. Open MainActivity.java and replace the placeholder key with your app’s public key.

2. Change the sample’s package name to your package name. To do that, you only need to update the package name in AndroidManifest.xml and correct the references (especially the references to the R object).

3. Make sure that AndroidManifest.xml lists the updated package name!

4. Export an APK, signing it with your PRODUCTION (not debug) developer certificate

A few notes about what is going on inside MainActivity are later in the article. For now,  keep it simple and just make the editing change (Step 1)  to put the product key into the code. You can also ignore their security recommendation “TODO”. Get the sample app to work and then worry about what a real, finished app should handle. You might not need to worry about Step 2 if you renamed the package earlier, as I suggested above. While you are editing in the manifest file, fix up the “targetSdkVersion” line, making it match whatever version of Android you are using to compile with.

 <uses-sdkandroid:minSdkVersion="10" 
  android:targetSdkVersion="19"/>    

For Step 4, build your app and export it, as described earlier. Then continue with the README instructions.

BACK TO GOOGLE PLAY DEVELOPER CONSOLE

1. Upload your APK to Google Play 2. Wait 2-3 hours for Google Play to process the APK (if you don’t, you might see errors where Google Play says that “this version of the application is not enabled for in-app billing” or something similar)

As stated earlier, use the Alpha Testing tab and upload the APK file. The Alpha test version will not be visible in the Google Play store. In the top right part of the screen, you should see a “Ready to Publish” button. Publish the app.

dev-console-02

The instructions in the README make publishing seem like it is pretty easy. In a way, it is, but there are a few things you have to take care before you can publish. They have minimum requirements that include descriptions of the product, setting prices, marketing images, etc. Fortunately, there is a good checklist that they provide. Just work your way through the items one a time. Use placeholder images for the marketing images. Here is what the checklist looks like.

dev-console-04

Testing

The last part of the instructions in the README are related to testing.

TEST THE CODE

1. Install the APK, signed with your PRODUCTION certificate, to a test device [*] 2. Run the app 3. Make purchases (make sure you’re purchasing with an account that’s NOT your developer account with which you uploaded the app to Google Play).

Remember to refund any real purchases you make, if you don’t want the charges to actually to through.

[*]: it will be easier to use a test device that doesn’t have your developer account logged in; this is because, if you attempt to purchase an in-app item using the same account that you used to publish the app, the purchase will not go through.

One suggestion for a test device (Step 1) , for those of you that have a Nexus 7, is to set up your tablet with multiple users. I did that and made one of the users be my test user. Some of the errors you are likely to see include:

  • It takes some time (2-3 hours, they say) for your app changes to be visible after publishing. If you test too early, you will see messages about there being no in-app products. The most common message is “the item you are attempting to purchase cannot be found”.
  • If you run without access to the Internet, the error messages you see might not be that clear or might make you think that there is a serious problem with the app. So do check for connectivity as one of your first corrective actions.

The README reminds you to refund purchases for the test purchases. What they are referring to there is Google Wallet. As a developer, you do need to set up a Google Wallet account. The screenshots below show where you go to cancel test orders.

wallet_01

wallet_02 wallet_04

Next Article: Inside the Code

The focus on this article has been on getting a working example going. That is a really important step. The TrivialDrive app will be your reference app as you move ahead  with your own app. I do not recommend skipping the TrivialDrive example. There are too many things that can go wrong if you are learning the basics of in-app billing at the same time as you are adding items to your own app. Getting your own app working will be the subject of “Part 2″ of this article.Topics to be covered include:

  • Understanding the code and methods that you use to make in-app purchases. That includes querying to see what items are available, querying to see what items have already been purchased, starting and completing transactions to purchase an item, etc.
  • Adding in-app billing code in a way that does not complicate your existing app code.
  • Making it easy to track changes to the in-app billing code.
  • Making design decisions about what in-app products to offer and how to present them to users.
  • Information about the best practices the README authors mention related to security.

References

Preparing Your In-App Billing Application – the primary reference that this blog note is covering.

Preparing for Release – an article on developer.android.com that tells you what you should do to prepare for releasing an app.

Signing Your Application – another developer.android.com article; this one is about how you sign your application before releasing it.

Java keytool command, keystore files, and certificates – this note contains a lot of useful information about using the Java keytool.

In-App Billing in an Android Space War Game – my earlier article on in-app purchases for the game I am working on.

 

 

Posted in Android | Tagged , , , , | Leave a comment

New demo video for Starship app

Your chance to save the galaxy.

 

For more information on this Android app: see Starship Alpha Test and articles tagged “space war”.

Posted in Android | Tagged , , , | Leave a comment

Improved Play Screen in Starship App

The latest alpha test version is out for my Starship game app on Android. The big improvement  is the new action bar along the top of the screen. Status bars show the energy level of the ship and shield strength. Time left, enemy count, damages, and speed are also shown. The new status indicators provide better feedback as you play.

starship-play-n7-140619

This version also includes Google Play leaderboards.

To try the Alpha test version of the app, go to the Google+ community for Starship and click the “Join” link:

Try the Starship app

Further design improvements are on the way. The Beta test version should be available August – September 2014.

Posted in Android | Tagged , , | Leave a comment

In-app Billing in an Android Space War Game

I am going to write a series of articles about how to implement in-app billing for an Android game app. I will get that started by telling you something about the game app I am working on and how in-app purchases tie in to upgrades within the game.

Coin purchase screenshot

The name of the app is “Starship”, but that’s likely to change during beta test. Starship is a turn-based, single player, space war game. It is available for Android phones and tablets. The game begins with you in training. You take on training missions that allow you to advance through the ranks of Weapons Officer, Navigator, Commander, and finally, Captain. Upon promotion to Captain, you command a very powerful starship. Your mission is to find and destroy alien starships that have invaded the galaxy. To end the threat completely, you must find the alien home world and destroy it. A screenshot from the game is shown below.

scene-from-starship-space-war

As you play the game and destroy alien ships, you earn gold coins. The coins can be used to purchase items that improve your capabilities. In the current version of the game, there are four upgrades that you can purchase:

  • Long Range Move Equipment – allows you to jump to a distant quadrant in one move. Crystals power this equipment.
  • Mining Equipment – allows you to mine crystals from planets.
  • Extra Starbases – give you more places where you can resupply and make repairs
  • Extra Mission Time – gives you more time to complete missions

None of these upgrades are made with in-app purchases. All it takes to upgrade is gold. There are, however, two ways to get gold coins: (1) you can earn gold coins within the game by going on missions, destroying the enemy ships, and moving up levels; or (2) you can go to the Coins store screen and purchase coins there.

The figures below show what a complete transaction looks like within the game. You start on the Coins screen, select an item to purchase, enter your password, and then wait for the order to be fulfilled. The white popup boxes are being done by code in the Google Play services library.

starship-iab-03

 

starship-iab-04b

starship-iab-05

Once the receipt makes it back into the game, notice that the coin total in the upper right of the game screen increases by the amount of coins you purchased.

starship-iab-06

After the purchase, the player uses the Upgrades screen to purchase one of the upgrades.

starship-iab-08

Model for In-App Purchases

In some game apps, you have to make an in-app purchase if you want the extra equipment or powers. That is not the case in this game.

In Starship, you are not required to make in-app purchases to get ahead in the game. If you earn the coins playing the game, use them to make upgrades. If you would like to get those items a little faster, you spend real money to get in-game money. Of course, the other reason to make a purchase is because you enjoy the game and would like to send a little money to the developers as a way of thanking them.

Next Articles

This note is not a how-to article. What I usually do on this blog is provide working demo programs with source code. That’s what you will see in the next set of articles about in-app billing and purchases.

Topics for the upcoming articles include:

  • Suggestions on how to get started with the TrivialDrive demo program.
  • Adapting the TriviaDrive demo to your own application.
  • Tips and suggestions for testing in-app billing.
  • Tutorials and suggestions for building your own Coins and Upgrades screen.
    (Some of this is already available. See below.)
  • Different ways to invite players to upgrade.

References

New Turn-Based Space War App – article about the Starship game app. Read this if you want more information about the game or would like to be part of the test community.

Update on Starship game – a short note about some new features in the game.

Android Fragment for an Item in a Store – article about a demo app that uses Android fragments to displays items in a list. The same fragment is used in the Starship app for the Coins screen and the Upgrades screen.

Examples of Store Item Activities in Android – a follow-up article to the fragment article.

Google I/O 2012 – Monetizing Android Apps – a talk from Google I/O 2012. It covers the different ways you should consider for making money from your apps.

 

 

Posted in Android, Game Design | Tagged , , , , | 1 Comment

My Reminder: How to fix “conversion to Dalvik format failed with error code 1″

Every month or so, while exporting an Android application to get an apk file, I see the mysterious message: “Conversion to Dalvik format failed with error code 1″. Information on what to do is easy to come by. I search Google on that phrase and get to another great StackOverflow page with an explanation.

http://stackoverflow.com/questions/2680827/conversion-to-dalvik-format-failed-with-error-1-on-external-jar

export-app-error-code-1The problem for me is that particular question /answer post is fairly long and points out that there  are several different things you should try. Since I keep forgetting which of those work for me, I am posting ny standard steps for myself here.

I work on a Macbook, run Eclipse, and I usually do very well at keeping my Android environment up-to-date. Also, when I build I have Proguard set to run, which means I will see some unusual messages from time to time. Those tend to throw me off and forget what I should be doing.

My Standard Fixes

  1. I start with doing a clean build of the project with “Project – Clean”. I include the project and any projects it depends on.
  2. Then I check to see which Proguard I have installed. A new Proguard is required. Right now that is 4.11.

Step 1 used to be all I needed to do. I’d do the “clean” build and then try to export again, and it would work. This last week, however, that did not help. The export would fail and the Console messages would indicate that Proguard was having trouble. There are, of course, lots of things that Proguard can report on, but these messages said that none of the classes of the app itself  could be found. That did not make sense to me since I had built apk files for the very same app not long before. So that’s when the closer reading of the StackOverflow message paid off.  Someone noted that a newer Proguard fixed the problem for them.

Android tool set for Eclipse has an old version of Proguard. One more thing to watch out for is that the Android tools in Eclipse have an old version of Proguard. Any time you update that part of your Eclipse installation, it is going to overwrite the new Proguard you installed with one that might not work. So that’s why I have two steps. Fixing the problem with Step 2 is something I have to keep doing until the newer Proguard is in the Android tools update. The Proguard folder is inside folder “android\sdk\tools”.

So good advice, as always, from StackOverflow provides a solution. And for me, a good reminder is what I need so here it is in an easy place for me to find it.

 

Posted in Android | Tagged , , , | Leave a comment

How to View an Android Shared Preferences File

Here is what I do when I want to see the contents of an Android Shared Preferences file when I am debugging an app.

1. Change the AndroidManifest.xml so the app is debuggable. Add a line in the <application> tag.

android:debuggable=”true”

2. In Eclipse, run the application in the debugger. That is the “Run – Debug as …” menu item.

3. Run the app until you get to the point where you want to see the contents of a shared preferences file

4. Then start a terminal session and do the following commands after using the Android Debug Bridge (ADB) to start a shell.

adb shell
 $ run-as com.wglxy.starship
 $ ls

 $ cd shared_prefs
 $ ls
 $ cat game_data.xml

For your own app, be sure to replace the text in italics with your app’s package name and the name of the shared preferences file you want.

The two ls commands are there to reassure yourself that you are in the right place. The last command (cat) copies the contents of the shared preferences file to the Terminal window. After that, I usually copy all of the text from the Terminal windows to an editor or text viewer so I can take a close look at it.

I do not know exactly where this works. I work in Eclipse Indigo on a Macbook.  These steps work fine with my Nexus 7 tablet, which is running Android 4.4.2. However, it does not work on my Galaxy Nexus phone (Android 4.3).

Sorry for the imperfect solution, but I thought it would be better to share a partial solution because, when it does work, it is quick way to see what is going into your shared preferences files.

Acknowledgement

Thanks go to Dennis Kubes for writing “Read Android Data Folder Without Rooting“. It took me a while to figure out which devices I could use his suggestions for, but now I use it all the time.

Posted in Android | Tagged , , | 2 Comments

More Mobile Enemy in Starship App

For those of you who are following the progress of my Starship game app for Android, here is a short update. The latest alpha test version of the Android app is out. Version 0.93 features a more mobile enemy fleet. At level 1, the enemy move when a Commander ship is nearby. After level 1, all enemy ships move. Leaderboards are working again. Sign in to Google+ to use them. Touch Leaders on the Menu screen after you get through training.

To try the prerelease version of the app, go to the Google+ community and click the “Join” link:

Try the Starship app

Please note that improved graphics are on the way. Look for better graphics in the Beta test version, which should be available May – June 2014.

The latest demo video is on Youtube.

Related Articles

For software developers interested in how this app was constructed, read these blog articles.

Posted in Android | Tagged , , , | 1 Comment