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

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 JitPack.io repository. The first step is to add the required repository into your build.gradle file

repositories {
    // ...
    maven { url "https://jitpack.io" }
}

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.

<com.hookedonplay.decoviewlib.DecoView
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    custom:dv_lineWidth="26dp"
    android:id="@+id/dynamicArcView"
    android:layout_width="match_parent"
    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(R.id.dynamicArcView);

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

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)
        .build();

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(R.id.textPercentage);
seriesItem.addArcSeriesItemListener(new SeriesItem.SeriesItemListener() {
    @Override
    public void onSeriesItemAnimationProgress(float percentComplete, float currentPosition) {
        float percentFilled = ((currentPosition - seriesItem.getMinValue()) / (seriesItem.getMaxValue() - seriesItem.getMinValue()));
        textPercentage.setText(String.format("%.0f%%", percentFilled * 100f));
    }

    @Override
    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)
        .setIndex(backIndex)
        .build());

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)
        .setIndex(series1Index)
        .setDelay(5000)
        .build());

decoView.addEvent(new DecoEvent.Builder(30f)
        .setIndex(series1Index)
        .setDelay(10000)
        .build());

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

License

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

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

References

DecoView on GitHub: https://github.com/bmarrdev/android-DecoView-charting

Faux Fit sample on GitHub: https://github.com/bmarrdev/fauxfit-decoview-sample

3 Comments

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:

lib/x86/
    libdatabase_sqlcipher.so
    libsqlcipher_android.so
    libstlport_shared.so

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:

https://androidbycode.wordpress.com/2015/06/30/android-ndk-version-code-scheme-for-publishing-apks-per-architecture/

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.

Conclusion

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

References

Multiple APK support in Android: 

http://developer.android.com/google/play/publishing/multiple-apks.html

Android apk-splits user-guide:

http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits

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

https://software.intel.com/en-us/android/articles/how-to-develop-and-evaluate-64-bit-android-apps-on-intel-x86-platforms

1 Comment

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="http://schemas.android.com/apk/res/android"
      package="com.hookedonplay.androidbycode.mynewapp"
      android:versionCode="1"
      android:versionName="1.0">
      ...
</manifest>

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: 'com.android.application'
 
 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
            reset()
            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 =
                project.ext.versionCodes.get(output.getFilter(
                    com.android.build.OutputFile.ABI), 0) * 10000000 + android.defaultConfig.versionCode
        }
    }
 
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
 }
 
 dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
 }

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
            reset()
            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 =
                project.ext.versionCodes.get(output.getFilter(
                    com.android.build.OutputFile.ABI), 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:

versionCode='20000101'
...
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'
sdkVersion:'15'
targetSdkVersion:'21'
application-label:'Android Database Encryption'
application-icon-160:'res/mipmap-mdpi-v4/ic_launcher.png'
application-icon-240:'res/mipmap-hdpi-v4/ic_launcher.png'
application-icon-320:'res/mipmap-xhdpi-v4/ic_launcher.png'
application-icon-480:'res/mipmap-xxhdpi-v4/ic_launcher.png'
application-icon-640:'res/mipmap-xxxhdpi-v4/ic_launcher.png'
application: label='Android Database Encryption' icon='res/mipmap-mdpi-v4/ic_launcher.png'
application-debuggable
uses-feature: name='android.hardware.touchscreen'
uses-implied-feature: name='android.hardware.touchscreen' reason='default feature for all apps'
main
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.

References

Multiple APK support in Android

http://developer.android.com/google/play/publishing/multiple-apks.html

Android apk-splits user-guide

http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits

Amazon Device Targeting

https://developer.amazon.com/public/solutions/devices/fire-tv/docs/using-device-targeting

4 Comments

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 'com.android.support:design:22.2.1'

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:

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"        
    android:layout_height="match_parent"        
    android:layout_alignParentBottom="true"        
    android:layout_centerHorizontal="true"        
    android:id="@+id/snackbarPosition">
</android.support.design.widget.CoordinatorLayout>

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:

import android.support.design.widget.Snackbar;

public class MainActivity extends AppCompatActivity...

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

final View coordinatorLayoutView = findViewById(R.id.snackbarPosition);

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

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(android.graphics.Typeface.BOLD), 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:

-dontwarn android.support.design.**
-keep class android.support.design.** { *; }
-keep interface android.support.design.** { *; }
-keep public class android.support.design.R$* { *; }

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.

References

Snackbar specification:

http://www.google.com/design/spec/components/snackbars-toasts.html

Snackbar class:

https://developer.android.com/reference/android/support/design/widget/Snackbar.html

CoordinatorLayout class:

http://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.html

5 Comments

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:

http://tools.android.com/tech-docs/unit-testing-support

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

https://github.com/evant/android-studio-unit-test-plugin

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: ‘com.android.library’ instead of apply plugin: ‘com.android.application’.

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.

References

AAR File Format

http://tools.android.com/tech-docs/new-build-system/aar-format

Manifest merging user guide

http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger

9 Comments

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:

/home/username/.AndroidStudio/config/codestyles

On Windows:

C:\Users\JohnDoe\.AndroidStudio\config\codestyles

On MacOS:

~/Library/Preferences/.AndroidStudio/config/codestyles

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