RxJava with AIDL Services

Most contrived Rx examples show you how to replace AsyncTask with Rx. Not many examples show how to abstract away complex async scenarios, such as oneway AIDL Bound Services. Using RxJava with AIDL Services will help us clean up the interface to consume the AIDL service – making it less … gross and easier to work with.

Assume you want to connect to a Bound Service which is
created through AIDL to get some data. Let’s also assume that all the calls on that bound service are oneway calls (async with a callback listener). In order to get the data you need you will have to set up a ServiceConnection then once connected you need to then use the service object to request the data. Since the connected service (AIDL Service) you’re working with only has oneway calls you basically have two layers of indirection you have to deal with before you can get at the data. For example – Suppose we pass in a orderId and we get an Order object back from the bound service … we have to wait for two async calls to complete in order for that to happen:

  1. Connecting the Activity to the bound service via the ServiceConnection
  2. Making the async call on the service after connection, passing in a callback listener to be called when the data is returned.

Currently anytime I need data I have to connect to a service, wait … query the service, wait … and then get a callback. If I need to make multiples of these types of calls things can get hairy, fast.

The goal here is to wrap this code up somewhere and abstract away the details and simply have an interface that returns Observable<Order> getOrder(long orderId);

Here’s how I’ve gone about implementing this … (full gist).


In the constructor I connect to the bound service with the bindService call. This is async. Once connected in the ServiceConnection I call onNext on the BehaviorSubject that holds the reference to the boundService. Since no one is listening yet, no big deal. That class just hangs outs and waits.

When an interested party subscribes to the getOder call, we return:


This way the caller doesn’t know they’re working with a subject (which is recommended).

In that method I subscribe to the orderServiceSubject. If the service connection is still in flight, no big deal – Rx will allow us to wait until onNext on the orderServiceSubject is called. If the service connection has succeeded then the subscriber to orderServiceSubject will get it’s on next called with the bound service as its parameter.

Once we have reached this point, we have a bound service object that we can call methods on. Remember, these methods are set as ‘oneway’, meaning that they are also async and we must supply a callback listener that gets called once the work is complete (at this point it is starting to resemble JavaScript all of a sudden, like whoa).

Inside of this listener (the anonymous Stub class) we use the PublishSubject – orderSubject and call its onNext with the value that was returned. This will propagate the value all the way back to the activity and then we can do whatever we want with it.

As you can see, we can abstract away the nasty AIDL code behind Rx and make it a lot cleaner. Now the client can use RxJava and get the the benefits of Rx without dealing with the ugly guts of the AIDL system.

Special thanks to Dan Lew for proof reading this article.

Here’s the full implementation with an example of how you’d implement this with an Activity.

Quick and Easy StateListDrawables in Android with ONE PNG

One of the things that used to drive me (and my designer co-workers) crazy was that we needed to create a full stack of various PNG’s to create different states on our drawables. That means if I wanted a button with a white default state, orange pressed state and grey disabled state I’d have to create three PNG’s (for each density) … which … as you know is a huge number of PNG’s and a real pain to update when the time comes.

One Png To Rule Them All

I’m not the first to come up with this solution, but I figured its a good time to share it so its out there. This is not a one size fits all solution (see the conclusion at the end for more info), but it does give you a good jumping point and if you’re building state list drawables. You can see how this would help you simplify some of your icons by only having to create one.*

With this solution we have one PNG and then we use some Java code to create a StateListDrawable at runtime. This allows us to have one default PNG and then change the colors at runtime with just code.

Place the code below in a file called DrawableUtil.java and put it somewhere in your project.

public class DrawableUtil { 

