Speed up your app

A few weeks ago, I gave a talk about Android Performance Optimization, at Droidcon NYC.

I invested a lot of time in this presentation, since I wanted to show real examples for performance issues, and how to identify them with the available tools. I had to cut down about a half of my slides because I didn’t have enough time to show everything. In this post, I’ll summarize everything I was talking about, and show examples I didn’t have time to go over.

The talk was recorded and you can watch it here:

The slides are also available:

Now, Let’s go over some of the important things I was talking about, hopefully I can give a deeper explanation for everything, starting with the basic rules I follow when I work on optimizations:

Read more -->

Yet another blog setup post

After several years of using Wordpress.com for my blog - I decided I need a change.

I wanted to move to something different for a while, but kept postponing it because that would require some time and effort to do. In this post, I’ll summarize my transition experience and elaborate on problems I had and how I solved them. Hopefully, this information will help others with similar ambitions.

Read more -->

AOSP Part 3: Developing Efficiently


The AOSP codebase in big.

Developing on the AOSP is not as simple as writing an app, where you execute a nice gradle target and poof! you see it on the device. So far in this series, we discussed how to get the AOSP code into our environment, and how to build this code into a sweet flashable Android image files. We can now fill in the missing piece – how to efficiently develop for such an enormous system.

In this post, I will cover:

  • Properly importing an AOSP repository into your source control

  • Use better ways to build modules and deploy to the device

  • Writing scripts for faster development process

I’ll use Git and Bash commands that you may not know, but can definitely search and learn as we go. You can also use this simple Bash scripting tutorial to get started.

Read more -->

AOSP Part 2: Build variants

On the previous post, we got the AOSP code into our environment and learned how that process works. The _repo _tool and the Manifest project goes hand-in-hand, managing the 200+ git repositories, all part of the AOSP.

Now that we have all the code locally, we need to get all those lines of code into a nice package we can eventually install on a device. The nice guys in Google brought us some nice utilities to help with that. To initialize your environment with those new functions and environment variables, you need to run the command:

$ source <working dir>/build/envsetup.sh

Note: I’m using Mac OS with “oh-my-zsh” and “zsh” as my default shell. When running this command from a shell other than “bash”, you’ll get a warning that only bash is supported. From my experience, I can tell that I never ran into a problem. If you know otherwise - let me know, otherwise - I highly recommend this configuration regardless of AOSP work.

Now, we can get this party started..

Read more -->

AOSP Part 1: Get the code using the Manifest and Repo tool

6 months ago, I moved to New York, the first city I lived in outside of Israel.

With a new job at a new place, I decided to also try a new laptop running a new platform - Mac OS. I always used Windows before that. I have used Linux as a VM and on servers I worked on, but as a primary OS - I sticked with Windows (with no particular reason).  After many recommendations, I decided to give Mac its big break. As one big advantage of Mac over Windows - I could build my own Android ROM (Android operation system software, running on a device), which i’ve wanted to try and do for a long time.

It wasn’t an easy start..

Read more -->

ViewPager and Hardware acceleration

Last week, Romain Guy posted about Optimizing hardware layers. He explained how hardware layers are a great way to boost the performance of your animations, but can also degrade it.

When your view is backed by a hardware layer, that layer will get updated every time the view itself will update, and after that the layer will be drawn to the screen. Meaning, if your view is altered during an animation – more work is done per frame and you’ll get a drop in your frame-rate. That’s why it’s not wise to change your animated view while it’s backed by a HW layer.

On his post, Romain suggested an easy way to spot such problems, using the “Show hardware layers updates” under the Developer Options. Every time a HW layer is updated – it’ll be highlighted in green.

So I tried it.

Read more -->

Write your own Android Sync Adapter

On my last post on the subject, Write your own Android Authenticator, we embarked on a journey to the unfamiliar part of authentication on Android. I received many positive responses about it from you all, and it seems I really helped a lot of people to get to know this feature well.

Since then, I had a lot of stuff going on in my life (getting married is one of them) which delayed the release of this obvious sequel. On this post, our journey continues to another not-well-documented area, which goes hand-in-hand with our own authenticator. It’s no other than the notorious SyncAdapter. I’ll show you how to make your app more efficient and robust when it comes to data synchronization, by using sync adapters. The web doesn’t have all the information I’d hope to find about it. I felt like I need to give this feature another one of my in-depth researches, see what this feature is all about, how it works, how to write one, and finally – report back.

In the screenshot: That’s how a sync adapter looks on the account screen, under the device’s Settings screen.

First, I’ll explain the benefits of the sync adapter. Then, how it works and after that how to build and monitor it. Finally, I’ll introduce the sample app I wrote, demonstrating how the sync adapter works, and also allowing you to play with its settings to learn from experience.

Read more -->

