Android Add Game Leaderboard

In order to display leaderboards from your game you will have to set up your project and to be signed in. Below you will learn how to do this.

Project Setup

  1. Download the Android samples from https://github.com/playgameservices/android-basic-samples
  2. Import BaseGameUtils into your project as module
  •  Go to the directory where you downloaded android-basic-samples and select libraries -> BaseGameUtils

  • If you get the below error:

 

 

Tap on the link and let the ide install missing platform.

  • You might get another error:

Tap on this link also and then go build.gradle from BaseGameUtils.

Change build.tools and library versions to the latest ones and sync the project. At the time of this tutorial, the current versions are 3.0.0, 27.0.0 and 11.4.2

3. Add to your app build.gradle file compile project (‘:BaseGameUtils’)

 

5. Add ids.xml to res – values directory

You will learn further in this tutorial how to obtain these 2 ids.

6. Add meta-data code inside <application> tag from AndroidManifest.xml

How to get the app_id?

In order to get the app_id and be able to use Google Play games services, you need to:

  • set up the game in the Google Play Console
  • generate an OAuth 2.0 client ID for your Android app.

Below are the steps about how to do this:

1. Add new game in Google Play Console

2. Game Set Up

3.  Go to Linked Apps

4.  Select Android platform

5. Set package name (of your app)

Don’t forget that you have to copy-paste here your app package name. After that, click on the Save and Continue button.

6. Authorize your app now

7. Copy-paste your app SHA1 fingerprint

In order to obtain your SHA1 fingerprint follow the steps from this post.

8. Obtain Application Id

In the screenshot is our application id. You will have to copy yours and then paste it in the ids.xml file from your project.

9. Create your Leaderboard

10. Save Leaderboard

11. Copy Leaderboard id

Copy your leaderboard id and paste it in ids.xml file.

MainActivity class

We just used BaseGameActivity class from BaseGameUtils module. It is an example class that  akes care of setting up the API client object and managing its lifecycle.

IMPORTANT: If your app is unpublished and you haven’t added a test account, you will have to do this.  See the steps here.

Now you should be able to display your leaderboard. 🙂

You can also check the android developers documentation.

Android ViewPager Tutorial

In Android, if you need to swipe from right to left or vice-versa in order to see different data, you can use a ViewPager. In order to use it, you have to implement a PagerAdapter which will generate the pages that the view shows.

ViewPager’s adapters

We can use one of the 3 adapters provided:

  • PagerAdapter:
    • it is the base class for a ViewPager adapter
    • used when you need to display only views
  • FragmentPagerAdapter:
    • extends PagerAdapter
    • represents each page as a Fragment
    • each page is persistently kept in the fragment manager as long as the user can return to the page, but the view hierarchy can be destroyed when not visible
    • mostly used for static pages like tabs
  • FragmentStatePagerAdapter:
    • extends PagerAdapter
    • represents each page as a Fragment
    • handles saving and restoring of a Fragments’s state
    • mostly used for a large number of pages

When an adapter loads a page, it creates the adjacent pages also. This means that for position 0, it will also load the next page from position 1. And for position 1, it will load the pages from positions 0 and 2, and so on.

Fun fact: even though you can set a click listener or a longClick listener on a viewPager, they won’t work. ViewPager does NOT consume click events. You will have to set the click event on your view in instantiateItem() method.

PagerAdapter

First, we will see an example of a ViewPager that uses a PagerAdapter, this means that we will have to display only some views (in our case, some images :P)

activity_main.xml

view_pager_item.xml

MainActivity.java

As you can see, when using the base adapter, we have to implement the following methods at minimum:

  • instantiateItem(ViewGroup, int): in this method we have to inflate the layout which which will represent a page for the given position.
  • destroyItem(ViewGroup, int, Object): in this method we have to write the code that removes a page from its container for the given position. This method is called while the user navigates through pages. For example if the current position is 0 and the user navigates to the next page, which will be on position 1, at this point, the method is not called. But, when the user goes again to a next page, position 2, at this point, the page from position 0 will be removed. And from now on, whenever the user swipes to a next page the method will be called for the next positions, 1, 2 and so on.
  • getCount(): here we have to provide the number of pages that the viewPager will have to display. In our case, the size of list containing our images which is 3 🙂
  • isViewFromObject(View, Object): it is required for a PagerAdapter in order for it to function properly. It checks if Object (the one returned by instantiateItem(ViewGroup, int)) is the same with View.

