Help! My custom font does not work on Android 5.0

Issue description

On Android Lollipop versions before 5.1 some custom fonts loaded using the API Typeface.createFromAsset() do not render using the correct font. This issue was fixed with the release of Android 5.1, but will still affect your users running Android Lollipop 5.0.x.

This should not cause a crash in your app, it will just cause your view to render using the default typeface rather than the custom font you have specified.

What causes the issue?

The cause of this issue is badly formed TTF font files. Minor issues in font files may be ignored or tolerated by most systems rendering the font, however the tolerance level in the early builds of Lollipop was not so high and some fonts fail to render causing the system to fall back to using the default font. It is similar to having a badly written audio file that will play in some media apps but is flagged as corrupted in others.

Is my app affected?

The first thing to check is if your app loads custom fonts. Take a look for any font files found in your Android assets/fonts folder. Then look for the code that is loading the font so you can see where in the apps UI the custom font is used. Loading a custom font from your apps Assets folder and setting it into a View is quite straight forward.

Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");

Having custom fonts doesn’t always mean your app will be affected by this issue however. The quickest way to check is to visually verify those custom fonts are being rendered correctly. Another check suggested by the Android team is to run your font through the Sanitiser for OpenType engine. To determine a potential issue look for this in the output:

WARNING at ots-read-only/src/ bad id_range_offset


The root cause of the problem is badly written font files, so it makes sense that the solution is to re-encode the offending font.

If you only have a couple of font files you would like to re-encode a great place to start is with an online converting tool such as Upload your dodgy font file and even if you select the same input and output font format (ie. TTF), the file will still be re-encoded and should now be able to be used in your app. This web service has successfully fixed all the non conforming fonts I have thrown at it.

However if that online tool did not help, or you have a huge repository of files you would like to re-encode you may like to use to convert your TTF to XML and then back to a TTF.

Be careful running any software that will re-encode your font files. As this process will be changing the file there may be side effects such as loss of quality. Also it is possible the tool you are using to re-encode the file will also produce non-compliant font files that fail in some environments.

Why did my Unit tests not catch this error?

If you have had to fix this error then you may be thinking to yourself, Why did my unit test not alert me to this issue? or How can I write a unit test to stop this issue next time?

Don’t be too hard on yourself; for all intents and purposes the code appears to function correctly without visually verifying the rendering. The typeface is loaded correctly and it can be set into a view without issue or complaint. Even after the view has been invalidated and rendered there is still no exceptions or warnings of an issue raised. The problem only becomes obvious on visual inspection of the View.


Android issue tracker for this issue:

Android Typeface documentation:

Leave a comment

Filed under Android 5.0, Android SDK, Testing

Using Battery Historian to tame your battery draining app

IMPORTANT: Battery Historian 2.0 has been released. This article includes instructions that relate to the initial version of Battery Historian.

Battery Historian is an open source python script released by Google to profile battery related events on your Android Device. It was conceived as part of Google’s Project Volta that also saw the introduction of the new JobScheduler API to give developers some tools to develop apps that are good citizens when it comes to battery consumption.

It is useful for developers to investigate the impact their app is having on battery life by displaying a time line of events where the state of the most battery hungry sensors and features of Android are graphed.

Some typical use cases for Battery Historian would be:

  • To show a wake lock is being acquired and released in the correct manner
  • To verify the GPS is being turned off when your app no longer requires it
  • To ensure your app isn’t constantly activating the mobile radio and preventing Android from entering a sleeping state


There are a few prerequisites that are required to use Battery Historian.

  • An Android device running Android 4.4 or later
  • Battery Historian script. Available from
  • ADB. You will need the Android Debug Bridge installed to issue commands to your Android device
  • Python 2.x. Battery Historian is actually just a python script that processes the information in a battery stats dump from your device and builds a document to graphically represent the data. The python script that is Battery Historian is written for Python 2.x, and as such is not compatible with the latest Python 3.x. versions.