Create a secret doorway to your app

This short post will be about creating a back-door to your app, giving you the option to provide more information or actions than you want end users to have. This will be using the Secret Code feature.

I came across some articles with list of codes in order to access some phone’s data (i.e. Camera’s firmware spec.), run some tests (i.e. Vibration test) or even perform actions such as reset to factory settings. Some examples can be found here and here and even as an app that indexes all that information.

Create your own

Creating your own secret doorway for your app can help you get more information from users of your app in a time of need. Getting crash reports from end users can be done by several services such as ACRA or BugSense, but how about errors that are not crashes? How many times did your Mom/Spouse/Friend/Mailman showed you their phone, running your app, and said something like: “Why do I see duplicates on the list here?! Why can’t I sync??”. You probably can’t do anything without debugging the app or at least take a look at the app’s SharedPrefs/SQLiteDB. Using a backdoor can help you get more internal information that will help you find the cause for the problem, no computer is necessary!

Another cool thing is providing more actions to do with your app. You want to keep the app clean for your users, but you might want more power to yourself. You can tweak your internal settings, whether for testing purposes or just to try out new features on your everyday use. Not needing to compile a new version after each change of internal setting, can help a lot in the task of identifying tricky problems.


Before learning how you can create your own secret code to do some cool stuff, let’s review some use cases that you can use it for:

  • Diagnose information - Presenting technical details of you app, such as generated UUID that can be used to find relevant server data.

  • Send internal data outside - You can dump app information, such as the SharedPrefs/DB data, and send it to you via email. Since this code runs on the same process as your app - you have access to everything!

  • Change settings - You can change the internal settings of your app. Showing more debug logs, communicating with a different server or even change the sorting order of the list you present the user. Anything that can help you understand more about the current situation of the app.

  • Demo mode - Need to show your app to investors? Showoff to your Friends? You can create shortcuts to some app features that are relatively difficult to simulate. For example: Notification that triggers every morning or when the phone is idle for more than 30mins. Maybe a SMS/phone-call triggered action, QR code scan or a sensor’s incoming data. You can create a demo screen to start everything you want to show on the app, and with sample data to make a neat presentation.


Let’s see how to create one of our own secret code:

<receiver android:name=".receiver.DiagnoserReceiver">
        <action android:name="android.provider.Telephony.SECRET_CODE"/>
        <data android:scheme="android_secret_code" android:host="111222"/>

That’s what you put on your manifest. Looks simple right? All we do is provide a listener to a secret code, defined in a <data> tag as the “android:host” attribute, and declare a receiver for it. On the receiver, we can just run some code, open an Activity, run a Service etc. Here’s an example of a receiver that starts a new Activity:

public class DiagnoserReceiver extends BroadcastReceiver {
	public void onReceive(Context context, Intent intent) {
        if ("android.provider.Telephony.SECRET_CODE".equals(intent.getAction())) {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setClass(context, Diagnoser.class);

We create an intent with the Activity class, Diagnoser, and start it. That activity will run on the same process as our app, allowing us to access all the data that our app has, using all the permissions that our app has been granted with.

Use it

To start our diagnose screen, all you need to do is go to the phone’s stock dialer (third party dialers not always work with secret codes) and dial the secret code you defined in the “android:host” attribute on the manifest, in the following pattern: “###*#*. In our example, you'll need to dial *#*#111222#*#*, the DiagnoserReceiver will receive the intent and start the Diagnoser activity.

That’s it. I hope this post helped you get more from your app. If you have more ideas for use cases for this feature - write them on the comments to help us all exploit this nice feature.

Write your own Android Authenticator

When I wrote Any.DO’s sync system, about 18 months ago, I wanted to use the built in AccountManager API to authenticate and store the users’ credentials. When I used it to access Google accounts it seems a pretty simple experience, so I thought I should do that for Any.DO as well. It also goes very well with a sync mechanism (using a SyncAdapter), making it the perfect solution. The problem - no good documentation was out there. The developers community didn’t have much experience with that back then, and since we didn’t have much time to figure out issues that could arise from this “No man’s land”, a decision was made to use other methods.

But times have changed..

I recently studied that feature again for a project I’m working on, and saw there’s a huge improvement with the knowledge about it. Besides the better documentation on the Android.com site, more and more tutorials went out to the wild, feeding us with knowledge about the mysteries of the notorious Account Manager. Some tales were told about the road to create your own account. I read pretty much all of them. 

But..they all still miss something.

I didn’t feel that I actually know everything I wanted to know about the process, and some parts weren’t clear enough. So I did what I usually do when I want to know everything about something - investigate it “Jack Bauer style”! This post is the in-depth conclusion of my journey, with all the quirks and features that this service provides and I thought was important enough to find out. There will be a followup post about Sync Adapters as well, so I recommend RSS/Twitter subscribing to be notified…if you’re into this kind of stuff. I’ve been pretty thorough learning all those features, not just the basic stuff as all other tutorials did, but if I forgot something - please let me know by commenting this post.

Why Account Manager?

Why really?

Why not just write a simple sign-in form, implement a submit button that post the info to the server and return an auth token? The reason for that is the extra features you get and in the small details that you don’t always cover. All those “corners” that developers often miss when they need their users to sign-in, or dismiss by saying “This will happen to 1 out of 100000 users! It’s nothing!”. What happens if the user changes the password on another client? Has an expired auth-token? Runs a background service that doesn’t have a UI the user can interact with? Wants the convenience of logging-in once and get automatically authenticated on all account-related app (like all Google’s apps do)?

Reading this article will probably make you think it’s complicated stuff, but it’s not! Using the Account Manager actually simplifies the authentication process for most cases, and since I’m already giving you a working code sample - why not use it :)

So, to recap the benefits:

Pros: Standard way to authenticate users. Simplifies the process for the developer. Handles access-denied scenarios for you. Can handle multiple token types for a single account (e.g. Read-only vs. Full-access). Easily shares auth-tokens between apps. Great support for background processes such as SyncAdapters. Plus, you get a cool entry for your account type on the phone’s settings:


Look mom, my name is on the settings screen!

Cons: Requires learning it. But hey, that’s what you’re here for, isn’t it?

The steps we’ll performs to get this done:

  1. Creating our Authenticator - the brain behind this operation

  2. Creating the Activities - in those the user will enter his credentials

  3. Creating the Service - through it we can communicate with the authenticator

But first, some definitions.

Read more -->

Activity Split Animation

This week I had the time to write a small and cool transition animation between Activities.

The regular transition animations between activities animate the Activity as a whole. I wanted to create an animation that split Activity A into 2 parts, animate them in the way out and revealing Activity B. Here’s a gif that illustrate this:


The idea is fairly simple:

  1. Save Activity A as a bitmap
  2. Split bitmap into 2 parts
  3. Pass the 2 bitmaps to Activity B
  4. Show the bitmaps on top of Activity B’s layout
  5. Animate the bitmaps outwards
  6. User is now seeing Activity B

The implementation was not as straightforward as I thought. I ran into some difficulties on the way, but I found solutions to all the problems I encountered. Let’s go step by step.

Note: This implementation requires holding a snapshot bitmap of the entire screen. For some devices that might be a very expensive operation due to low memory and/or large screen area. If you choose to use this animation - do it with care and don’t overuse it.

Save as Bitmap

In order to get a bitmap of the Activity, we can use this code:

[sourcecode language=”java”] View root = currActivity.getWindow().getDecorView().findViewById(android.R.id.content); root.setDrawingCacheEnabled(true); Bitmap bmp = root.getDrawingCache(); [/sourcecode]

On the first line, we get the root view for the activity. We find the view with the id of  _android.R.id.content, _which is the FrameLayout that exist on every layout and contains the layout you put on setContentView(). Here’s how it looks on HierarchyViewer:


In order to get a bitmap of the root view, or any view for that matter, we call the getDrawingCache() method. This will return the cached bitmap of this view in case we have enabled the caching for it. That’s why we also call the setDrawingCacheEnabled() before that. If there isn’t a cached bitmap for the view – it’s been created on the spot.

Split the Bitmap

In order to split the bitmap, I wrote this code:

Bitmap mBmp1 = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), splitYCoord);
Bitmap mBmp2 = Bitmap.createBitmap(bmp, 0, splitYCoord, bmp.getWidth(), bmp.getHeight() - splitYCoord);

_bmp _is the main Bitmap for the entire Activity. _splitYCoord _is the Y coordinate of the splitting point.

I create 2 smaller bitmaps. mBmp1 is the upper part of the larger bitmap and mBmp2 is the bottom part. Each part’s height is determined by the splitYCoord.

Pass the bitmaps to the next Activity

After I have the 2 bitmaps, I want to start the next Activity and put them on top of its layout. That way the user will see Activity A’s layout where in fact we already moved on to Activity B.

At first, I wanted to pass them as Extras of the Intent, it’s possible since Bitmap is Parcelable . The problem is the bitmaps are too large to transport in an Intent, due to size limitation for IPCs. This is the error I got:


There are few workarounds for this, including writing the bitmaps into a file and then read them back on the other end. I found the easiest and fastest way will be to just keep them as data members in a common area. I created a static class to contain the bitmaps and all the logic to create and animate them. More on that later.

Show the bitmaps on Activity B

After I start Activity B, disabling any default activity animation using overridePendingTransition(), I create 2 ImageViews to contain the previously created bitmaps, and presenting them on screen. I do that before calling _setContentView() _to avoid seeing Activity B’s layout ahead of time.