FragmentPagerAdapter and FragmentStatePagerAdapter

In order to implement any of these 2 adapters you will have to implement just 2 methods to have a working adapter:

  • getCount()
  • getItem(int)

Of course, you can also implement methods from PagerAdapter also if you need to.

In the following example, we will use the same example as above, but using a FragmentStatePager adapter. The example is available for a FragmentPagerAdapter too, as both adapters have to implement same methods.

view_pager_item.xml and activity_main.xml will remain the same. What changes is MainActivity.java class and we have to create a new java class (a fragment), named MyFragment.java.

MyFragment.java

MainActivity.java

FragmentStatePagerAdapter vs FragmentPagerAdapter

What is the difference between these 2 adapters? Well is the way they handle the life of pages. The first will destroy and recreate the pages if we implement getItemPosition() POSITION_NONE. But the latter, will not destroy them, but it will attach and detach them which makes it perfect to use for fragments that are permanent.

Fun fact: notifyDataSetChanged() doesn’t work by itself on a viewPager. It has to be used together with

The above method is triggered by notifyDataSetChanged().

Android ViewPager Cube Animation

After trying some libraries in order to make a cube animation for my viewPager, I realized that is pretty easy to do this. Android provides an interface called ViewPager.PageTransformer and you just have to implement its method transformPage().

Below is the code, step by step.

activity_main.xml

view_pager_item.xml

 

And now, the interesting part of the tutorial:

CubeTransformer.java class

Let’s explain a bit this code. As you can see, we created a new class CubeTransformer that implements the interface I mentioned at the beginning of the post, ViewPager.PageTransformer. The tranformPage() method that has to be overridden, is called for each visible page and for its adjacent pages (left and right) and requires a view and position.

  • view: represents either the current view that starts beeing swiped, either the next one
  • position: represents either the position of the current view, either of the next one
    • 0 – is for the current view/page when it fills the screen
    • 1 – is for next view/page that has just been drawn
    • when the user starts to swipe between pages, page one (current) will have positions with negative values, and the next page that has to come in place, will have positions with positive values.

Before going further, we have to mention that in Android the x,y coordinates start from the top left corner.

The animation is done with just 3 lines of code:

  • view.setPivotX(): This is like a pin on the x axis around which the view will be rotated and scaled.

In our code, when position <= 0 (current image) we will set the pivot on the rightmost point of the X axis (view.getWidth()) , and when position > 0, (next image) the pivot is set on the left (origin of the axis) on X axis. This way, the pages will look like the faces of a cube.

  • view.setPivotY(): This is like a pin on the Y axis, around which the view will be rotated and scaled.

In our code, we set this to be on the halfway on Y axis.

  • view.setRotationY(): The view will be rotated vertically around Y axis with 90 degrees on the left multiplied by position.

So, using these 3 lines of code, we can have a cube animation on our viewPager 🙂

Now, the final step of the tutorial, is about how to use the above class.

MainActivity.java

The only new thing in the above code, is this line:

The rest of the code is just the usual implementation of a ViewPager.

Android Navigation View With Tabs

In this tutorial we will create a simple app which has a NavigationView, a Toolbar with Tabs and a simple list of items, that are displayed for each selected tab.

Tabs & Navigation lollipop and above

Tools used:

  • Android Studio 2.2 Preview 4
  • Android Emulator 5x API 22

Project

  1. Create a new project by choosing the empty template and then click the Next button until the project is created.
  2. Switch the visibility of project structure by selecting “Project” option like in the image below.
    Android Project Structure

Part 1: NavigationView

First, we will create the NavigationView like explained further in the tutorial.

Summary

  • add compile ‘com.android.support:design:24.0.0’ to dependencies in build.gradle
  • handle theme setup in values – styles.xml
  • handle theme setup in values-v21 – styles.xml
  • set the themes in AndroidManifiest.xml
  • create menu items for NavigationView
  • add strings in strings.xml
  • add dimensions for NavigationView’s header in dimens.xml
  • create the xml file for the NavigationView’s header
  • set TabLayout and NavigationView in the activity_main.xml
  • setup NavigationView in MainActiviy.java