Tip: Using the python convert script does not correctly upgrade the python source. You need to either run the script with Python 2.x or convert and debug the script manually.


Generating a Battery Historian chart

It is just a quick couple of steps to setup and generate the battery stats chart using Battery Historian. You need to clear the existing bugreport data in the device, then perform any operations on your app, download the new data to your computer and run it through the python script to produce a lovely colorful representation of what has happened on your device.

Step 1: Prerequisites

Ensure you have checked all the items listed in the prerequisites section.

Step 2: Reset battery stats data on your device

All existing battery stats data needs to be removed from your device before we try to capture the data while your app is being used. To reset existing data make the following command line call:

adb shell dumpsys batterystats --reset

Step 3: Disconnect your device from your computer

Step 4: Test your app

Perform all the steps you want to do to test your app while the battery stats monitoring is taking place. If you are not tracking a specific bug then you can just try to exercise the areas of your app that may be triggering and stopping battery intensive operations.

If you are tracking a specific bug you will need to understanding what is happening under the hood of your app and which calls to which APIs are happening.

Step 5: Reconnect your device to your computer

Step 6: Generate bugreport

To generate the bugreport data and download it to your device you need to issue the following ADB command:

adb bugreport > batterystats.txt

This may take a couple of minutes to generate as the data file produced can be quite large.

Step 7: Generate the Battery Historian report

To generate the battery historian report from the bugreport output execute the script

python batterystats.txt > batteryreport.html
Battery historian command line arguments

Battery historian command line arguments

If you execute this script using python 3.x you will see an error such as SyntaxError: Missing parentheses in call to ‘print’.

Generating this report may produce an out of memory error due to the bugreport captured being too large, if this happens return to step 2 and start again with a smaller duration of testing your app.

Interpreting the Battery Historian chart

Open the html report generated to view your data. You will see a report similar to the image below:

Battery historian chart

Battery historian sample chart

Take a look at the period of time when your app was running, it will be shown in the row labelled top. This shows the topmost app running at any given time. Follow the list of rows down to see what is happening at the time your app was visible and running on your Android device. You should see the state of the screen, wake locks, GPS, WiFi, mobile data and other battery hogging events.

Remember that all running services could be affecting these readings as this data is not just in the domain of your app. Also remember that it may be that your battery drain issues may be caused during the period when your app is no longer topmost. You need to have a deep understanding of your services, what they are doing, when they are doing it, and how they are initiated to correctly interpret these charts.

Fixing common battery drain issues

Knowing what the common battery drain issues are and how to fix them will go a long to helping you understand why your app is producing the results in your Battery Historian chart. This is a vast topic in itself but a couple of the more common scenarios are:

  • Explicit wake locks not being managed correctly. Don’t use explicit wake locks unless it is absolutely necessary. It is almost always not necessary to use them directly to keep the screen awake. As an alternative use LayoutParams.FLAG_KEEP_SCREEN_ON and remove this flag as soon as you no longer need the screen to remain on.
  • Executing battery draining non-urgent tasks at inopportune times. Tasks that can be deferred until the device is on WiFi and/or charge can now be delayed using the simple and powerful JobScheduler API in Android 5.0+.
  • Constant Polling of web services keeping the mobile radio alive. Take a look at a using SyncAdapter to reduce server polling or use inexact alarm schedules for tasks.
  • Third party libraries such as Mobile Advertising or Analytics SDKs. It is easy to add libraries to your app but you must give consideration to the effect that library has on battery performance. Any library that transfers data to and from the internet is going to come with some costs. If it is a poor quality library it could cause major battery drain. Be careful what you include and profiling using Battery Historian after adding that any library is a smart move.


Battery Historian is not quite the powerful, easy to use battery performance tuning panacea that was trumpeted as part of Project Volta. It has very little documentation and isn’t great tracking down events over large time periods, for example on repeating alarm events, or events that only happen under very specific circumstances. However it is a useful tool that can help track issues such as ensuring wake locks, GPS and other energy sapping functionality are being handled correctly.