    public static StateListDrawable getStateListDrawable(Context context, @DrawableRes int imageResource, @ColorRes int desiredColor, @IntRange(from = 0, to = 255) int disableAlpha) {

        // Create the colorized image (pressed state)
        Bitmap one = BitmapFactory.decodeResource(context.getResources(), imageResource);
        Bitmap oneCopy = Bitmap.createBitmap(one.getWidth(), one.getHeight(), Bitmap.Config.ARGB_8888);

        Canvas c = new Canvas(oneCopy);
        Paint p = new Paint();
        int color = context.getResources().getColor(desiredColor);
        p.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
        c.drawBitmap(one, 0, 0, p);

        // Create the disabled bitmap for the disabled state
        Bitmap disabled = BitmapFactory.decodeResource(context.getResources(),imageResource);
        Bitmap disabledCopy = Bitmap.createBitmap(disabled.getWidth(), disabled.getHeight(), Bitmap.Config.ARGB_8888);

        Canvas disabledCanvas = new Canvas(disabledCopy);;
        Paint alphaPaint = new Paint();
        disabledCanvas.drawBitmap(disabled, 0, 0, alphaPaint);

        StateListDrawable stateListDrawable = new StateListDrawable();

        // Pressed State
        stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, new BitmapDrawable(oneCopy));

        // Disabled State
        stateListDrawable.addState(new int[]{-android.R.attr.state_enabled}, new BitmapDrawable(disabledCopy) );  // - symbol means opposite, in this case "disabled"

        // Default State
        stateListDrawable.addState(new int[]{}, context.getResources().getDrawable(imageResource));

        return stateListDrawable;


The code above creatse a StateListDrawable that will return a Drawable that has three states:

  • Default – The default image (imageResource)
  • Pressed – The default image, colored with the color param (desiredColor)
  • Disabled – The disabled state image is the default image (above) but has the opacity set to the value that is passed in (disableAlpha)


How to Use It

Simply call the static method with the required parameters and it will return a StateListDrawable that you can use to set the background of any image that can have state (like a Button, ImageView, etc).

myImageView.setBackground(DrawableUtil.getStateListDrawable(context, R.drawable.ic_user_dark, R.color.white, 127)); // 127 = 50% in 0…255 alpha

Now, if for some reason you want to change the color of the pressed state, simply change the color value that is passed in – say changing R.color.white to R.color.red and have the new selected image be red. All done with a simple code change.

If you want to get advanced you could use the Pallete lirbary to help get your colors and colorize your icons based upon the theme of the image that is composing the screen, the PocketCasts team does a great job of this in their player.

Here’s what it looks like if we use a user icon, set the pressed color state to red and the disabled to 90.


Why Did I Use This

There are a couple of other support library implementations that we could have used (shown below). The reason why this implmentation was used over the others is because I wanted to keep the default state of the PNG intact. What do I mean? I wanted to use a PNG that looked like this as the default state (not pressed, nor disabled):


When pressed though, I wanted the image to look like this:

Other Implementations such as DrawableCompat.setTintList() would not allow me to keep the original drawable.


Other Implementations

On the /r/androiddev comments for this article it was brought up that you can use DrawableCompat to wrap and set the tint list on the drawable. This is correct, somewhat. A problem occurs when you want to perform what I set out to do above – keep the original drawable but tint the other states. If you don’t care about keeping the original color (or simply want to change it anyway) you can use the DrawableCompat with great success like this:

Drawable logoDrawable = getResources().getDrawable(R.drawable.ic_agilevent_logo);
Drawable tintableDrawable = DrawableCompat.wrap(logoDrawable);
DrawableCompat.setTintList(tintableDrawable, getResources().getColorStateList(R.color.logo_color_selector));
DrawableCompat.setTintMode(tintableDrawable, PorterDuff.Mode.SRC_IN);


The R.color.logo_color_selector looks like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/red" />
<item android:state_enabled="false" android:color="@color/green" />
<item android:color="@color/blue" />



The new material design support libs out there you can do some of the same things I’m showing above, but some have still opted for this solution as they’re not 100% material (or not going material at all).

This is one of many solutions to a very common problem. It does not mean that you have to use this, in fact if you’re using v21+ you can use android:tint attribute to colorize android pngs. You can also use the android colorFilter to do the same thing we’re doing above. Like I said, there are a few ways to do this, but this is one way where you create advanced state list drawable in code.

Lastly, there is also a TintImageView that is present in the android.support.v7.internal.widget.TintImageView that has very similar settings. The code to use it looks like this:



However, I would advise against using this as this is inside of the internal package inside of android.support.v7. Traditionally anything inside of an internal package name indicates that it is not a public API that should be consumed or relied upon. Choose to use it at your own risk. :)