Explanation

  • build.gradle

    In the app module directory, open the build.gradle file and add ‘com.android.support:design:24.0.0’ to dependencies.

  • Theme setup in values – styles.xml

    Under app – src- main – res – values – styles.xml, set the default AppTheme to support a NoActionBar theme.

    Styles.xml from this directory, will be used for Android versions lower than API Level 21 (Lollipop). Also, keep in mind that for lower versions of Android the status bar won’t be transparent when the NavigationView is opened.

  • Theme setup in values-v21 – styles.xml

    You will have to create this directory because we will use 2 attributes which are available only for Lollipop and above. The directory must be created like this:

  1. Right click on the res directory
  2. Click New – Android resource directory
  3. Select values directory and api level  like in the image below:
    Values v21
  4. Now, inside this directory create a styles.xml file like this:
    1. right click on the values-v21 directory 
    2. click New – Values resource file
    3. write styles.xml
    4. This is the code you should add:

The 2 attributes that are available only from API Level 21 and above are:

  • android:windowDrawsSystemBarBackgrounds: Flag indicating whether this Window is responsible for drawing the background for the system bars. If true and the window is not floating, the system bars are drawn with a transparent background and the corresponding areas in this window are filled with the colors specified in {@link android.R.attr#statusBarColor} and {@link android.R.attr#navigationBarColor}.
  • android:statusBarColor: this will make the status bar transparent when the NavigationView is opened
  • Set themes in AndroidManifest.xml

  • Menu items for NavigationView

    Now, we will have to create a menu directory in which we will have to create a xml file containing the NavigationView items.

    1. Right click on the res directory
    2. Click NewAndroid resource directory
    3. Select menu directory menu
    4. Now right click on the menu directory
    5. Click New – Values resource file
    6. Write navigation_items.xml
    7. Add the following code:
  • strings.xml

    Add the following strings to res – values – strings.xml

     

  • dimens.xml

    Go to res – values – dimens.xml and add the following code.

  • nav_header.xml

    Under res – layout create a new xml file and name it nav_header.xml. This layout will be added as header to the NavigationView. It contains 2 texts and an icon (this file is taken from the NavigationView project from Android Studio Templates).

  • activity_main.xml

    In this xml file we will set the NavigationView, toolbar and tabs, using CoordinatorLayout. In the image below, we have described the hierarchy of the views (which view contains which view).

    CoordinatorLayout Hierarchy

    As you can see, DrawerLayout is the root view of this layout and this is the correct way to do it. If you embed DrawerLayout inside other layout (let’s say a RelativeLayout as root view) and you place other UI components outside the DrawerLayout, those UI components will overlap the NavigationView when opened like below:
    DrawerLayout wrong hierarchy

  • Another wrong example, that I did in a project of mine, was that I used CoordinatorLayout as root view instead of DrawerLayout. And because of that, the navigationView was not being opened over the status bar.Also, you have to keep in mind that FrameLayout (the container) will be replaced in Java code with ContainerFragment.java fragment. This class handles the displaying of the list of items and tabs. You will see later how to use this class. So, by using the correct hierarchy, we can now play with scroll events for the toolbar, due to the use of CoordinatorLayout. But if we don’t follow this hierarchy, the scroll events or UI elements might behave in a strange way.
Explanation of some properties
  • android:fitsSystemWindows="true" Read TYL 15
  • android:theme="@style/AppTheme.AppBarOverlay" Read TYL 16
  • app:layout_scrollFlags="scroll|enterAlways" Read TYL 17
  • app:tabMode="scrollable" Read TYL 11
  • app:layout_behavior="@string/appbar_scrolling_view_behavior" Read TYL 13
  • MainActivity.java (intermediary code)

    At this point, you can run the app to see how the NavigationView looks like and how it behaves on different Android versions (pre-Lollipop and from Lollipop and above).

Next, we will proceed to part 2 of this tutorial: on setting up the tabs.

Part 2: Setup Tabs

Summary

  • setup xml file with ViewPager for the container view
  • setup xml file with RecyclerView for a page from ViewPager
  • setup xml file with a title TextView for RecyclerView rows
  • create a new Java class for RecyclerView’s adapter
  • create a new Fragment for ViewPager’s pages
  • create a new Fragment which represents the container. From here we will create the tabs and handle ViewPager’s adapter.

Project

  • fragment_container.xml

  • fragment_page.xml

  • recycler_item.xml

    Note: android:background="?android:attr/selectableItemBackground" is used in order to have a click effect on the RecyclerView when its rows are clicked.

  • SimpleRecyclerAdapter.java

  • PageFragment.java

  • ContainerFragment.java

  • MainActivity.java (final)

You can also see the project on Github.

Android AdMob With Firebase

About Firebase

First of all, you have to know that using AdMob with Firebase is optional, at least for now, and you can still integrate AdMob by importing compile ‘com.google.android.gms:play-services’ (like in this tutorial). But even if it is optional, it is recommended, as it brings all services like AdMob, Analytics, crash reporting and other services together in just one place.

Integration

Versions used:

  • Android Studio 2.2 Preview 3
  • classpath google-services 3.0.0 dependency
  • firebase-ads 9.0.2 dependency

Project setup for supporting ads

  • google-services.json file from Firebase Console
  • In Project-level build.gradle add Google Services to dependencies
  • In App-level build.gradle  add Firebase Ads to dependencies and apply Google Services plugin
  • Internet Access

Before we start, create a new project with an Empty Activity template. After the project is created you should have MainActivity.java class and activity_main.xml file in res folder. We will refer to these later in the code.

1. Download google-services.json

This file is mandatory for your project to compile. If google-services.json file is not added to your project, you will get the following error when trying to sync App-level build.gradle.

So, in order to download it, you have to register your project in Firebase Console. Below are the steps:

Register project in Firebase Console
  1. Open Firebase Console and click on the Create New Project button
  2. Type your app name and click on Create Project button
  3. Now the following page should openAdd Firebase
  4. Tap on the button like in the above image
  5. In the new page that will open, type your project’s package name (you can find it in your AndroidManifest.xml file or in activities above imports)Firebase Add Details
  6. Now, after you press Add App button, the google-services.json will be automatically downloaded
  7. Copy the file that has just been downloaded and add it to your project to the application’s root folder, YourAppName/app/Firebase Config File
  8. Click Continue and then Finish
2. Project-level build.gradle

Project Level Build Gradle

In the build.gradle file which is outside app module, you have to add the following dependency:

Now, tap on Sync Now to sync gradle.

3. App-level build.gradle 

Inside the app directory you can see another build.gradle file. In this file you have to add 2 lines:

Below is how the final code should look like:

Tap on Sync Now to sync gradle.

4. Internet access

In order to receive ads you need access to internet. So you have to add the code below in the AndroidManifest.xml, right above <aplication> element:

Add the ads

  1. Go to activity_main.xml file and add the following code

    Note: Notice that in order to use ads: properties we have to add to the root layout

    In order to get YOUR UNIT ID you should do the following:

    • go to AdMob site, click on the Monetize New App button and add your app.
    • If you want to can link the app to Firebase from here. But you can skip an link it later like shown in this tutorial.

    monetize

    • after you add your app, on the Monetize page, you should find your project on the left. Click on it and you will see your Unit ID. Unit IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN.

    admob_monetize

    test_unit

    Now, just copy it from here and paste it into your activity_main.xml file.

  2. Go to MainActivity and add this code:

NOTES

NOTE 1:

YOUR APP ID is different from Ad Unit Id. Application IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN and can be found on your AdMob account page by clicking the Settings icon – App Management.

NOTE 2:

It is very important to run the ads in debug mode on your own devices, in order to avoid being disabled for clicking your own ads. So, to get your device ID, you have to run your application on the DEVICE in debug mode and wait for an ad to load. Then go to logcat output and search for the ID. It should be at Log INFO like in the picture below. You can add as many devices as you want.

android_adMob_ID

Link your app from AdMob to Firebase

If you want to see Firebase Analytics information in AdMob you have to link your app from AdMob account with Firebase project we have just configured earlier.

  1. From AdMob account, tap again on the Settings icon – App management
  2. Search your app and tap on the Link to FirebaseLink to Firebase
  3. Add the package name of your app you (in our example we have to use the package name we used when we configured our app directly in Firebase)AdMob Package
  4. Click Continue button and you should see the following screenLink to existing
  5. In our example we let the first option to be enabled (Link to existing…) as we got an error that we cannot create a new Firebase project due to limit exceeded (even though we only have this project). Click the Continue button and done.

Successfully linked

See your linked apps in Firebase Console

View Linked Apps

Android Free/Paid Versions Tutorial

There are situations when you might decide that you need to create 2 versions for your application: a free one and a paid one. So, in this tutorial, which is just a simple example (we will just set different colors for the 2 versions), we will see how to achieve this using flavors. Your project is certainly more complex, but I think that this tutorial will be ok for you to get the main idea of how you can do this.

Create Flavors

First of all, you have to add 2 flavors: free and paid.in the build.gradle file which is located inside app folder (to not be confused with the build.gradle of your application which is outside of the app folder). Below is the code:

  1. build.gradle (from app module diferctory)

Configure Project Structure

Now, that we configured our 2 flavors we should create new folders (directories) in our project structure which map these 2 flavors. You can see how to do this in this tutorial. The project structure should look like this in the end:

free paid structure

 

NOTE: Notice that in order to identify later in our code if we use the free or paid version for enabling/disabling features, we have to add a custom flag in gradle using buildConfigField property. This custom flag “PAID_VERSION” will be available in BuildConfig class.

Below is the code used for using different colors for free and paid version.

  1. src – free – res – values – colors.xml

  1. src – paid- res – values – colors.xml

Flavors Usage

And below is the code for or example application, where we have just one text view and a MainActivity.

  1. activity_main.xml (from main directory)

  1. MainActivity.java

Now, in order to run your app in free version, you just have to select the freeDebug variant, from Build Variants which is located in the bottom-left of Android Studio:

free debug

And the result will be this:

free version

Do the same for the paid version. The result should be this after you run the app:

paid version

You can also check the tutorial on GitHub here.

Android Build Types and Flavors

In this tutorial we will talk about Build Types and Flavors, for what are they used, what is the difference between them and what they have in common.

Build Types

When you work on a project, at some point you might need to run your app in release mode, or debug mode, or qa mode, or any other mode you might need.

Why would I need this?

  • to have a signed apk with a release key for release mode, and non-signed with a release key for debug mode (debug key used instead)
  • to use different web service calls for qa mode, release mode, debug mode, etc, in case your web service team has different environments
  • to add a package name sufix.

E.g:

  • require extra permissions in debug mode, like ACCESS_MOCK_LOCATION for example.
Build Types Configuration

When you create an app, debug and release types are created by default. You can see them in Android Studio, by clicking on BuildVariants button on the bottom left of the Android Studio.

BuildVariants Default

But if you need to add new Build Types, like QA for example, or DEV, or whatever you need you have to follow these steps:

  1. Open build.gradle file from app directory (your module-level). Note: to not be confused with build.gradle of the project, which is located in the root of your project.
  2. Inside android {} block, you should already have buildTypes{} declared with release type in it. You just have to add your new build types you want. In our example we will add qa type:

3. Now, you have to tap on sync gradle popup that will be displayed.

SyncGradle

4. After the sync is done, click again on Build Variants button from the bottom-left of Android Studio and notice that now we have 3 build types:

Build Variants With QA

So now, if you want ro run your app in qa mode, just select qa type from here and run the app.

NOTE: Notice we added the signingConfig property in build.gradle. That was needed, because otherwise the app would not run and the following error will be displayed when you try to run the app:

Qa Unsigned Error

Create new source set directory for QA build type

Now that you have configured your new build type (QA), you need to create a new folder for QA in the project structure where you can override what you need.

  1. From app – src – right click on src folder – click NewFolderJava Folder – From Target Source Set select qa

New Source Set

Select QA Source Set

Now you should have 2 source type directories. main and qa, but in qa directory you will have just an empty java folder so you will have to add manually the other resource folders you wil need by always specifying the target source.

Source Types Project

 

Product Flavors

Flavors are similar in a way to Build Types, but they are used in case you need different versions of the same app. The best example in this case is free version vs paid version of an app. Or also flavors are used in case of rebranding an app (different resource files and slightly different code).

Product Flavors Configuration

  1. Open build.gradle file from app directory (your module-level), the same build.gradle used for Build Types.
  2. Inside android {} block, below buildTypes{} add the above code.

The final gradle files should look like this:

3. Now sync gradle and look to Build Variants options. You will see a combination between our Build Types and Product Flavors:

BuildFlavors

So basically, Build Variants = Product Flavors + Build Types!

 

Build Types vs Product Flavors

Differences
  • Build Types are used for your development cycle (debug, release, qa, staging, etc), while Product Flavors are used for your distribution strategy (free vs paid, rebranding, etc)
  • minifyEnabled property can be configured in Build Types, but NOT in Product Flavors
  • applicationIdSuffix property can be configured in Build Types, but NOT in Product Flavors
  • applicationId can be configured in Product Flavors, but NOT in Build Types
  • minSdkVersion,targetSdkVersion, versionCode, versionName can be configured in Product Flavors, but NOT in Build Types
Common
  • signingConfig property can be set in both
  • buildConfig property can be set in both (the ability to provide custom Java code)
  • you can set different dependencies (see example code here) inside dependencies{} block by:
    • flavors (<flavorName>Compile)
    • build type (<buildTypeName>Compile)
    • both flavor and build type combined (<flavorName><BuildTypeName>Compile).

 

Android @IntDef Annotation Example

Android has some helpful annotations in the support library so, in this post, I will show you an example of how to use @IntDef annotation. You can use this annotation (or @StringDef annotation) instead of Enum.

Steps

1. Add your constants

2. Add the @IntDef annotation and between ({ }) paranthesis, declare your constants

3. Add the @Retention annotation

RetentionPolicy.SOURCE means that the annotation is only available in the source code.

NOTE: If the @Retention annotation is not set, RetantionPolicy.CLASS will be used as default, which means that the annotation would be available in the source code and in the class, but not at runtime.

4. Add an annotated interface and give a name (the same you give a name for an Enum)

5. Add a variable which will be set with one of the Constants.

6. Add a setter and getter for the variable created above using annotation in order to force you to write one of the declared constants. The annotation should be the name you gave for the annotated interface at step 4.

Code Example

Using the above example, you should be forced to set another planet only by using  the NAME of one of the declared constants. You will get an error if you write the value of one of the constants like in the below image:

indef annotation

Android Set Horizontal Divider to a Vertical LinearLayout

If you need to use a “list” divider, but you need it on a vertical LinearLayout instead of a List you can do this by using some attributes on the LinearLayout. It’s not very straightforward as you maybe expected, but it’s not very difficult either. Before starting, you have to know the 2 major things this tutorial will teach you:

  • how to add divider to a VERTICAL LinearLayout
  • how to add padding at the bottom between divider and content

Summary

  • create 2 drawables: one for shape and one for the actual drawable
  • add 2 LinearLayout attributes android:showDividers="end"
    and android:divider="@drawable/divider_drawable" for each LinearLayout

Now, let’s begin!

  1. Create a new project (activity_main.xml will be automatically generated. You will have to edit it later with the code from this tutorial).
  2. In the app – src – main – res – drawable folder,  create a new drawable and name it divider_shape.xml. Inside this xml we will have to create a rectangle shape with a hight of 1dp for the divider.

 3. Again, in the drawable folder, create another drawable xml and name it divider_drawable.xml. Inside this xml we have to create a layer-list which will use the drawable_shape.xml as drawable. Here is the place where you can handle the padding for the divider. In this tutorial we use top and bottom paddings.

4. Now in activity_main.xml, add the following code:

As you can see the “list” divider we want to simulate, uses the “end” value in order to be displayed at the bottom of the each linearLayout.

NOTE: Don’t forget to add the orientation attribute as VERTICAL for every LinearLayout. Otherwise, the default is Horizontal, and the divider won’t be displayed.

Android LinearLayout Dividers