Battery Historian is another tool to add to your arsenal, even if just to give you some piece of mind that your app is being kind to your user’s battery. The best bet is as always understanding the fundamentals for battery performance turning and ensuring you are not violating best practice. Finally, don’t forget about one of the other pillars of Project Volta, the JobScheduler API.

Take a look at the Google I/O session below for more information about Battery Historian and Project Volta.

Leave a comment

Filed under Performance

Android memory leak detection using leakcanary

leakcanaryThe good folk over at Square have a history of developing high quality open source Android libraries that make developers lives easier. Their latest project has just been announced; it is called leakcanary and as the name suggests it is a memory leak detection library for Android.

As usual from Square it is released as open source, simple to integrate and after some quick tests initial impressions are this is another winner.

Everything you need to know is included in the announcement on their blog and the readme on at the projects GitHub home.

Leave a comment

Filed under Tools

Pseudo-localization testing in Android

Developers localizing Android apps have to contend with the same considerations and issues as with software on any other platform. This article is not a step by step guide to the internationalization process, but simply touches on a couple of Android specific tips and tricks for developing a localized version of your app. Before proceeding you should be familiar with the Android Localization practices described in the official documentation. Localizing with Resources and Localization Checklist are the best place to start.

What is Pseudo-localization?

Pseudo-localization is a method to test the internationalization of text while maintaining readability. The purpose of this testing is to expose issues regarding length and flow of text, layout issues and logic issues.

If you are getting translations done externally it can be a time consuming and expensive process so localization testing should take place long before you get any kind of translator involved. By verifying everything is correct you will save time and iterations back and forth with translators.

Testing with Pseudo-localization on Android

You can test localization in your Android app by using a special developer locale that will lengthen string lengths and add accents to characters while still maintaining readability of the original strings. While documentation from Android regarding these new locales is basically non-existent at the moment, it appears you need to be running Android 5.0+ and have developer options enabled on the device to be able to access these special locales.

On your compatible Android device navigate to the device settings and select Language & Input > Language > English (XA)

locale_english_xa sample_locale_english_xa

After setting the language to English (XA) (above left image) text will start to appear in the pseudo-localization style (above right image). You will notice how the text is still legible in English, while being substantially longer than normal, in order to simulate more verbose languages.

As a broad generalization the Romance languages can be up to 30% longer than the equivalent English, while languages such as Chinese, Japanese and Hebrew languages may be significantly shorter.

Using your Android device after making this locale change you will note that most apps will not take on the same English (XA) appearance as is displayed in the example image. The reason for this is that pseudo locale support is designed simply for testing so must be explicitly enabled for each app individually in the build process. You can do this by setting pseudoLocalesEnabled to true in your gradle build script.