The ImageViews are added directly to the Window of the activity. This allows the ImageViews be on top of the soon-to-be inflated layout and gives more flexibility when deciding the location of each one of them on the screen.

ImageView imageView = new ImageView(destActivity);

WindowManager.LayoutParams windowParams = new WindowManager.LayoutParams();
windowParams.gravity = Gravity.TOP;
windowParams.x = loc[0];
windowParams.y = loc[1];
windowParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
windowParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
windowParams.flags =
windowParams.format = PixelFormat.TRANSLUCENT;
windowParams.windowAnimations = 0;
destActivity.getWindowManager().addView(imageView, windowParams);

Pretty straightforward.

The gravity states where we’ll put our layout in the window. Since we calculated the X,Y position of the bitmaps relative to the top of the screen – we’ll set the gravity to TOP.

Animate the bitmaps

After we created and positioned the bitmaps on Activity B, we can call setContentView() to inflate the Activity’s layout. After the layout is inflated we can start the animation that pushes the 2 bitmaps outwards, thus revealing the Activity’s layout.

mSetAnim = new AnimatorSet();
mTopImage.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mBottomImage.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mSetAnim.addListener(new Animator.AnimatorListener() {
                    public void onAnimationEnd(Animator animation) {

                    public void onAnimationCancel(Animator animation) {

// Animating the 2 parts away from each other
Animator anim1 = ObjectAnimator.ofFloat(mTopImage, translationY, mTopImage.getHeight() * -1);
Animator anim2 = ObjectAnimator.ofFloat(mBottomImage, translationY, mBottomImage.getHeight());

mSetAnim.playTogether(anim1, anim2);

The animation is a simple TranslationY animation that moves every ImageView outside the screen, each one to a different directions. I use hardware acceleration (read my last blog post to learn more about HW accelerated animations) and I do some cleaning after the animation is finished or canceled (removing hardware layer, removing the ImageViews from the window etc.).

How to use my Animation

So I was debating with myself what’s the best way to make it easier to use, without limiting the developer too much. The easiest way was to create a base Activity that the developer can extend and the actions will be taken care of without too much effort. The reason I didn’t do that is because I **HATE **extending from other base activities just to get some more features. If your application has it’s own base activity it can be very frustrating if every library will demand you to extend from their own branded Activity.

That’s the reason I created a simple class with static methods that do all the work. here’s the API:

 * Utility class to create a split activity animation
 * @author Udi Cohen (@udinic)
public class ActivitySplitAnimationUtil {

     * Start a new Activity with a Split animation
     * @param currActivity The current Activity
     * @param intent       The Intent needed tot start the new Activity
     * @param splitYCoord  The Y coordinate where we want to split the Activity on the animation. -1 will split the Activity equally
    public static void startActivity(Activity currActivity, Intent intent, int splitYCoord);

     * Start a new Activity with a Split animation right in the middle of the Activity
     * @param currActivity The current Activity
     * @param intent       The Intent needed tot start the new Activity
    public static void startActivity(Activity currActivity, Intent intent);

     * Preparing the graphics on the destination Activity.
     * Should be called on the destination activity on Activity#onCreate() BEFORE setContentView()
     * @param destActivity the destination Activity
    public static void prepareAnimation(final Activity destActivity);

     * Start the animation the reveals the destination Activity
     * Should be called on the destination activity on Activity#onCreate() AFTER setContentView()
     * @param destActivity the destination Activity
     * @param duration The duration of the animation
     * @param interpolator The interpulator to use for the animation. null for no interpulation.
    public static void animate(final Activity destActivity, final int duration, final TimeInterpolator interpolator);

     * Start the animation that reveals the destination Activity
     * Should be called on the destination activity on Activity#onCreate() AFTER setContentView()
     * @param destActivity the destination Activity
     * @param duration The duration of the animation
    public static void animate(final Activity destActivity, final int duration);

     * Cancel an in progress animation
    public static void cancel();

In order to use it, just call this from Activity A when you want to animate to Activity B:

ActivitySplitAnimationUtil.startActivity(Activity1.this, new Intent(Activity1.this, Activity2.class));

And call this on Activity B’s onCreate():

// Preparing the 2 images to be split

// Setting the Activity's layout

// Animating the items to be open, revealing the new activity.
// Animation duration of 1 second
ActivitySplitAnimationUtil.animate(this, 1000);

That’s it!

No need to extend anything, just 3 simple calls to static methods.

The code supports API14+ but it can easily be converted to work on older devices using NineOldAndroid.

The repository is here:


Use it, Fork it, Extend it.

What’s next

There are more things that can be done to extends it:

  1. Vertical splitting – Let the activity split also to the sides.
  2. Split the activity to more than 2 parts
  3. You name it!