Category Archives: Android Studio

Creating a Google Fit style circular animated view

Google’s health tracking platform, Google Fit, provides data visualization using a circular view to display feedback to users. This circular view is smoothly animated and presents a variety of data about the current status of the users fitness goals.

This article takes you through the steps required to build the chart shown in the clip below and add it into your Android App.


DecoView was designed as a fully configurable library for animating arc based charts. Continue reading this article to find out how to reproduce the Google Fit user experience in your app with DecoView. DecoView is open source and available on GitHub.

DecoView is subclassed from the Android View class. Just like other View subclasses, such as TextView and ImageView, it can be added and configured from your layout XML then controlled in your Activity code.

Faux Fit: DecoView sample project

The source code is available from the Faux Fit project on GitHub.

Step 1: Include the DecoView library in your project

DecoView is hosted on the repository. The first step is to add the required repository into your build.gradle file

repositories {
    // ...
    maven { url "" }

Next, add the gradle dependency for DecoView

dependencies {
    compile 'com.github.bmarrdev:android-DecoView-charting:v0.9.3'

Step 2: Add a DecoView to your XML layout

Open your Activity layout file and add a DecoView by inserting the following declaration.

    android:layout_height="match_parent" />

Note the use of the custom:dv_lineWidth attribute to set the default width of the arcs. You can always override this value for any of the data series you add later.

Step 3: Configure the DecoView by adding a data series

After adding a DecoView to your XML layout you will not see anything in your app unless you add one or more data series.

The first data series we are adding is going to be used as a background track to show the path where the other data series will follow as they are animated. To add this background arc add the following code to your Activity source file. Note how we set the color to a very light gray (hex code #FFE2E2E2).

DecoView decoView = (DecoView) findViewById(;

SeriesItem seriesItem = new SeriesItem.Builder(Color.parseColor("#FFE2E2E2"))
    .setRange(0, 50, 0)

int backIndex = decoView.addSeries(seriesItem);

Tip: While we are setting the color to be fully opaque here, DecoView supports alpha transparency in all functions that take a Color value

Next you need to add an actual data series in your Activity code. This may be used to visualize a data value such as the number of calories the user has burnt or number of minutes spent walking.

final SeriesItem seriesItem = new SeriesItem.Builder(Color.parseColor("#FFFF8800"))
        .setRange(0, 50, 0)

int series1Index = decoView.addSeries(seriesItem);

Step 4: Add a listener to monitor value changes

First you need to add a TextView to your XML layout. Then you can attach a new SeriesItem.SeriesItemListener() that will be called whenever the current position of the data series is changed. If you issue an event to move the series this callback will be called multiple times for the one event.

We will calculate the percentage the data series is filled and update our TextView with this percentage value.

final TextView textPercentage = (TextView) findViewById(;
seriesItem.addArcSeriesItemListener(new SeriesItem.SeriesItemListener() {
    public void onSeriesItemAnimationProgress(float percentComplete, float currentPosition) {
        float percentFilled = ((currentPosition - seriesItem.getMinValue()) / (seriesItem.getMaxValue() - seriesItem.getMinValue()));
        textPercentage.setText(String.format("%.0f%%", percentFilled * 100f));

    public void onSeriesItemDisplayProgress(float percentComplete) {


Tip: When implementing the DecoView progress listeners be aware that they will be called many times for each event. Avoid heavy processing in the listener to prevent jank, and avoid new allocations to prevent memory churn.

Step 5: Create timed events to animate the DecoView data series

We need to set the background track to be at the maximum value, this enables it to be drawn as a complete circle. We could have set this as the initial position for the track when it was constructed, however we want to see an animation filling the background track so we use an event to reveal the background track. While it is possible to fully customize this animation we will keep it simple and just set the minimum information required; that is the position to move the value and the index of the data series to execute the event.

decoView.addEvent(new DecoEvent.Builder(50)

It is possible to animate the DecoView at any time in response to a user action, such as pressing a button or using a swipe gesture. This is what we have just created with an event to be executed immediately.

It is also possible to delay events to happen at a future time. We will construct then event using setDelay(5000) to delay the animation of the main data series. We need to set the current value between the minimum (0) and maximum (50) values specified on creation of the data series.

Here is how to move the current position to 16.3f (out of 50) and delay the event to start after 5 seconds. After 10 seconds we will then move the position to 30.

decoView.addEvent(new DecoEvent.Builder(16.3f)

decoView.addEvent(new DecoEvent.Builder(30f)

Note: All time values in DecoView are specified in Milliseconds, 5000ms == 5 seconds

Step 6. Run your app to test your DecoView

You should now have the DecoView animating and looking similar to the image below when you run your app.

DecoView basic sample

Step 7. Add more data series, custom reveal animations and event listeners

To finish off building the Faux Fit sample you need to:

  • Add two more data series. This can be done using the same method used to create the existing series
  • Add custom reveal and hide effects
  • Create a animation loop by adding a listener to recreate all the events when the last one has completed

The code required to complete these final tasks can be viewed in the Faux Fit Activity found within the GitHub project. You should end up with an Activity something like the snapshot below.

Faux Fit DecoView Sample


Copyright 2015 Brent Marriott

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
See the License for the specific language governing permissions and
limitations under the License.


DecoView on GitHub:

Faux Fit sample on GitHub:



Filed under Android Libraries, Android Studio, Animation, Charting

Android NDK: A guide to deploying apps with native libraries

Libraries written in C++ and C have long been supported in Android through the Native Development Kit (NDK). Even if you haven’t directly built native code libraries, you may have included pre-built native libraries; they can be identified by the .so file extension. The main drivers for Android developers to include native libraries are:

  • Porting existing code to Android
  • Building a library of functionality
  • Increasing performance for intensive algorithms

Note: The process of building a native library is not covered in this article. Head to the Android NDK site for the tools and information you need to build native libraries for Android.

Android NDK

Most apps won’t benefit from native libraries and most apps should be developed exclusively using Java, which is executed in a virtual machine on the device using the Java ‘Write once, run anywhere’ philosophy. Including native libraries in your app results in you losing the write once, run anywhere benefit. Figure 1 shows a summary of the pros and cons of using native libraries:

Figure 1: Pros and cons of using a native library

Figure 1: Pros and cons of using a native library

Android Architectures and the Application Binary Interface (ABI)

Different Android devices use different CPU architectures, which in turn support different instruction sets. An ABI is different for each combination of CPU and instruction set. If you build with native code you need to compile that native code for each ABI that your app supports.

ABIs supported by Android

Android supports architectures from ARM, Intel and MIPS technologies, each in 32 bit and 64 bit flavors. In figure 2, below, you can see each ABI supported along with example devices.

Figure 1: Android ABI support

Figure 2: Android ABI support

Shared native library example

In this article I will use the SQLCipher project as an example use case for native libraries. SQLCipher is a great example of where using native libraries in Android is a necessity, here’s why:

  1. Performance benefits: SQLCipher has to decrypt/encrypt data, which requires very intensive processing
  2. Ease of reuse: The SQLCipher library was already developed in C/C++, using a native library makes is easier than rewriting and maintaining the library in different languages for different platforms

Performance testing

Building a shared native library can provide significant performance increases compared with implementing the same algorithm in Java. During some basic testing to compare some similar algorithms in native code compared to Java, I found the result ranged from double to a 20 times performance increase, however it should be noted these algorithms were heavy image manipulation processing. On less intensive use cases there will be little, if any, performance benefit.

Native library performance benefits

Figure 3: Native library performance benefits

APK size increase with native libraries

The table in Figure 4 shows the effect on the file size of an Android APK that include the .so libraries for SQLCipher. The universal APK in the table is built with libraries for all the tested ABIs.

Native library size increase table

Figure 4: APK size effect of including SQLCipher native library

For more information take a look at how to set your build.gradle file to build APKs that target different ABIs.

64 bit native libraries

When including native libraries you have to make a decision if you are going to ship with native libraries specifically targeting the 64 bit ABIs. Up until the start of 2015 this was an easy decision as 64 bit devices were only just hitting the market.

Note: It is not mandatory to build 64 bit libraries to support 64 bit Android devices. All 64 bit ABIs are backward compatible to support native libraries built for the equivalent 32 bit ABI. This applies to ARM as well as Intel and MIPS devices.

During 2015 sales of 64 bit Android devices could overtake those of 32 bit devices in some markets. If you provide native libraries specifically for 64 bit devices you should see a small performance increase with these new devices. Intel® have done some tests on Android performance using 64 bit compared to 32 bit and found performance is generally increased by 5-10%[1].

In summary, if you include 64 bit native libraries in you app:

  • You will still need to include 32 bit native libraries
  • You will not support any more devices than if you only include 32 bit libraries
  • You may see a small increase in performance for 64 bit devices[1]
  • You will increase the size of your APK (if building one APK with all native libraries)

Play Store Device support for different ABIs

While I have not been able to source official figures for sales figures of devices running each architecture, the breakdown is pretty clear through casual observation. ARM architectures dominate the Android device marketplace. There is a small percentage of x86 devices and virtually no MIPS devices.

When uploading an app to the Play Store feedback is shown with regards to the number of devices that are able to run your APK. Here is an example of the results:

Native Play Store device support

Figure 5: Play store reported supported devices

Notice in the table shown in Figure 5 that uploading an APK with armeabi native code will target 12 more devices than uploading an APK containing armeabi-v7a native code. The reason for this is that all devices running the armeabi-v7a are also able to execute the armeabi native code.

Multiple APK support on Google Play

It is possible to upload separate APKs to the play store for each ABI you are targeting. The best place to learn about this is by reading the Android documentation about Multiple APK support.
It should be noted that generally using multiple APKs to target different device configurations is discouraged. Here is what the official documentation has to say:

Note: You should generally use multiple APKs to support different device configurations only when your APK is too large (greater than 50MB) due to the alternative resources needed for different device configurations. Using a single APK to support different configurations is always the best practice, because it makes the path for application updates simple and clear for users (and also makes your life simpler by avoiding development and publishing complexity).

Verifying native libraries included in APK

It is possible to visually inspect the contents of any APK; remember that an APK is just a standard zip archive, so opening this archive you should find your native libraries in the folders for the ABIs you are targeting. For example, if you are building an APK that includes the SQLCipher native libraries for the x86 ABI, the file structure within the APK will look like:


Uploading multiple APKs to the Developer Console

In the Google Play developer console you can set your app to have multiple APKs that target different devices while all being part of the one application. This means that all download counts and reviews for the different APKs still apply to the one listing in the Google Play store.

There are some rules the must be followed in order to have ABI specific APKs active for the same app. The developer documentation describes some of these rules as:

  • All APKs you publish for the same application must have the same package name and be signed with the same certificate key.
  • Each APK must have a different version code, specified by the android:versionCode attribute.
  • Each APK must not exactly match the configuration support of another APK.

The image below shows the Google Play website for the Android Maps app. Note how the Size for the app is listed as Varies with device. This is as a result of uploading multiple APKs for the one application.

Example of Play Store variation per device

Figure 7: Play store entry for multiple APK app

Setting the versionCode

If you decide you need to deliver multiple APKs for the one app you will need to implement a version scheme for each APK. In a previous blog I have suggested extending a scheme suggested in the Android documentation, as shown below.

versionCode format

Figure 6: Android versionCode suggested format reference

Read more about this version scheme and how to automate the generation of different versionCodes for different target ABIs in this article:

Uploading your APKs

The Google Play Developer Console allows you to upload multiple APKs for the same application through the Advanced Mode in the APK management section.

  1. Go to the Developer Console
  2. Select the APK management menu
  3. Select Switch to Advanced Mode button
  4. Select Upload new APK button for each APK that targets different ABI

Your developer console should look similar to Figure 8, below, once you have uploaded multiple APKs.

Developer Console multiple native versions

Figure 8: Developer console uploading multiple APKs

You will notice in figure 8 the warning message:

Some devices are eligible to run multiple APKs. In such a scenario, the device will receive the APK with the higher version code.

You may think each version uploaded is targeting a different ABI Native platform, so why is this message being shown? Remember that some ABIs can support code targeting more than one different ABI. In this example the armeabi-v7a devices also are backwards compatible to support armeabi, but the reverse is not true.


The most pertinent points that must be considered when deciding to deploy your app with native libraries are:

  • Don’t use native libraries if you don’t need to
  • Consider which ABIs you need to target
  • Consider if specific 64 bit libraries to maximize performance are worthwhile
  • Avoid producing multiple APKs for one app unless APK size is an issue


Multiple APK support in Android:

Android apk-splits user-guide:

[1]How to Develop and Evaluate 64-bit Android Apps on Intel® x86 Platforms


Filed under Android NDK, Android Studio, Gradle

Android NDK: Version code scheme for publishing APKs per architecture

Distributing native libraries with your APK adds complexity to your build process and can bloat the size of your APK. You have to include a specific build of native libraries for every architecture you want to target, or to be more technically correct every ABI (Application Binary Interface) you are targeting. Different Android devices use different CPU’s architecture, which have support for different instruction sets. An ABI is different for each combination of CPU and the instruction set supported.

The recommended distribution method for your APK is to distribute one APK that contains all the static native libraries for all the ABIs being targeted. This article does not follow that path and discusses how to build, upload and manage separate APKs for your app. Each APK will include only the native libraries for a specific ABI. The following assumptions are made:

  • You are using Android Studio 1.2+ and using the Android gradle plugin build system
  • You are distributing your app through the Google Play store
  • You already have static native libraries (.so) built with the Android NDK
  • You are concerned about APK bloat caused by these native libraries

Universal APK or Multiple APKs

You need to make an educated and considered decision about if you distribute one APK that includes all native libraries or multiple APKs. The advantage of one universal APK is that it is simple to deploy and maintain your app, the disadvantage is that you potentially could have a substantial increase in APK size. I have previously described how to use SQLCipher in an Android app which discussed this tradeoff. Figure 1, below, shows the impact on size when shipping SQLCipher native libraries in a basic APK.

Figure 1: Size increase when including SQLCipher

Figure 1: Size increase when including SQLCipher

Play Store requirement for unique versionCode per ABI

The only way for a developer to distribute an app, with different APKs, to users on different devices is to have a unique versionCode and to ensure each APK is targeting different devices. The versionCode needs to be unique as it is possible that a users device is compatible with more than one APK, when this happens they will receive the version with the highest versionCode.

When I mention the version I am not referring to the version that is visible to the user, which is specified as the versionName, I am talking about the internal version which is a numerical versionCode that indicates an ascending order of releases. The snippet from a build.grade script below shows the default versionCode and versionName that Android Studio will apply to a new project.

defaultConfig {
 applicationId "com.hookedonplay.androidbycode.mynewapp"
 minSdkVersion 15
 targetSdkVersion 21
 versionCode 1
 versionName "1.0"

It is possible that you are maintaining existing apps which only specify the version in the AndroidManifest.xml. While this works well for static version information we need to use the new Android Gradle build system to be able to dynamically generate version information. Here is an example of version information added directly into the AndroidManifest.xml.

<manifest xmlns:android=""

Format for individual versionCodes per ABI

Each ABI needs to have an unique versionCode before it can be uploaded to the play store. We are going alter the build.gradle file to automatically generate a unique version number for each ABI. Assuming we want to build our app with versionCode 101, Our aim is to produce the following results:

ABI versionCode table

Figure 2: Example versionCode values for each ABI

The order of the ABI numbers are important as is the length of the 8 digit versionCode.

The order is based on way the Play store works with multiple APKs. Remember, if a users device is compatible with more than one APK for an application the device will receive the version with the highest version code. This is why an armeabi build will be given a prefix of 1 as this build will also be able to run a armeabi-v7a device (2) and in some cases a x86 device (8) due to a proprietary ARM translation layer called libhoudini.

The versionCode we are going to generate is 8 digits long to cater for multiple APKs that differ not only by target ABI, but also different Android SDK versions and screen sizes. An example of how to incorporate all these details into the 8 digit versionCode is shown in Figure 3 below. This is an extension of a numbering scheme suggested in the Android developer documentation where we prefix the number with the ABI id value that was listed in Figure 2.

versionCode format

Figure 3: Android versionCode suggested format reference

You should be aware that this is only a suggested method for generating version information. It is not mandatory and it can be tailored to me your needs. For example, if you know that you are not going to distribute different APKs based on Android SDK API level then you could drop those two digits from the version.

Automating unique versionCode generation

Before continuing and changing your versionCode naming convention you need to understand the following:

If you are distributing one APK containing all flavors of native libraries then you do not need to worry about implementing the following version scheme.

To automate the version process we need to customize the build process. The build.gradle script for your app is where you can configure the build to produce a separate APK for each ABI type and also set the versionCode to conform with the desired 8 digit format discussed earlier.

Here is an example of a complete build.gradle that will achieve this:

apply plugin: ''
 android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"
    defaultConfig {
        applicationId "com.hookedonplay.androidbycode.androiddatabaseencryption"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 101
        versionName "1.0"
    splits {
        abi {
            enable true
            include 'x86', 'armeabi', 'armeabi-v7a'
            universalApk true
    project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]
    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.versionCodeOverride =
          , 0) * 10000000 + android.defaultConfig.versionCode
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
 dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile ''

Building separate APK files

The splits mechanism for the Android Gradle Plugin allows you to generate multiple files as shown by the example below. You can include only the ABI types you want to build and it is also possible to build an APK that includes all possible native libraries through the command universalApk true.

splits {
        abi {
            enable true
            include 'x86', 'armeabi', 'armeabi-v7a'
            universalApk true

Generate versionCode per APK

The section of the build script that sets the versionCode of each APK to a unique number is shown in the code snippet below. Note the project.ext.versionCodes which sets the first digit of the versionCode when multiplied by 10000000 we generate the 8 digit number we require. Finally the initial versionCode of the app, accessed with android.defaultConfig.versionCode, is added to complete the full numerical version for each APK.

project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]
android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.versionCodeOverride =
          , 0) * 10000000 + android.defaultConfig.versionCode

Verify the versionCode included in each APK

The Android Asset Packaging Tool (aapt) is part of the Android build tools and is required to build APK files. You can also use it to verify the contents of the APK files you have generated.

You will find the aapt executable in your latest version of the build tools, for example ..\sdk\build-tools\22.0.1

Execute the following command on each of the APKs you have produced:

 aapt dump badging AndroidApp.apk

You will find a wealth of information about the APK but the following items in the output will be of most interest:

native-code: 'armeabi-v7a'

Below is a more detailed, but still trimmed sample output from the aapt badging request:

package: name='com.hookedonplay.androidbycode.androiddatabaseencryption' 
versionCode='2000101' versionName='1.0' platformBuildVersionName='5.0.1-1624448'
application-label:'Android Database Encryption'
application: label='Android Database Encryption' icon='res/mipmap-mdpi-v4/ic_launcher.png'
uses-feature: name='android.hardware.touchscreen'
uses-implied-feature: name='android.hardware.touchscreen' reason='default feature for all apps'
supports-screens: 'small' 'normal' 'large' 'xlarge'
supports-any-density: 'true'
locales: '--_--' 'ca' 'da' 'fa' 'ja' 'nb' 'de' 'af' 'bg' 'th' 'fi' 'hi' 'vi' 'sk' 'uk' 'el' 'nl' 'pl' 'sl' 'tl' 'am' 'in' 'ko' 'ro' 'ar' 'fr' 'hr' 'sr' 'tr' 'cs' 'es' 'it' 'lt' 'pt' 'hu' 'ru' 'zu' 'lv' 'sv' 'iw' 'sw' 'fr-CA' 'lo-LA' 'en-GB' 'bn-BD' 'et-EE' 'ka-GE' 'ky-KG' 'km-KH' 'zh-HK' 'si-LK' 'mk-MK' 'ur-PK' 'hy-AM' 'my-MM' 'zh-CN' 'ta-IN' 'te-IN' 'ml-IN' 'en-IN' 'kn-IN' 'mr-IN' 'mn-MN' 'ne-NP' 'gl-ES' 'eu-ES' 'is-IS' 'es-US' 'pt-PT' 'zh-TW' 'ms-MY' 'kk-KZ' 'uz-UZ'
densities: '160' '240' '320' '480' '640'
native-code: 'armeabi-v7a'

This same dump can be also used to verify other attributes of your APK, such as the build SDK version, locales and supported screen densities.

You will also be able to verify the targeted ABI and versionCode once you upload to the Play Store via the developer console.

Distribution of multiple APKs via alternative app stores

This article has assumed that you are distributing your app through the Google Play Store. It may be possible that you are using multiple distribution methods, such as promoting your app on the Amazon Appstore. According to the documentation the same version methodology will work for the multiple APK support within the Amazon Appstore. There are also a number of smaller app marketplaces that may automatically add your app. Each of these app store may or may not handle multiple APKs correctly which may result in some users downloading an APK that is incompatible with their device.


Multiple APK support in Android

Android apk-splits user-guide

Amazon Device Targeting


Filed under Android NDK, Android Studio, Automation, Google Play, Gradle

Material Design Snackbar using the design support library

A Snackbar is a lightweight material design method for providing feedback to a user, while optionally providing an action to the user. They are displayed on the screen until a specified interval has passed, the user swipes to dismiss them, or when the user interacts with another part of the screen. Think of it as a modern take on the Android Toast.

This week at Google I/O 2015 the Android Design Support Library was released including a Snackbar implementation. Before now implementing and following the material guidelines for a Snackbar was left to the developer. A few third party libraries were released to make developers lives easier, but now official support for Snackbar has been introduced to make it easier than ever to add a Snackbar to your Android app.

Support for Snackbar pre-lollipop

While the Snackbar concept was introduced with the material design guidelines, the newly released Android Design Support Library works with devices right back to Android 2.1 (API 7). That is over 99% of active Android devices.

Material design specification for Snackbars

Many of the design rules for Snackbars are automatically enforced by the new support library. For example, if you provide lower case text for the action button it will automatically be displayed in upper case. However you still should brush up on the exact guidelines to know the best practices and what you can and can not do with a Snackbar. Take a look at the specification for full details.

A summary of the guidelines are:

  • Content: Keep text short
  • Icons: Do not add icons
  • Core functionality: Do not place core app functionality into a Snackbar
  • Multiple Actions: Use a dialog if you have multiple actions
  • Input: Snackbar does not block input, use a dialog for this
  • FAB: Don’t block the floating action button (FAB)
  • Consecutive: Only one can be displayed on the screen at any time
  • Single-line height: 48dp
  • Multi-line height: 80dp
  • Font: Roboto Regular 14sp
  • Action button: Roboto Medium 14sp, all-caps text
  • Default background fill: #323232 100%
  • Width on Tablets: Minimum 288dp, maximum 568dp

Adding a Snackbar to your app

Firstly you will need to add the Android Design Support Library dependency to your gradle build script:

compile ''

Next, you need to add a CoordinatorLayout to your xml layout. More details about what new features this new layout class bring are included later in this blog. Here is one that will position itself centered at the bottom of the screen:


In your AppCompatActivity class you need to configure the Snackbar object using the Builder design pattern. The most useful functions will be to create the Snackbar with make(), optionally set an action that the user can perform using setAction(), and finally to display the Snackbar to the user, show().

Snackbar will only work in Activities that are AppCompatActivity. If your activity extends a standard Activity or ActionBarActivity then you will need to either change your base class or use a third party implementation of a Snackbar.

Here is an example of a Snackbar that displays a message and allows an action to be executed by the user:


public class MainActivity extends AppCompatActivity...

final View.OnClickListener clickListener = new View.OnClickListener() {
    public void onClick(View v) {

final View coordinatorLayoutView = findViewById(;

    .make(coordinatorLayoutView, R.string.snackbar_text, Snackbar.LENGTH_LONG)
    .setAction(R.string.snackbar_action_undo, clickListener)

The result should be a Snackbar displayed on the device as shown in the image below. Note how the Snackbar in this image conforms to the specification. The text is kept short and the action text is all upper case. It is displayed on a tablet, so you will see rounded corners of 2dp and that a minimum width is enforced.

Snackbar displayed on tablet

Snackbar displayed on pre-lollipop tablet

Processing the Action button

The Snackbar action button should present an action related to the information being presented to the user. The most common type of actions are UNDO and RETRY.

Remember in the Material Design Snackbar specification that you can only show one action on a Snackbar, and that action must be short text composed entirely of uppercase text, no icons.

In the previous Snackbar example you can see that creating a View.OnClickListener() and adding it with an action is quite simple. The only work left is how you handle a click on the action button. Let’s take a look at an example, it is one of the most common use cases for a Snackbar. You have a list of items that are loaded from a database. With a swipe of the finger the user removes an item from the list and you display a Snackbar to confirm to the user that the item has been deleted and provide a action button to UNDO the delete and restore the item.

There may be a temptation to think that the easiest solution here is to remove the item from the list and wait until the Snackbar has completed being displayed and then do the actual delete from the database. If the user has hit the UNDO action button then add the item back into the list and don’t do the delete from the database.

The Snackbar implementation in Android does not encourage this type of implementation and in fact it doesn’t provide a callback to signal when the Snackbar view is no longer visible. The design pattern that Android wants you to follow for the example I have given is when the item is swiped from the display the item should be removed from the database immediately. You should keep the data needed to re-insert this item in the case that the user selects the UNDO action.

Positioning of the Snackbar

The Material Design specification of a Snackbar only stipulates that it is shown at the bottom of the screen. The example images in the specification show the Snackbar being horizontally centered, however the default position of the Snackbar in the Android design support library is the bottom left of the device if you do not use a CoordinatorLayout (see below). It is only possible to control the position of the Snackbar if you are using a CoordinatorLayout.

On smaller screen devices the Snackbar will take up the entire width of the screen, while on larger tablets sized screens the Snackbar will hit the maximum allowed width and not take up the entire width of the device.

Introducing CoordinatorLayout

When using many of the new elements introduced in the support library you will need to get to know the CoordinatorLayout.

CoordinatorLayout is a ViewGroup derived component that allows you to specify behaviors for child views to control how they interact with one another. If you recall one of the design rules for Snackbars was that they should not block the floating action button (FAB). With the newly released FloatingActionButton class blocking of the button is prevented by controlling the behaviors of the child views in the CoordinatorLayout.

By using a CoordinatorLayout you are also able to add padding or margins in order to move the Snackbar display position from the bottom of the screen.

Swipe to dismiss

Swipe to dismiss functionality is baked into the new Snackbar class when used in conjunction with a CoordinatorLayout. If you are finding that swiping on your Snackbar has no effect then check the type of View you are passing to the Snackbar.make() function. You don’t have to pass the CoordinatorLayout directly, passing a child view of a CoordinatorLayout is sufficient.

Duration of the Snackbar display

The Snackbar is not designed to be displayed indefinitely, but you are able to set the duration it is displayed before it is once again animated to hide it from the interface.

There are two standard lengths Snackbar.LENGTH_LONG, which is currently 2750 ms and Snackbar.LENGTH_SHORT which is currently 1500ms. It is possible to pass a custom display length in ms to the Snackbar.setDuration(int) function, and with the 22.2.1 release Snackbar.LENGTH_INDEFINITE is also a valid argument.

Adding bold text to your Snackbar message

You can add formatting such as bold to your Snackbar text using the Android Html class. The Html.fromHtml() function will generate a Spanned object that can be passed to the Snackbar.make() function:

Snackbar.make(view, Html.fromHtml("Add <b>bold</b> to Snackbar text"), Snackbar.LENGTH_LONG).show();

Adding multicolored text to your Snackbar message

You are able to add color combinations to the Snackbar text using the SpannableStringBuilder class. Using this class is also an alternative method for applying formatting such as bold to the Snackbar text.

Here is an example:

SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Add ");
int boldStart = snackbarText.length();
snackbarText.append("bold color");
snackbarText.setSpan(new ForegroundColorSpan(0xFFFF0000), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
snackbarText.setSpan(new StyleSpan(, boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
snackbarText.append(" to Snackbar text");

Snackbar.make(view, snackbarText, Snackbar.LENGTH_LONG).show();
Snackbar colored text

Snackbar colored text

Using the Design Support Library with ProGuard

In the initial release of the Design Support Library (22.2.0) you may hit issues with ProGuard. At this stage I would recommend you exclude all the design support library from the effects of ProGuard. This will cause some unnecessary bloat and once an update of the design support library is released you should revisit this issue and look for some official documentation. For now you can add the following to your ProGuard rules:

-keep class** { *; }
-keep interface** { *; }
-keep public class$* { *; }

Bigger is not always better

In the case of a Snackbar minimizing your text length is vital. Be succinct when writing text on the Snackbar, especially the action text. While the text must contain enough information that the user understands the meaning, it can’t be so verbose that layout problems are caused on small devices.

Ensure you test the layout of the text on a range of devices. While your text may look good on your shiny new 10″ tablet, spare a thought for those on the smallest devices your app is targeting.

If it is a possibility that you may localize your app in the future then think about the size of the text now to prevent more work down the track. Consider doing some pseudo-localization testing for your app, remembering that this text could possibly be twice as long after being translated from your apps native language. I have previously blogged about how to test localization using pseudo-localization on Android.


Snackbar specification:

Snackbar class:

CoordinatorLayout class:


Filed under Android SDK, Android Studio, Material Design

Android Studio 1.1: Unit Testing on the local JVM

The Android Studio 1.1 update is still filtering onto developers machines. One important improvement is the addition of support for unit testing using the local JVM on your development machine. This feature is still experimental and must be enabled in the IDE settings.  You can read all about it on the official site:

This new feature means the most popular open source Android Studio plugin for gradle unit tests will now no longer be developed or maintained:

Leave a comment

Filed under Android Studio, Testing

Building an AAR Library in Android Studio

Purpose of AAR

Library reuse has long been available in Java based applications through Java Archive (.jar) files.  Android AAR files build upon this concept to allow you to package not only the source code but also the libraries self contained Android resources. The library can have its own manifest and resources and can also optionally provide assets, NDK built libraries, proguard configuration and even its own custom lint filters.  This is all bundled into a zip archive that can be published to a repository for your team (or the world!) to get easy access from a Gradle build.

AAR File Format

The AAR File format is simply a zip archive file with extension .aar. The archive contains:
  • /AndroidManifest.xml (mandatory)
  • /classes.jar (mandatory)
  • /res/ (mandatory)
  • /R.txt (mandatory)
  • /assets/ (optional)
  • /libs/*.jar (optional)
  • /jni/<abi>/*.so (optional)
  • /proguard.txt (optional)
  • /lint.jar (optional)

Creating an AAR library project

The good news is creating an AAR library is easy and Android Studio will do all the hard work for you.

Android Studio create library module

Figure 1: Create an Android Library

  1. Start by selecting New Module… from the File menu
  2. Select Android Library as the module to be created (see Figure 1)
  3. Step through the process of using a template for the creation of your library much like creating a new project

One key difference in the created library and an Android application will be the libraries Gradle build script includes apply plugin: ‘’ instead of apply plugin: ‘’.

When you build your project the AAR file will automatically be assembled and placed in these folders (Android Studio 1.0+)

| build
| outputs
      | aar
           | applib-debug.aar
           | applib-release.aar

Using AAR

You have a few choices as to how to include your AAR library in your project:

  • Publish to a external Maven repository
  • Publish to a local repository
  • Access from a local folder

While Gradle can be used to directly publish to repositories such as Maven Central, this article doesn’t cover publishing your AAR file to Maven repositories.

To include your AAR library as a dependency from a local folder:

1. Copy the AAR file into the libs folder in your project. Create this folder if it doesn’t exist. It needs to be located in the same folder as your application Gradle build file, not the top level project folder.

2. Declare the libs folder as a dependency repository in your application Gradle script.

repositories {
    flatDir {
        dirs 'libs'

The Gradle flatDir repository declaration allows you to declare a file system directory that is a repository for dependencies for the project. In the example above I am using the libs folder which needs to be located relative to the location of the build script. The name of this folder does not have to be libs and it is also possible to declare multiple fileDir folders in the one project.

3. Declare your AAR library as a dependency:

dependencies {
    compile(name:'yourlibraryname', ext:'aar')

Manifest Merging

Earlier in this article we noted that the AndroidManifest.xml is a compulsory item in an AAR library. When an app includes your AAR library the manifest must be merged with that of the app, as there will be only one manifest included in an APK.

Merging manifests can quickly get messy when multiple conflicting manifests are all merged. The android tools user guide to manifest mergers is the best resource available to explain all the ins and outs of how the merge will happen and how you can control the merge.

The most basic rule of the merge is the order of priorities given to different manifests. From most influential to least:

  1. Product flavors and build types specific manifest files.
  2. Main manifest file for the application.
  3. Library manifest files.

So you can see your Library manifest sits at the bottom of the pecking order.

Most of the time this merging will happen like magic, without the need for intervention. If issues arise in the manifest merge there are a couple of places to start looking in order to track down the issue. The first place to check is the final outputted manifest file. The next place to check is the manifest merge report (which is saved into the app\build\outputs\logs\ folder of your project). The format and contents of the logging in the merge report is explained here.


AAR File Format

Manifest merging user guide


Filed under Android SDK, Android Studio, Gradle

Applying the AOSP Coding Style in Android Studio

No matter if you are a one man operation, or a cog in a large team, coding with a consistent style makes life easier when it comes to maintenance, refactoring and reuse. Modern IDE’s are powerful and highly configurable, with Android Studio supporting configuration for Java, HTML, XML and your gradle files. The AOSP (Android Open Source Project) has a defined code style that does not differ too much from the Android Studio default, if you want to use the AOSP coding style in Android Studio take a look at the steps below.

Step 1: Download the style definitions

Grab the xml code styles definitions for the Intellij platform.  These can be downloaded from the AOSP source, or for easy access from a GitHub mirror.

Step 2: Add the definitions file to your Android codestyles folder

You need to move this file within your .AndroidStudio configuration folder on your machine.  The exact location will vary not only between operating systems, but also Android Studio versions.  These folders are valid for the latest Android Studio 1.0 and 1.1 versions.

On linux:


On Windows:


On MacOS:


Note that these folders are often hidden so be sure to enable displaying hidden files and folders.

Step 3: Apply the code style to your project

Restart Android Studio to allow the new code style to be found.

Open the Code Style settings in the IDE (File > Settings… > Code Style) and click the Manage… button.  A new entry AndroidStyle should be in the list of available code styles.  Select and click Copy to Project to apply it to the current project. Then apply the formatting by running the Reformat Code tool across your source.

You should also take note of some more rules that are enforced for AOSP contributions, even if you are not contributing to AOSP, they are rules that should be applied to any project.

Remember this is the style used in AOSP, there is nothing wrong with the default code style settings in Android Studio, what is important is that you ensure you and your team follow a consistent style.

Leave a comment

Filed under Android Studio

Goodbye launcher drawables, hello mipmaps!

(UPDATE 18th FEB:  Android Studio 1.1 has been released!)

The upcoming release of Android Studio 1.1 will largely be a bug fixing release. There is one change however that might catch your eye when creating a new project. Projects now create launcher icons in the mipmap resource folders instead of the drawable folders. I am sure we will hear a lot more about this with release of Android Studio 1.1 coming very soon.

Why use mipmaps for your launcher icons?

Using mipmaps for your launcher icon is described as best practice by the Android team. The advantage you get is that you can keep resources in the mipmap folders for all device densities and then strip out other resources from the drawable folders that are not relevant to the specific users device density.

Here is an example, say a user has a device that is classified as xxhdpi. The drawable resources in your apk for all other densities, such as xxxhdpi, are not required and can be stripped out. The launcher icon is different to other resources as it is possible that a higher resolution icon is displayed in the users launcher. If that higher resolution image has been stripped from your drawables folder, then a lower density icon will programmatically be up-scaled. This may cause an unattractive blurry icon.

You may not be producing multiple apk files with stripped out resources to minimize apk size yet. Therefore making the change to mipmaps for your launcher icon will currently not make any difference. That does not mean you should not do it. The best reason for using mipmaps folder is that the Android team want you to and describe it as best practice. They know what new features are in the pipeline for Android and who knows, but maybe they are planning to introduce a new feature where unused resources are automatically stripped for the user when they download apps.

History of launcher mipmaps in Android

The mipmaps resource folders in Android started appearing long before they were introduced to the wider Android development community to use, which started in Android Jelly Bean 4.3. Very little official information came from the Android team about why to use them. Around the time of the release of 4.3, Android framework developer @hackbod announced:

…if you are building different versions of your app for different densities, you should know about the “mipmap” resource directory.  This is exactly like “drawable” resources, except it does not participate in density stripping when creating the different apk targets.

Since that time if you have taken a close look at the apps produced out of Google you will notice that some apps were doing exactly that.  Shipping only the required density but including all densities in the mipmap folders for the launcher icons.

As time went on still there was not much noise out of the Android team about using launcher mipmaps, that was until Lollipop hit AOSP and the new Nexus devices hit the market.  The Android Developers blog posted about preparing your apps for the new Nexus 6 and 9.  This detailed a compelling reason you should use mipmap folders for your app icon and announced the shift of best practice to using mipmaps:

…Provide at least an xxxhdpi app icon because devices can display large app icons on the launcher. It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density. For example, an xxxhdpi app icon can be used on the launcher for an xxhdpi device.

Interestingly there is still no update in the Official Android documentation and it still mentions drawable folders being the place for your launcher icons.  I am sure that will change in the coming months as the update to Android Studio is the next step in the progression of the change.

Update May 2015: The Android developer documentation has now been updated to document the purpose of mipmaps.

Creating a new project using launcher mipmaps

Update to Android Studio 1.1, any new project will use the new structure when it is created.

Updating an existing project to use launcher mipmaps

If you have used the excellent tool Android Asset Studio to generate your launcher icons recently you will notice the mipmap change is now reflected in the structure of assets generated. Even if you normally generate your icons through another process this is a great place to start as it shows the format and structure you should be using.

Your assets need to go into a structure much like your previous launcher drawables.

    mipmap-mdpi/ic_launcher.png (48x48 pixels)
    mipmap-hdpi/ic_launcher.png (72x72)
    mipmap-xhdpi/ic_launcher.png (96x96)
    mipmap-xxhdpi/ic_launcher.png (144x144)
    mipmap-xxxhdpi/ic_launcher.png (192x192)

You will also need to change your AndroidManifest.xml to use mipmaps for the launcher.



Filed under Android 5.0, Android Studio, Image, Nexus

Static Code Analysis using FindBugs (Android Studio)

There are many techniques, procedures and tools that can contribute to the quality of the source code your team produces.  One of those techniques is static code analysis and if you are using Android Studio you are probably using at least one tool for this already, Android Lint.  Lint is an very high quality tool that will not only give your Java source code the once over, but also your XML files, including layouts. It has deep knowledge about Android development patterns and it evolves with each SDK release, it should be the first stop for static code analysis in Android.  Every developer should pay attention when Android Lint waves that little yellow flag at you.

No matter how good Android Lint is, it is always worthwhile having a second and third opinion from different tools.  FindBugs is not an alternative to Android Lint, but it can be used as a companion. It is an open source tool that performs static analysis of your Java bytecode to warn of potential bugs, defects, security and performance issues.  It knows nothing about Android and is not a panacea for poorly designed apps, but it can provide a little nudge in the direction of potential issues in your software. As with all tools in this space it will never have a 100% strike rate, but it does allow the developer to take another look and think twice about a piece of code.

When an issue arises you will get a warning that is placed into one of nine different buckets. They are:

  • Dodgy code
  • Malicious code vulnerability
  • Bad practice
  • Correctness
  • Internationalization
  • Security
  • Performance
  • Multi-threaded correctness
  • Experimental

Each of these can be disabled if not required and you can also configure the confidence level at which issues will be reported.

Using FindBugs in the Android Studio IDE

Android Studio is built from the IntelliJ Java IDE which allows it to use IntelliJ plugins.  This is how you can integrate FindBugs into your Android Studio environment.

To open the IDE plugins go to the settings page (File > Settings…), and find the Plugins menu.  From here you can browse plugin repositories and do a search for FindBugs, or you can download the FindBugs plugin and install it manually from file.  When searching for the plugin you may find references to the QA Plug plugin.  This is another plugin that includes FindBugs and another way to get access to FindBugs from within your IDE and as a bonus it also includes other code analysis tools such as CheckStyle and PMD.

Executing FindBugs Analysis

Your code must have been built before analysis as FindBugs operates on the generated bytecode.  You can start the FindBugs analysis from within Android Studio by going to the Analyze menu, selecting FindBugs and then selecting the scope of the analysis to perform.  If you are using FindBugs through the QA Plug, you can access it from the Tools menu.

Exclude filters for Android

On first run of FindBugs you may be quite disappointed with the results.  With the default confidence level and no filters set FindBugs will report many issues that are part of the automatically generated android code to support functionality such as accessing resources.  For example, you may get many warnings similar to the these:

The class name R$dimen doesn't start with an upper case letter
The class name R$drawable doesn't start with an upper case letter

Take a look at the FindBugs manual for the specification of the filter format and details how you can create an exclude filter. For a filter that stops the warnings from Android auto generated code use the following XML:

<?xml version="1.0" encoding="UTF-8"?>
        <!-- ignore all issues in resource generation -->
        <Class name="~.*\.R\$.*"/>
        <Class name="~.*\.Manifest\$.*"/>

Another issue you may hit are FindBugs warnings for JUnit tests. This can also be handled in the exclude filter file by adding the following:

<!-- ignore all bugs in test classes, except for those bugs specifically relating to JUnit tests -->
    <Class name="~.*\.*Test" />
    <!-- test classes are suffixed by 'Test' -->
        <Bug code="IJU" /> <!-- 'IJU' is the code for bugs related to JUnit test code -->

This filter can be added to your Gradle build file for the automated builds discussed later, but for manually executed analysis you can add the filter in Android Studio. Go to settings dialog (File > Settings…) and select FindBugs-IDEA. Here you can configure the plugin settings and add the exclude filter list from an XML file.


Run FindBugs again and you will have no one to blame except your team for the issues that are reported.

Automating FindBugs

Like other parts of the development process you can automate this static analysis. Gradle has support for the FindBugs plugin. To create a Gradle task you can add the following to the in your project:

apply plugin: 'findbugs'

task findbugs(type: FindBugs) {
    ignoreFailures = false
    effort = "default"
    reportLevel = "medium"
    excludeFilter = new File("${project.rootDir}/findbugs/findbugs-filter.xml")
    classes = files("${project.rootDir}/app/build/intermediates/classes")
    source = fileTree('src/main/java/')
    classpath = files()
    reports {
        xml.enabled = true
        html.enabled = true
        xml {
            destination "$project.buildDir/findbugs/findbugs-output.xml"
        html {
            destination "$project.buildDir/findbugs/findbugs-output.html"

Visit for more information about configuring FindBugs in Gradle.


If your team doesn’t enforce clean Android Lint builds for your projects then stop looking at other tools now.  It should be your first line of defence for code quality standards.  If your lint pane is boringly empty then maybe it is time for another tool to give its opinion.  This is not a must have tool for every Android developer, but it does have its value.  It may only need to pick up a lazy security flaw once to make the configuration and automation time worthwhile.


FindBugs home

FindBugs Intellij Plugin

Gradle FindBugs Plugin


Filed under Android SDK, Android Studio, Automation, Gradle, Performance, Security, Tools