buildTypes {
    debug { 
        pseudoLocalesEnabled true 

Note: Support for pseudoLocalesEnabled was added to the Gradle plugin version 0.14.2.

Simplifying localization using XLIFF

XLIFF is a set of standards to aid in the translations of XML documents. You can use XLIFF to prevent text being translated and also to show formatted examples of string paramters. To use XLIFF in your Android string XML files you need to include the XLIFF 1.2 namespace:

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

This example shows how you can use XLIFF to help translators by flagging text not to be translated:

<string name="website_url">
    Take a look at our website <xliff:g id="blog_address"></xliff:g>

This example shows how to use XLIFF to display example arguments when using String formatting. It allows translators to understand what the data that will be injected into the string will look like.

<string name="city_longitude">
    Longitude: <xliff:g id="lon" example="37.8° S>%1$s</xliff:g>

Note: Support for XLIFF is available in Android Studio 0.3 and later

Supporting Right to Left layouts

Native Android support for right to left layouts (RTL) was introduced in API 17 (Android Jelly Bean 4.2). The Android Framework Team covered the introduction of this support in some detail.

Layout Mirroring is a term used to describe the ability of software to reorder the UI elements to match the right to left flow for that locale. It is possible to achieve a mirrored layout by manually creating a layout for RTL locales, but with API 17 automatic layout mirroring was introduced. If you want your app to use layout mirroring then you need to flag this support in the <application> element in your manifest file.


For some time Android Lint has been generating warnings in layouts to replace or duplicate left/right layout properties to new start/end equivalent properties for RTL support. For example if your layout contains layout alignments for left or right, such as:


You should also add the equivalent End element to support RTL:


The latest versions of the Android Studio layout editor will add these in automatically when you create the items. If you are hand coding the XML or created the layout in an alternative IDE you may have to add them manually.

Mirroring drawables on RTL layouts

Drawables often need to be reversed on locales that use RTL layouts. An example of this is the Notification bar at the top of your Android device. On a RTL layout the icons, ie. signal strength, will be reversed. There are a couple of ways to achieve this.

For API 19+ you can set the the AutoMirrored Flag to indicate if a drawable should automatically be reversed when a RTL locale is selected.

For API 17+ you can specify different drawables in the same manner as you might for different densities using the qualifier “-ldrtl” or “-ldltr”. For example your resource folders may look like this:


Testing with Pseudo-localization on RTL layouts

Earlier in this article I explained how to set your device to language English (XA). There is also another locale (XB) in the languages list which allows testing of pseudo-localization using a mirrored RTL layout.

locale_xb sample_locale_xb

In the images above the Android signal strength icon is AutoMirrored once the RTL layout locale is invoked. Take some time to consider which icons should be mirrored in your app. Also note how layout mirroring has been invoked with the ActionBar to move the search and navigation views.


Translating large products is a time consuming and expensive exercise that will require at least a few iterations between developer and technical writer. By ensuring your product is fully prepared for localization prior to starting the text translations you will keep the number of iterations and costs of the process down. Add pseudo-localization, visually inspect all layouts and run your full test process to ensure your product not only functions, but looks good in anyone’s language!


Filed under Android SDK, Testing

Vector Graphics in Android: Converting SVG to VectorDrawable

Vector graphics native support has long been on the wishlist of Android developers who have to export their vector graphics as a rasterized PNG file for each different device resolution.

Introducing VectorDrawable

The good news is that the Android SDK now has native support for basic vector graphic definitions. With the release of API 21 (Android 5.0) came VectorDrawable.

The most important things to understand if you want to implement drawables in your app using VectorDrawable are:

  • VectorDrawable is not implemented in the support library, therefore it will only work in Android 5.0+ (VectorDrawable support for older APIs may be coming soon to the support library)
  • VectorDrawable supports paths using the same definition as the ‘d’ attribute in the SVG format
  • VectorDrawable does not read or support the SVG format
  • VectorDrawable does not support gradients and patterns
  • VectorDrawable does not support numbers using scientific E notation (as commonly used in SVG)

While it is important to understand that the SVG format is not supported, it doesn’t necessarily mean you can’t convert your existing simple SVG files. A VectorDrawable is specified through XML, with the format of the path data in the VectorDrawable using the same format as the specification for SVG paths. This allows us to reformat the XML in some SVG files to convert it into a VectorDrawable XML file.

If you are looking to use SVG files directly in your Android app take a look at this comparison of 3rd party solutions:

Case Study: Converting SVG to VectorDrawable

The penguin in the image below (Attribution: Larry Ewing) has been rendered from a SVG image.  SVG images such as this can not be converted into a VectorDrawable as it uses LinearGradient in the original source.NewTux

Below is a rendered image of the flag of Ghana, it is also rendered from an SVG however as this image doesn’t have a gradient and only includes simple shapes, it is most suitable for conversion to a VectorDrawable. We will use this image as to illustrate how to convert an SVG into a VectorDrawable.

Flag of Ghana

SVG Images are described using the XML format. The above image contains 4 elements; three stripes and a star. The SVG XML source may appear as follows:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns:svg=""
  id="rect4" />
  id="rect6" />
  id="rect8" />
  d="M225,100 L257.492,200 172.427,138.197H277.573L192.508,200z"
  id="path10" />

If we want to create this same image as an Android VectorDrawable the first thing we need to do is ensure all items are described using paths. Remember only paths are supported in VectorDrawable.  To do this we convert each rect definition in the SVG image to use a path definition. The following XML shows the new path objects:

  d="m 0,0 450,0 0,300 -450,0 z" />
  d="m 0,0 450,0 0,200 -450,0 z" />
  d="m 0,0 450,0 0,100 -450,0 z" />

The next step is to convert the XML into Android’s new VectorDrawable format.  To do this we need to keep the path and color definitions but replace the formatting.  The XML should now look like this:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android=""

    android:pathData="M 0,0 l 450,0 0,300 -450,0 z" />
    android:pathData="M 0,0 l 450,0 0,200 -450,0 z" />
    android:pathData="M 0,0 l 450,0 0,100 -450,0 z" />
    android:pathData="M225,100 L257.492,200 172.427,138.197H277.573L192.508,200z" />

This VectorDrawable file should be named with an .xml extension and placed in your drawables folder so it can be accessed in your Java source code or layout definition as you would with any other drawable.

The good news is you don’t need to step through this process by hand each time, there are tools to help you out. I have documented this process as it is important to know what and how to hand code the xml format as the conversion tools will not work all of the time so you may need to tweak the code from time to time.

To convert your SVG file to use only paths you can use Inkscape (The awesome open source SVG tool).  Open the SVG file in Inkscape and select all items you want to convert to a path.  Then from the Path menu select Object to path. If you use Adobe Illustrator then you need to convert the shapes into compound paths before saving the SVG.

To automate the conversion of an SVG file to the VectorDrawable format you can use the on-line open source svg2android tool.

VectorDrawable support pre Android 5.0

While the VectorDrawable class is only available on 5.0+ at this stage, an unofficial project has released support for older versions of Android.

Visit Mr. Vector on GitHub for the source code and usage instructions. You should note that the Vector XML used in this project is slightly different to the standard VectorDrawable specification. You can convert your simple SVG files to the Mr. Vector format using Svg2MrVector.

UPDATE MAY 2015: VectorDrawableCompat is in the process of being developed and may be added to the official support library. Once released there is no need to use the Mr. Vector project anymore, so keep an eye on the official Android Developers Blog for updates to the support library.


Scalable Vector Graphics

SVG Path Format




“NewTux” by Larry Ewing. Licensed under Attribution via Wikimedia Commons –

“Flag of Ghana”. Licensed under Public Domain via Wikimedia Commons –


Filed under Android SDK, Image

Vector Graphics in Android: SVG Format

Vector graphics native support has long been on the wishlist of Android developers who have to export their vector graphics as a rasterized PNG file for each different device resolution.

The main use case for vector images are simple icons that need to scale to fit the resolution of the device. Another more complex use case is to implement functionality like that of the Androidify app from Google. In that app you can tweak and accessorize your little Android friend without any of the artifacts that become present when resizing raster images.

Why doesn’t Android support SVG?

I don’t believe there has ever been official word out of the Android team about support for SVG (Scalable Vector Graphics). However it is safe to assume that the reason SVG is not supported as a native image format is because of performance issues. SVG files can run into megabytes of XML data and to render a SVG those megabytes of XML have to be parsed and interpreted and then rasterized. Do some testing using some complex SVG images with some of the open source libraries in this article and you will see the performance issues that surface.

With Android 5.0 we have seen the future direction of vector graphics for the operating system, that is the VectorDrawable class. I will discuss this new functionality in more detail in a sequel to this article, but the take away from it is that full native SVG support will not be coming to Android any time soon, if ever. To read more about converting your SVG files to a VectorDrawable see the second part of this series on Vector Graphics in Android:

Open Source SVG support

The solution for developers to get vector image support has been to turn to the open source community to fill this gap. There have been a few solid implementations providing SVG support in line with the majority of the SVG specification. However there is no prefect solution for using SVG files in Android and there never will be. Every implementation will have performance issues and, of what is currently available, they all have quirks (some would call bugs) that need to be worked around.

Here is a list of the main open source projects. None of these projects will support every SVG and none will support every part of the SVG specification. You will need to try each solution with the type of SVG files you want to render in your app.



Description: Parser and renderer for Android that claims almost complete support for the static visual elements of the SVG 1.1 and SVG 1.2 Tiny specifications.

Last release:  1.2.2-beta-1 (16 June 2014)

Known issues: 

  • Stroking of underlined or strike through text is not supported in versions of Android prior to 4.2
  • Android 4.3 bug that breaks the <clipPath> feature when using renderToPicture()
  • SVGImageView has documented issues in Android Studio

Status: Code is still being developed and a 1.3 release is planned although the last source code changes were checked in August 2014.

License: Apache License 2.0

Review: I had no issues with this library when rendering simple SVG files. Throw some complex SVGs at it and you see the performance hit you are taking. On some environments I was hitting the stack size limit and could not load some complex images. For my use case loading the SVG on a thread and displaying a placeholder image until completion of the load produced the most successful outcome.



Description:  The developers describe this as a compact and straightforward library for parsing SVG files and rendering them on an Android Canvas. This was the library used to render the interface of the original Androidify app.

Status: Appears abandoned, last changes 2012

License: View the license here

Summary: Very popular on initial release, there are many forks of this project but few have made substantial ongoing bug fixes. If this library works well for you except for some bugs then you may want to hunt around the many forks.



Description: Scalable Vector Graphics Support for Android. This project, a fork of the svg-android project, exists to provide additional capabilities to the svg-android project.

Status: Last code changes were Jan 2014, although very little active development takes place in this project, occasional bug fixes are applied.

License: Apache License 2.0

Summary: Fork of svg-android with enhanced features and newer bug fixes, however development is spasmodic.

TPSVG Android SVG Library


Description: SVG image parser for Android. The developers description is that it converts image to list of native objects which can then be speedily rendered on Canvas, and provides callbacks to allow image elements to be manipulated programmatically.

Status: September 2013 was last activity on this project

License: Apache License 2.0

Commercial Support

There are some commercial options available for SVG support on Android. I have not tried them and have not read glowing reviews of them that would have me reaching for my wallet, if however any of them proved to have a performance edge loading SVG files then they may be worth your consideration.


SVG is a open standard that allows developers to quickly make p vector graphics without expensive software. However it is not a standard that was designed to be quickly rendered inside applications, which is why it is not supported by native Android. There are cases however where using SVG can not only save you development time, but also increase the visual appeal of an app.

If you believe your app falls into the category of those that can benefit using SVG then you may consider using one of the open source libraries. I would recommend AndroidSVG, as long as you follow my two golden rules with SVG and Android:

  • Keep the complexity of your SVG files to a minimum
  • Never load an SVG on the UI thread (either pre-load in advance, or display a placeholder while it is loading)

You may have to get your hands dirty and fix bugs yourself in any of these open source libraries, or work around bugs by manipulating the XML of your SVG files. It is best to have a variety of tools capable of writing SVG files as different tools will produce different XML that will perform differently with these libraries.

One last word of warning. Before you jump in and implement anything using the SVG format in your app you should take a look at VectorDrawables.  I won’t go into the pros and cons of these here, I will leave that for part 2 of this series on Vector images in Android.

Sample Project

For a functional sample showing the use of AndroidSVG, take a look at the following project from GitHub:


SVG Homepage

SVG Specification

Inkscape Open Source Vector Authoring Tool

Leave a comment

Filed under Android SDK, Image

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