Why You Should Use a GIT SHA in Your Crash Reporting

A common problem developers encounter when developing applications that use a crash reporting tool like Crashlytics is determinig if a particular crash/bug has been fixed/addressed or not.

For example assume that you get a crash report for a recent release. But you released three times this week already … which release does it apply to?

This is usually solved by reviewing the version code and verison name in Crashlytics. But even then you have to be properly tagging your releases. If you’re doing that you can trace back the release to a particular commit and then investigate.

However … Lets be 100% honest here – not everyone does this. Unfortunately , very few companies do this in my experience and it declines even more when the size of the team deminishes to even a single developer. There’s a lot going on, its easy to miss. Furthremore, chasing down a tag, then finding a commit, well … its kind of a pain. If someone forgot then its all for nothing.

That said, here’s a quick tip that can save you a ton of time when you’re performing crash and bug triage with tools like Crashlytics.

Adding The GIT SHA
In your Android application, open the build.gradle file and add the following above the android block.

// Hat tip to Jake Wharton for this - found it in the u2020 app
def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()

Back in the Android block add a git sha build config constant.

android {
 compileSdkVersion 19
 buildToolsVersion "21.1.0"

 defaultConfig {
 applicationId "co.your.appname"
 minSdkVersion 19
 targetSdkVersion 19

 buildConfigField "String", "GIT_SHA", "\"${gitSha}\""


Now go back to where you’ve set up your Crashlytics instance in your application code (example shown below). Just below the initialization script add the following code:

Crashlytics.setString("git_sha", BuildConfig.GIT_SHA);

What this will do is set a string with the key value being “git_sha” and the value being the short git-sha from your source control.

Now, when your application crashes you’ll get a bug report in Crashlytics and you’ll be able to see what the latest commit was on that code.

Reviewing in Crashlytics
Open Crashlytics and go to one of your crashes. Then click on “more details”. Here you will see (screenshot below) the git_sha that the application was built off of.

Then you’ll see this ..


Once you have identified the crash and the git-sha you can checkout that exact version of the code by issuing

git checkout git_sha_goes_here

At this point you’re in a detached head state. You’ll want to see what caused the crash in this state. Then you’ll want to return to your current develop branch or tagged branch to fix/hotfix the issue and release the fix.

The git_sha saves a ton of time and its super easy to set up. You no longer have to dig through git logs, tags, patches, etc to find “what commit is this crash happening on? Did we fix it already? How can I find out?” Simply check the git sha, look for the bug, see if it’s fixed yet. If it is, cool. If not, fix it and be on your way.

I hope that helps!

** Update **

Jake had a great comment in the reddit thread that I wanted to share …

Worth noting that this will break incremental compilation as you commit (and thus cause the value to change). Internally we switched to writing the SHA to a file if it is missing and using the file’s value (we do the same with build timestamp). This means that only a clean build gets fresh values. Since CI builds and making releases are always clean (right? RIGHT?) it keeps developer builds fully incremental yet still gives the right values where it matters. – Jake Wharton

A Stereotypical Day

It was a nice sunny day, maybe 70 degrees here in AZ. A perfect early spring morning.

I decided to go work at my favorite local coffee shop. I walked in and saw a guy in his mid 30’s covered in tattoos. Not just arms, but legs, hands, fingers … the whole nine – he was covered in them – some good some bad – that doesn’t matter though. He had a beard, he was sort of skinny, yet not a rail. He kind of looked like a hipster but also had some other type of other aire about him. Not sure what it was. He looked nice, but he also looked lost. That was my initial impression of him.

He was working behind the counter at the coffee shop; I thought he was the new guy – I’d never seen him before.

He was kind of awkward when replying to a couple of professional guys at the coffee bar and I dismissed him as some tattooed guy who is just trying to find his way in life. Just another guy who probably made a bunch of mistakes during his time on earth and is now working at a coffee shop, taking it day by day. I see it almost everyday in every city I visit. It is what it is. Secretely, I wished the best for him.
Everyone deserves a chance, right?

I get in line and a few minutes pass.

The tattooed guy starts talking to a customer. I’m in line behind the guy he’s talking to. Another gentleman approaches the two and interjects.

“He’s the owner of this place.”, says the newcomer.

He’s referring to the tattooed guy. That lost guy I was talking about above.

The tattooed guy admits he is the owner and that business is going quite well. The professional gentleman states that he wishes one of these shops were up in the northern part of the city because he loves this coffee shop. The tatooed guy states that hes looking to expand, reaches under the counter and grabs some business paperwork and starts thumbing through them – looking at numbers and charts, I presume.

The location of this coffee shop is in Scottsdale. Old town to be exact. The thing about Old Town Scottsdale – it is quite expensive here. It’s not a place I’d want to rent a commercial space. It’s very pricey. This place is nice, real nice. It’s defintely an expensive venture, and it is successful. Impressive.

What’s not impressive though?

That guy, the one I stereotyped a minute ago and dismissed as some nobody who is just trying to find his way …well … he is the owner of this place that I call my favorite coffee shop in all of Arizona. He’s not lost. He’s on his way, he has direction. I was wrong to stereotype him. I’m sorry tattooed guy – you have all of my respect and then some. I was wrong.

I order my coffee and step back and wait for it.

No more than 10 seconds later a man in black medical scrubs approaches the counter and puts down a recently emptied pint glass. This coffee shop also serves excellent micro brew beer and he just finished one.

I immediatly think to myself “its 8:10am on a Thursday, and that guy has already had a beer, what the hell?”

I take a longer look at him. He’s in his late 40’s or early 50’s. He looks tired. It’s obvious that he’s in the medical profession. Is he a surgeon or physician? Maybe. Probably. Is he a nurse or a staff member of a surgical team? Maybe. Probably.

I start thinking about why he might be drinking a beer this early in the morning.

I then remember that there is a hospital with a very active surgery center across the street. I can see it from where I’m typing this. My wife actually had a couple of surgeries at that exact location.

I also notice another woman in scrubs drinking coffee at the other end of the shop. I then realize that I see medical professionals in here a lot – I just had not really thought about it before. It makes sense – its a nice relaxing place and its close to the hospital. Its an excellent place to unwind.

Rewind a couple years.

I remember being in that exact same surgery center waiting room with my kids, terrified. I was in there hoping that my wife’s surgery would be a success and without a hitch (it did go well, both times – thankfully). I also remember seeing the others in the waiting room wearing exhausted looks of worry and fear.

I began thinking to myself – the waiting room at a surgery center/ hospital is not a place we go when we want to enjoy ourselves. We’re there because we have to be there, we’re there because we’re hoping women and men like the one who just put down an empty pint glass on the bar a second ago can help fix whats wrong with our loved ones.

Back to the man in the black scrubs …

It’s also obvious that this gentleman is off work – he looks wornout and has a stack of papers near his chair. I’m sure he had a long and late night (and/or early morning).

Back to the counter – He orders another beer.

He returns to his chair and starts reviewing some paper work, taking a moment every few minutes to lean over a bit, rounding his back and then he grasps his head like a basketball player palms a basketball.

Its apparent he’s under some level of duress.

I’m not sure why he’s here, but I have a suspicion that its because what he just went through at work this morning called for a beer, or two … or more.

I can only imagine the things that he sees and deals with. Its very possible someone died in front of him this morning. Its very possible he did everything he could to save this persons life. I can only imagine the level of stress that can bring.

So … who am I to judge him for drinking a beer at 8:10am? I should’nt be worried about it and I won’t be worried about it anymore.

Its also very possible he’s an alcoholic who is feeding his addiction, but I like to give people the benefit of the doubt. It looks like he was at work and looks like he had a long night.

What’s the moral of this story?

Its quite simple … both of these guys are having a stereotypical day and I just stereotyped them both within the first minute of seeing them. It wasn’t right.

We need to all act more compassionate towards each other and realize why we feel the way we do, even during our first impressions. Perhaps they’re wrong, most likely our first impressions are wrong.






The Single Best Thing You Can Do For Your Career

If you’re looking to break out in your industry and looking to take yourself to the next level there is one thing that can help propel you into opportunites you never imagined. What is it?

Public Speaking

It’s true. No doubt about it. I attest most of my success to a fateful day in 2008 (May 31st to be exact) when I spoke at Desert Code Camp in Phoenix. That was my first public speaking event in a professional setting, ever. The topic?

Intro to Dependency Injection and Inversion of Control
You can find the slides for that talk right here on slideshare.

I’m serious, that’s my first foraye into speaking. The slides are terrible and embarassing, but everyone loved the talk at the time. In fact, the people liked it so much that when I signed up to speak there I was able to see how many people were going to be at my talk in advance. The web app that code camp was using at the time had that feature (it was a different one than Desert Code Camp uses now, but similar). Long story short, my talk went from the “small classroom” to the medium room, to the large room to the auditorium at a tech college I was speaking at. Fun fact – the presentation was at UAT to be exact and thats actually where I went to college.  I was very familiar with the auditorium and knew how many people it could fit. At the time I went it was 172 people.

How many people were there when I presented? Well over 172, there was standing room only and it was one of the most popular talks of the day. This is not a humble brag, but I am actually saying this for the exact opposite reason. I’m saying this because when I got on stage, I was scared shitless. To this day I remember walking on stage and then walking off, going outside, calling my wife and telling her how I did, going home and falling asleep from the sheer exhaustion of stress and terror that I just experienced. I do not remember any of the talk whatsoever. Kind of crazy how the mind will do that to traumatizing events.

Terror? Stress? What? Why? You may ask. You had a popular talk. You might think. You’re right, I did. People loved it and I got a lot of professional attention because of it, and it helped my career. The important thing to note here is that this was my first professional talk, ever. The most people I’d ever spoken in front of prior to that event was maybe 10-12 people, and that was during a work lunch when you go around the table and talk about something (such as a team building event). 172+ people? ABSOLUTE TERROR, PANIC & FEAR.

The thing is, public speaking has often been rated in many publications as the one thing people fear far more than death itself. Thats a pretty bold statement. More than death itself? I don’t know about you, but I love life. Sure, its full of stressors and other things that are out of my hands at time, but I love being alive. I’d much rather get in front of people and talk than die. But … thats the reality of the situation – people are scared to get in front of crowds and speak. So scared that they’d rather die. Think about how many people you know that say “OMG, there is now way I could do that, I’d die”. Yeah. Exactly.

That one day led to many job offers eventually. Not just full time offers but consulting offers and offers to do bigger and better things. From speaking I ventured deeper into blogging and then into more writing in general. I kept speaking and eventually got noticed by some consutlingn firms. I worked for them for awhile and kept speaking as well. Companies usually love when you speak in public. You’re a public face of their company (in this case, part of the engineering deparment). Eventually I got enough offers for external contract jobs that I decided to jump and go work for myself as a consultant. I did that six years ago in 2009. I went full time independent consulting. How? All from speaking.

If I had never got in front of people and spoke about what I knew I’d never be in the situation I’m in now. I’m foreever grateful to those who gave me the opporutnity to speak, to hire me and to bring me on to help their team. Thank you.

Fast forward many years later from my initial speaking engagement and I’ve now spoken to crowds of 400-500 people at times with no fear. As with anything – the more you do it, the better you get at it and eventually you actually kind of get used to it.

I challenge you to go out and speak. Find a local user group, a code camp, a meet-up of some sort. Just go out and share your knowledge. Don’t be scared. Will you know everything? No. Will there be someone in the crowd who knows more than you? Yes. Regardless, you need to get out there and do it. You’ll be glad you did. It will open doors you never knew existed.