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/

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 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(; 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, _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!

Android app to the Challenge

A week ago I gave a talk about Android performance, presenting some old and should-be-known-to-all-developers methods, aside to new tools introduced in Jellybean. The talk was recorded and here’s the video:

The slides are here.

I know that performance optimization tends to be pushed aside when developing a project, especially if you’re in a start-up company and all you do is pretty much “run” with the product.


On this post I’ll give you the tools **and knowledge **to easily do a performance review and solve common issues in your app, rising it up to the challenge of smooth running.

Let’s start:

Read more -->

Android Scripts

As a busy/lazy developer, I always try to automate repeating routines. Those sequence of actions are getting annoying after a few times and always make me gasp. That’s why some of my time is dedicated to writing small scripts to make my life easier, and the development process faster and anger-free. Most of them are very specific to the apps I’m working on, and some are more generic. I’ve pushed them to a new repository on GitHub, and it will updated with more scripts when I’ll make some more, or generalize other existing scripts that I use.

ADB Batch Scripts

ADB – Android Debug Bridge, is a very powerful tool. You can control a lot of features on the phone. Furthermore, granting yourself with a ROOT access will bring many rewards, as getting files in and out the file-system, manipulating system files and more. I highly recommend rooting your development phone; it’ll prove itself worthy towards the trouble that it might cause in some devices. I’ll also note that the root access from ADB is limited on production builds (stock ROMs) vs. custom ROMs (e.g. Cyanogenmod), so I prefer to just flash a custom ROM on my development phone, making me the master of its domain!

Most of my repeated ADB commands are for DB access. I need to check the app’s SQLite DB to see that my code did everything right. So I wrote this windows batch script:

adb root
adb pull /data/data/<package name>/<db filename> c:\temp
if %errorlevel% neq 0 goto :error
start d:\programs\SQLite_browser\SQLiteDatabaseBrowser2.0b1.exe c:\temp\<db filename>
goto :EOF

echo Error accessing the DB
exit /b %errorlevel%


First, I request to start ADB with root access, not applicable on stock ROMs (as least not easily), and pulling out the DB file to a temp location. The first time running this will show an error, since the _adb root _command restarts the ADB daemon on you computer, which causes the next ADB command not to find the device momentarily. The second time running this will be the charm. To open the DB I use SQLite Browser, which is very simple and lite. Running SQL on the DB is buggy, but for simple table viewing – it’s good enough.

If we want to modify the DB on the device, I wrote a small script to receive any SQL statement, and run it directly on a DB inside the device:

adb shell sqlite3 /data/data/<package name>/<db filename> %1

Very simple. Using the sqlite3 command, we can get a SQLite prompt that’s running on the device itself. If you don’t have the sqlite3 file in your device, which can happen on stock ROMs mostly, you can use this nice article that helped me do it on my Galaxy Nexus, or just search Google.

Another common thing I do, is executing specific services and activities, great help for my debugging life. The syntax is simple, but here’s an example to show how easy that it:

adb shell am startservice -n <package name>/<Service full class name> [<extras>]
adb shell am start -n <package name>/<Activity full class name> -a android.intent.action.MAIN [<extras>]

I can pass extras, action and even activity attributes as clear-top, no-animation and more. I recommend reviewing all the options for those commands, you might get ideas how to automate some of your routines.

Some tests require installing/uninstalling the app to clear the data fast or to test upgrading code. The _adb install _and _adb uninstall _will do the trick here. Very simple to use and fast. I usually install the newest version of Any.DO on my device using an ADB command, rather than from Google Play. It’s just faster!

Python Scripts

Using Python, I could write more complex stuff, like analyzing a system dump, pulling only the important information. If you’re familiar with ADB, you probably heard of “adb shell dumpsys”. This command will print a dump of the system, containing LOTS of data about memory allocations, registered receivers, apps permissions and more. You can call “adb shell dumpsys <service name>” to get a specific service’s information. Some examples:

# All the information about accounts on the device
adb shell dumpsys account 

# The battery state
adb shell dumpsys battery

# All the registered alarms on the device
adb shell dumpsys alarm

The problem with the last command – it prints out too much garbage. There are lots of alarms registered on your device at any given moment, and the dump’s printing format is not exactly an eye candy. Since there’s a lot of alarm handling on Any.DO, I needed a clear and easy way to look only at the relevant information. That’s why I wrote this script:

p=subprocess.Popen([r'adb', 'shell', 'dumpsys alarm'],
                       stdout=PIPE, stderr=PIPE,
                       shell= True,
out, err = p.communicate()

pp = pprint.PrettyPrinter(indent=4)

lines= out.split('\n')
alerts = [["RTC TYPE", "When", "Repeat", "pkg", "Type"]]

for i in xrange(len(lines)):
    if lines[i].replace(" ","")[:3]=="RTC":

        # Extract the information we
        rtc_type = lines[i].strip().split()[0]
        intentType=list(re.findall("PendingIntentRecord{(\w+) ([\w\.]+) (\w+)", lines[i+2])[0])

        # If the user has passed a package name as an argument
        # we'll filter all other packages' alarms
        if len(sys.argv) > 1:
            if intentType[1] == sys.argv[1]:
                alerts.append([rtc_type, when, repeat, intentType[1], intentType[2]])
            alerts.append([rtc_type, when, repeat, intentType[1], intentType[2]])

out_lines = [""] * len(alerts)

# Format the data nicely to columns
for column in xrange(len(alerts[0])):

    for alert_index in xrange(len(alerts)):
        out_lines[alert_index] += str(alerts[alert_index][column])

    line_size = max(map(len, out_lines)) + 5

    for alert_index in xrange(len(alerts)):
        out_lines[alert_index] += " " * (line_size - len(out_lines[alert_index]))

for l in out_lines:
    print l

All I do here, is getting the output from the command “adb dumpsys alarms”, and extract the information I need the most:

  1. RTC type.
  2. When will the alarm go off.
  3. The repeat interval of the alarm, if there is one.
  4. The intent type that the alarm will invoke. Could be a Service, Activity or a Broadcast.

Here’s an example output:


Passing the package name as an argument will print only its relevant alarms.

Another issue I encountered was activities’ stack handling. All those activities’ attributes, “singleTop”, “singleInstance” and more, can get you utterly confused about what would happen when you press the back button. Will you be navigated to the previous activity? will you be thrown to your main activity? or is it to the launcher screen? Reading the documentation will help you understand what **should **be, and using my “Activity stack viewer” will help you see what **is **happening back there. This script is parsing the dumpsys, as the previous script did, and prints the activities’ stack grouped by their package name:


Here I can see that on the Twitter app, I opened the post activity from the home activity. I see all the other paused activities that haven’t been destroyed yet by the operation system. Passing a package name as an argument will print a filtered list;

That’s all for now. I hope I helped at least some of you to do thing better. I’ll keep that GitHub repository updated with new scripts I’ll write. If you have a script to contribute – please comment to this post about it.