Wednesday, May 25, 2011

Answers to Unanswered Questions from the I/O Protips Q&A

There's never enough time for Q&A at the end of an I/O session - particularly when the session is immediately followed by lunch. In an effort to remedy this, here are the answers to most of the questions that were entered onto the Moderator page for my Android Protips talk.
    Eclipse is a wonderful development tool. However sometimes it is clunky. Generic error messages, mysteriously build problems solved by quitting & relaunching, etc. Do you ever get frustrated with Eclipse? Do you have any tips of working with Eclipse?
I do! Almost as much as I was frustrated by Visual Studio in a previous life spent writing C# Winform GUIs. I don't have any specific tips beyond the things that work with mode IDEs. Frequently restart and make sure you're using the latest stable build along with the latest version of the ADT.
    Do you have any tips for working with SQLite databases through eclipse? At the minute I rely on external tools to view data that is in the database on the phone to debug problem. This means manually copying it off the device. Any tips?
You can use the sqlite3 command line tool to examine SQLite databases on the phone. It's not built into Eclipse but might save you the extra work of pulling the database off the device first.
    Do the developers at Google use any hardware emulators to speed up development. If so, can you please recommend some. The soft emulator is too slow.
Unfortunately not. Generally we'll be working towards the release of the new platform on a given piece of hardware, so the internal teams will use that rather than an emulator where appropriate / applicable.
    Will there be a faster Android device emulator anytime soon?
Yes! Check out this session on Android Development Tools for a preview.
    Is there a suite of AVDs for Eclipse that emulate actual devices?
Some manufacturers make AVDs available for actual devices (I believe Samsung provide an AVD for the 7" Galaxy Tab). Generally speaking, no - there's no central repository or suite of all actual device AVDs.
    Will there soon be a legitimate way to replace the Android lockscreen (with a lockscreen application)?
Due to the security implications, I'm not aware of any plans to make the lock screen (or in-call screen) replaceable.
    You mentioned better not to loose your signing key. But how to update your app, when your certificate expired?
For now, certificates used to sign apps launched in the Android Market need to expire after 22 October 2033. We'll have a solution for replacing these certificates in place well before 2033 :)
    What's the recommended way to implement a horizontally scrolling, virtualized list?
No simple answer here as it depends on the kind of data you're displaying, how long your list is, and what the best user experience would be. There are some good articles online (including this answer on Stack Overflow) that explain how to create a virtual list in a ListView, but you can use a similar technique within a Gallery or even a HorizontalScrollView to achieve a horizontal virtualized scrolling list.
    Are Shared Preferences the bast way to store small piece of data?
It depends on what kind of small data you're storing. Shared Preferences are the best way to store user preferences and Activity / Application state information.
    A view from one app needs to be updated by another app. Can't use the widget paradigm, is there any other way?
This depends on a number of factors. Are both apps written by you, or is one a third party? How dramatic are the changes? New layouts or changed text in a TextView?

Generally speaking, the best approach is likely to be a Broadcast Intent. You can package the data that will be used to update the View in the "other" app by including them as extras. The "other" app simply registers a Broadcast Receiver that listens for the Intent, extracts the data, and updates its view accordingly.
    How would you test/optimize the apps that are not meant for the Android Market?
The principle of using Analytics for tracking bugs and doing A/B testing works just as well internally as it would on apps that will launch in Market. The biggest difference is distribution. Given the ability to side-load apps onto most Android devices, I'd most likely setup an internal website that would host the APKs you want to distribute for the Beta test.
    How can we know if a certain service is already running?
You can bind to a Service using bindService without starting the Service. The Service Connection you pass in to bindService will notify you using its onServiceConnected and onServiceDisconnected handlers when the Service starts and stops. You can use those callbacks to set a variable within your code to check if the Service is running at any given time.
    Is there any option to backup the default SharedPreferences via BackupManager? Do I have to use the packagename?
The default SharedPreferences file getSharedPreferences uses the Activity's class name as the preferences name.
    Is there a way for accessories to "push" an embedded app or service package to the device so that specialized services for certain types of accessories will be able to automatically add functionality to the device when connected?
As part of the process of starting the device in accessory mode, you send identifying string information to the device. This information allows the device to figure out an appropriate application for this accessory and also present the user with a URL if an appropriate application does not exist. It won't install the package for you, but it will prompt the user to download it.
    Just to make sure, now we can send requests to the devices in order to update the info, instead of having the refresh intervals?
That's right, you can use Cloud to Device Messaging to ping a device when it needs to perform an update.
    When will we have a UI Builder that is par to what we get for iPhone?!
Check out this session on Android Development Tools for a preview of some of the cool stuff the tools team have been working on.
    Can you describe your video and control hookup for your android tablet?
I wrote a blog post that describes the video and control hookup I used to do my presentation using a pair of Motorola Xooms.

Monday, May 23, 2011

My Attitude Towards Piracy of My Book

The short answer: I am against it.

Lest I be accused of bias, that goes for every book - not just the ones that result in a couple of bucks landing in my pocket.

The long answer

I was surprised recently when asked via email what my attitude was towards piracy of my book, and if an online donation might work as a "last resort" way for pirates to show their appreciation for my work.

For the record, I am a big supporter of making my book available in as many formats as possible. That's why I'm impressed that Wrox books are now available on Kindle, Google Books, Safari, and PDF eBooks. I get a royalty no-matter where you buy it from, so if you want a copy pick wherever offers the cheapest price for the format you prefer.

I'm also against DRM - I believe that DRM does nothing to prevent piracy while annoying the folks who legitimately paid for the content - so I was also thrilled with Wrox's decision to make their eBooks DRM free.

Your book is expensive: Do you have a donate link anywhere to show my appreciation but save a few bucks?

I can't speak for anyone else, but I don't write my books for the money. The advance and royalties go some way to compensating for the significant time and effort it takes to get the books written - but for me at least, it's not going to make me rich or let me give up my day job.

More importantly I don't write in a vacuum. Books cost money to make. I'm not talking about the paper, printing, and transport costs, I'm talking about all the people who were involved in making my book the best it could be.

There are 17 people on the "Credits" page for Professional Android 2 Application Development. They are not vanity credits. As an example, the following folks are the ones on that list who I had direct, repeated email contact with over the course of writing the book. Apologies to those I left out - they are equally important to the process.
  • Scott Meyers (Acquisitions Editor) suggested I write a second edition and shepherded it through the process.
  • William Bridges (Project Editor) made sure I handed in chapters on something resembling a schedule (without him I'd still be working on the 1st edition), as well as dispensing invaluable advice on everything from book and chapter structure to clarity and semi-colon use.
  • Milan Shah (Technical Editor) reduced the number of bugs in my code.
  • Sadie Kleinman (Copy Editor) corrected my comma use, spelling errors, grammatical issues, and generally ensured I didn't embarrass myself.
  • Mary Beth Wakefield (Editorial Manager) kept it all together when things got chaotic.
  • Kyle Schlesinger (Proofreader) ensured nothing slipped past us during the many edits and revisions before it went to print.
  • Michael Trent (Cover Designer) gave us the awesome Terminator cover (image by Linda Bucklin).
  • Robert Swanson (Indexer) provided a way to find things without a photographic memory.
  • David Mayhew (Marketing) made sure it was available from wherever people wanted to buy it.
These folks are an absolutely essential part of the writing process, and they don't work for free. Nor should they. There is a really simple way to show your appreciation for all the people involved in writing a book. Buy it.

Sure, but I need to know what the book teaches for my job / class, but I don't have the money to buy it.

Good news! You don't have to! At the risk of hurting my own sales, you don't need to buy my book to learn how to develop Android apps. I mentioned this during my Android Protips talk: Google aren't trying to keep this information a secret. There's a huge amount of information available online including:
Many people find the structured, consistent, and guided form of a book to be a great way to learn new material. Others find books a more useful reference while working. If you're one of those people, and you want to be able to continue using books in such a way, buying them is the only way to help ensure that will happen.

What are your thoughts on 2nd hand books and libraries?

Bring them on! I've probably bought 1,000 books in my life - of which more than half are 2nd hand, and I've probably borrowed a few hundred from libraries too.

Electronic books introduce new challenges to the 2nd hand book market and libraries. I'm firmly on the side that says that the rights we have with paper books should be mirrored in the electronic publishing age. If you're done with a book you should be able to sell it, loan it, or give it away without restriction.

If everyone downloads pirated PDFs of books instead of buying them, publishers will stop publishing them.

Without a publisher many books won't get written or released. I don't have the time, money, skills, or inclination necessary to produce a book of sufficient quality on my own. I need the 17 people on the credits page (and several more besides) to publish each new book or revision.

Writing isn't my livelihood, so as an author the end of publishing would be a serious disappointment, but I'd just stop writing and get on with my day job.

As a reader? I can barely imagine a future so grim.

Monday, May 16, 2011

Android Protips: Where to Download the Slides and Code Snippets

For those of you who want to take a closer look at my Android Protips session for Google I/O, you can now enjoy the video, slides, and code snippets in whichever format you prefer:
One of the nice things about SlideShare is that it lets you embed slideshows into your blog post:


I plan to do a series of more blog posts that dig into some of the topics I cover in the presentation in more detail. Where do you guys think I should start?

Android Protips at I/O: The Session Video (and How I Presented It)

[Update 16/May: Reposted after Blogger outage]
[Update 2: Working links to the sessions slides are available from here]

Another Google I/O, another jam-packed Android session room. This year they nearly doubled the room capacity for the main Android track making space for 1,000 seats. That still wasn't enough though - once again people were sitting on the floor and lining up to get in.

Android Protips: Advanced Topics for Expert Android Developers

After delivering my Android Best Practices for Beginners for the better part of last year, I was really excited to take things up a notch and deliver some real advanced content. To push things one step further, I presented my session using a pair of Xoom tablets. More on that after the video.



The awesome video content was created for me by an old friend of mine (he's still young, but we've been friends since high school) pandamusk - thanks panda!

How did you do that?

There were a lot of questions on Twitter asking:
  1. What app did I use to do the presentation using an Android tablet
  2. How did I live tweet my own presentation in real time?
  3. How did I not re-tweet everything when the tablet rebooted?
I'm an engineer so (of course) I took this as an excuse opportunity to write an app that does the former and built in functionality to do the latter (and come on — you think I didn't consider the case of having to restart? Please.)

How does it work?

One app, running on two tablets, both running Android 3.1 (with USB hostmode support) connected via Bluetooth.

Tablet one was wired up with HDMI out and a USB-connected clicker let me transition between slides. I added a "finger paint" View with a transparent background on top of the ImageView that displayed each slide which let me do the real-time annotations.


A second device (out of sight on the lectern) showed me my "Speaker View": My speaker notes, the current / next slide preview, my pre-written live tweets, and a countdown timer.


The two devices were paired and connected over Bluetooth, with the speaker view tablet set up as a slave to the presentation device. Whenever the display tablet transitioned slides, it transmitted the current slide to the speaker view tablet. It works the other way around too, so I can transition slides on the speaker view and have the live view update accordingly.

The tweeting happened on the speaker view tablet based on slide transitions (with a button for me to disable it if — for example — I had to restart half way through). I connected this one to a wired ethernet connection using a USB to ethernet dongle to avoid the notorious conference wifi syndrome.

I've got a bunch of ideas I'd like to incorporate (particularly around remote viewing), but ran out of time before I/O to get them implemented.

Can I Get the App? Can I See the Source?

Yes and yes. I need to make a few improvements before I release it on the Android Market and I need to refactor and tidy the code before I open source it. In the mean time I'll do a couple more posts the go into more detail on how each of the components work. Stay tuned.

Tuesday, May 10, 2011

How to Get Your Android Protips

I/O is always a great couple of days, and after last year's jam-packed Android room they've doubled our capacity and given us space for 1,000 folks in the audience. As if that wasn't enough, we're also live streaming the Android (and Chrome) sessions for your viewing pleasure.

What Am I Presenting and How Can You Watch?

I'm presenting Android Protips: Advanced Topics for Expert Android Developers at 11:30am PDT in room 11 up on the top floor (next to the keynote room) for those of you lucky enough to be at I/O in person.

If you're not here, you can still watch my session live as it's going to be live streamed across the intertubes (Stay tuned: that page will update when I/O starts in a few short hours).

If you are planning to tune in, that's 7:30pm BST and an ungodly 4:30am on the East coast of Australia.

If you've got questions, and won't be in the audience, you can pose them (and vote for others) on the session's moderator page.

I'm also going to try live-tweeting my own presentation using an Android app I've been working on for presentations (more on that later).

Once I'm done, the recorded video and slides will be available on the Android Protips session page. I'll also post a link to the code snippets for your copy/paste pleasure.

If You Just Can't Get Enough (or You Want to Know How to Avoid Bumping in to Me)

I'm also co-hosting "Web Apps versus Native" on Wednesday afternoon with Michael Mahemoff. Should be a good way to wind down after a long couple of days. When I'm not on stage I'll be hanging out at the Android office hours, so be sure to stop by and say hi!

Wednesday, April 27, 2011

Using Twitter4J to Tweet in Android

So I'm working on a little project for Google I/O that requires, amongst other things, the ability to post status updates to Twitter from within an Android app. I asked about it on Twitter and a couple of people asked me to post the results (and associated code snippets) so here you go.

I was hoping for a small code snippet that would let me do that without needing any third-party libraries, but the feedback from the lazy web suggested that jumping through the hoops of an OAuth implementation myself wasn't worth the effort.

The wisdom of crowds suggested Twitter4J as a simple alternative - and as the following code snippet shows - the most simple case is pleasantly simple to implement.

Twitter twitter = new TwitterFactory().getInstance();
AccessToken a = new AccessToken(oauth_token, oauth_token_secret);
twitter.setOAuthConsumer(consumer_token, consumer_secret);
twitter.setOAuthAccessToken(a);
twitter.updateStatus("If you're reading this on Twitter, it worked!");


In this instance I'm the only one who'll be using the app, so I'm dropping an auth token and auth token secret unique to my own Twitter login rather than going through the process required to obtain a user-specific auth token. If that matches your use-case you can grab those values by clicking "My Access Token" on the Twitter developer site after you've registered your app.

You can download Twitter4J for Android here. Then just add twitter4j-core-android-2.2.1.jar into your project as an external JAR.

Tuesday, April 12, 2011

I'm Saying Goodbye to London

Where to next?

Mountain View in sunny California!

Following this year's Google I/O, I'll be relocating to the home of the giant dessert sculpture garden, where I've been given the opportunity to take on the role of Tech Lead for the global Android Developer Relations team.

It's a chance for me to focus on some more strategic ideas and to work more closely with the core Android engineering team. It's a challenge I'm really looking forward to.

I've spent the last 6 years in London - the last 2 working here at Google - and it's been an amazing experience. I'll be leaving the Android developers of EMEA in the very capable hands of Nick Butcher, Richard Hyndman, and Robert Rhode - and I'll still visit, I'm particularly looking forward to this year's round of Google Developer Days.

I'm still working at Google, and I'm still part of the Android team, so being based in Mountain View I'll have the opportunity to meet and work with some of our North American Android devs - so be sure to say hi if you're coming to Google I/O this year.

The move is still some months away, but in the mean time here are some of the things I will (and won't) miss about London, and what I'm looking forward to in California.

Things I'll Miss About London
  • World class theatre, restaurants, and concerts all at my door step.
  • Living in close proximity to the rest of Europe.
  • Proper bacon and real cheddar cheese.
  • Seasons (particularly Spring and Autumn).
  • The awesome Android developers I've worked with over the last 2 years.
  • Full English breakfasts.
Things I Won't Miss About London
  • Commuting for an hour every morning, and again every evening.
  • The Victoria line and South West Trains.
  • Hearing my neighbor snoring.
  • Driving in London.
  • Black pudding.
Things I'm Looking Forward to in California
  • Fruit that tastes like fruit.
  • Living on the West coast (the best coast).
  • Living in close proximity to an ocean.
  • Living in close proximity to the rest of the US.
  • Wide roads and cheap(er) petrol gas. 
  • American breakfasts.

Wednesday, March 30, 2011

My Failed Startup (or How I Nearly Become a 3D Animator)

Building awesome software and having the right business contacts is not sufficient to convince the latter to hand over money for the former.
There was a time in 2004/05 when, for several minutes, I thought my future lay not in compilers and debuggers, but in modelers and animation. As you can see, it turns out I don't have the skill, patience, or eye for detail required to transition from "enthusiast" to "someone who gets paid".


The journey that led me to consider adding "animator" to my resume is more interesting than my non-existent animation career. After 6 years writing oil & gas inspection software, I teamed up with a good friend and very smart guy - Big Stu - in a quixotic attempt to extract some serious coin from the bottomless money-pit that is the Western Australian oil & gas industry.

Step 1: Combine his electrical / mechanical engineering knowledge and business contacts with my ninja coding and amateur 3D animation skills to forge a killer app.
Step 2: ???
Step 3: Profit!

Here's our Pièce de résistance:


Our output wasn't Avatar, but the cinematic eye-candy was a side-effect of the tools we used rather than the goal.

We built a system to visualize and simulate anything in a sub-sea installation. Each scene was fully interactive, and the models were based on engineering diagrams and were perfectly accurate. The field layouts were created from sub-sea survey data to perfectly depict every twist and turn of the flow-lines and anchor chains. I've still never heard of a system that provides that level of detail and accuracy for sub sea environments.


Despite the power of the tool and the shiny eye-candy it produced, our venture never gained critical mass and eventually fizzled as Stu and I went our separate ways - Stu as the admiral of a veritable navy of ROVs, and me to London.

What follows is a look back at why a great idea generated zero profit.

Some companies are born of technology, some achieve technological greatness and some have technology thrust upon them

Technology is at the very heart of Google. Any chance to advance the technology of which it was born is seized upon as an opportunity for greater success. It's the philosophy behind our endeavor to "drive the web forward".

Like Google, the oil & gas industry has an absolute dependence on technology. It simply could not exist without an army of technologists creating oil-field prediction engines and well flow models.

Like super-heroes, you can learn a lot about industries from their origin stories

The Social Network and There Will Be Blood both include generous helpings of greed and betrayal, but while getting gypped out of half a billion dollars is a pretty bad day, it's still a significantly better outcome than having your head caved in.

Don't get me wrong, in the 6 years I worked in oil & gas I never once saw anyone beaten to death, so things have progressed significantly in the past hundred years or so. But in it's soul oil & gas isn't about technology; it's a business of hard bastards drilling absurdly deep holes into the earth's crust, praying to f**k it doesn't explode, all in the hope of wringing a few more drops out of the bottom of a rapidly emptying cup.

I drink your milkshake. I drink it up.
(Value of a resource * quantity of resource extracted) - cost of extraction = profit
Finding more of a scarce resource makes it, by definition, less valuable. It's nearly impossible to increase the quality of a natural resource, so the best way to increase profits is to decrease the costs of pulling it out of the ground.

As resources become scarcer, the difficulty (and cost) of locating and extracting said resources increases. At this point your dependence on technology increases, and that technology costs money.

At Google, technology is the product. Our success has come from search and advertising, but technologies like Android, Chrome, and cloud computing offer an opportunity for more success.

In oil & gas, oil & gas is the product - and technology is simply a tool necessary to extract it. This is fundamental, and it affects the way technologists are regarded within each industry.

What they want is fancier tools - not a new cost center.

Stu and I quickly discovered that while there is a bottomless pit of cash, it is allocated almost exclusively to parts of the business that generate revenue.

They will happily pay stupid money for is a shiny box that helps you find oil reserves, or one that lets you extract said nectar from Mother Earth. What they do not want is to pay the salary of a dozen engineers (software or otherwise) that build shiny boxes.

The significant supporting industries - everything from field inspections and environmental surveys to intervention engineering and remedial work - is all just costs. Most have been outsourced and the associated budgets minimized, allocated, and fixed. Entire companies are created through such outsourcing and their goals are to lower costs as far below the allocated budget as possible.

Our technology was about lowering costs - so we should have been golden, right?

The best technology in the world isn't valuable without a customer to sell it to.

The oil companies loved our technology. The shiny graphics are like catnip to executives, and our pitch was compelling:
Using this software, we can increase efficiency by shortening each job by up to 20%. We only charge 5% for using the software, giving you a net saving of 15%.
Big smiles and firm handshakes all 'round.
You need to go speak to Our Contractor. They should definitely be using this!
Next week we bring our roadshow to the Contractor. These guys wear coveralls for a living and recognize the smell of bullshit as it pulls up in the parking lot. They know the animated movies for the smoke and mirrors they are, but they're also engineers - so we switch our focus to the accuracy of our models. So far so good, until we get to the pitch:
Using this software, we can increase efficiency by shortening each job by up to 20%. We only charge 5% for using the software, giving you a net saving of 15%."
The smiles are gone and people are starting to fidget.

Offshore jobs tend to operate on a "daily rate". So our pitch translated into something like this:
Using this software we can shorten your billable days by up to 20% and increase your operational costs by 5%, giving you a net profit reduction of 25%."
Oil Companies outsource technology for a reason, and they're not going to force their contractors to use one particular piece of new, untried technology. The aforementioned contractors have every incentive they need not to use it.

The week-to-week possibility of Croesus wealth punctuated by imminent doom were good practice for later years.

That said, it was a great idea that would likely have succeeded given more time and effort. If I hadn't been in such a hurry to move to London, we could have worked the right deals to get the Oil Companies to convince their contractors to use our tools. It would have continued to be challenging, but it had a good chance. I believe it's inevitable that others will succeed where Stu and I left-off, but in startups - like much in life - timing is everything.

The lessons I learned about business, entrepreneurship, and opportunity have proven invaluable. The pressure and excitement of seemingly imminent success parallel to equally imminent crushing failure was a brutal introduction into the Real World after years spent hiding in the dark corner of my own coding universe. It's strange, but seeing something you pour your heart and soul into fail, can be better incentive to strive than unmitigated success.

I never did persue a career in animation. After taking half a year off to travel Europe I settled in London with my passion for coding reignited. Some four years later, I found a job that offers the perfect mix of business development, technology evangelism, and hardcore coding that plays to my strengths. Oh, and did I mention we're hiring?

Thursday, March 17, 2011

Using the New Android Market Stats for Fun and Profit

Earlier this week the Android Market Publisher site was updated to include some cool new statistics for your apps. You can now see the user distribution of your app in terms of the countries, languages, operating system versions, and devices on which your apps are running.

Better still, you can compare your app's distribution in each of these categories with the overall distribution for all apps in the Market.


What does this mean?

There are two axes for gaining insight from these figures:
  • The distribution of languages, OS versions, devices, and countries of your app users.
  • The variance between your app and the overall (expected) distribution.
I looked at the statistics for my three most popular / successful apps: Earthquake, Animal Translator, and Gyro Compass, and have the following observations, conclusions, and action items.

Action Items and Conclusions
  • Create a Japanese and Spanish translation of Earthquake.
  • Translate Animal Translator into Japanese.
  • Modify culturally sensitive place names for Korean users.
  • Confirm Earthquake works on small-screen devices.
  • Drop platform support for Android 1.5 and 1.6 on Animal Translator.
  • For new apps, it's may not be worth supporting Android 1.5 or 1.6.
  • For new apps, it's worth launching with localized language support for Korean and Japan.
  • When promoting apps, be aware of time-zones.
  • Build tablet-targeted versions now to get first-mover advantage.
Observations: Location and Language
  • All my apps do disproportionately well in the UK. I'm based in London, so it's likely that my tweeting and blogging have driven more people in my time-zone to my apps.
  • The proportion of Japanese and Korean users is effected by how long the app has been around. The older apps have disproportionately more US users and fewer Japanese and Korean users, so  for new apps it's worth building with Japan and Korea in mind at launch. 
  • Japanese users account for 10% of Animal Translator users (double the normal distribution). They clearly like the concept, so a japanese language version should help drive popularity.
  • Around 70% of Earthquake! users are from the US (expected distribution if 60%). This is likely due to a lot of Android users in the San Adreas fault cities of San Francisco and Los Angeles.
  • Earthquake has 1.5% South Korean users versus an average of 10%. Many South Korean users have complained about the USGS use of the name "Sea of Japan" which they believe should be "East Sea". This appears to have a direct impact on their usage of the app.
Observations: OS Versions
  • My apps show a trend where older apps have disproportionately more 1.5 / 1.6 users, and new apps have disproportionately fewer. This seems to suggest that owners of these older devices aren't downloading as many new apps. As a result, it might not be worth supporting 1.5 / 1.6 users for new apps.
  • Earthquake! already has 0.2% of users running Android 3.0. This suggests that building tablet-optimized versions now can give you first-mover advantage.
  • Only 8 people are running Animal Translator on a device running 1.6 or earlier, so I can probably drop support for for < 2.0 in the next update.
Observations: Devices
  • Based on the devices, there are no small-screen Earthquake! users. Does the app work on small screens?
  • The popularity of devices seems heavily affected by the country distribution of users. For my apps the HTC EVO 4G and Droid series of devices seem very popular in the US, with the HTC Desire and Samsung Galaxy S very popular in Korea and Europe.
What patterns did you see?

What observations and patterns did you find looking at your app statistics?

Friday, March 11, 2011

What Does a Magnitude 8.9 Earthquake Look Like?

Today Japan was struck by a massive 8.9 magnitude earthquake that caused major damage and loss of life. The quake hit off the coast which resulted in a tsunami which struck towns along the Northern coast of Japan and has resulted in tsunami alerts across the Pacific including as far away as the West coast of the US and Australia.

Seismological details on the quake are available from the Japan Meteorological Society and the US Geological Survey.

If you have friends or family in Japan, or you're in Japan and want to let people know you're ok, you can use the Google Person Finder

Aljazeera are streaming live coverage on YouTube.

In very real terms, these pictures from The Atlantic show exactly what an 8.9 magnitude earthquake looks like. My thoughts go out to everyone affected.

Some Visualizations

A magnitude of 8.9 is big. Very big.

The Richter scale is logarithmic, meaning an increment each whole number increase in magnitude represents a tenfold increase in measured amplitude. In real terms, that makes today's earthquake in Japan is around 500 times more powerful than the 6.3 magnitude quake that devastated Christchurch in New Zealand last month.
The following visualizations are screen captures from my Earthquake Android app. They attempt to give an idea of the scale (relative and otherwise) of the earthquake in Japan. They are approximate, using only the magnitude of the quake to determine the areas likely to be affected. Additional factors like depth of quake, fault lines, mountains, and landscape can significantly change the areas affected.
In the image below, the giant outer circle represents the area within which people were likely to have "felt something"during the quake. That's the better part of a hemisphere reaching as far as Brisbane in Australia and touching Alaska.

By comparison, the smaller inner circle is the same "felt" area for a 7.1 magnitude aftershock.


This next image represents the area at significant risk of suffering from structural damage due to the quake. Again, the larger circle represents the initial 8.9 magnitude quake and covers around three quarters of Japan - an area that represents most of the US West coast.

For comparison, the smaller circle centered around the 7.1 marker is the damage radius for the smaller aftershock.


Just as striking is the aftershocks that inevitably follow such a significant quake. The following image shows only the aftershocks measuring above 6 ("Strong: Can be destructive in areas up to about 160 kilometers") on the Richter Scale.


The overlapping areas all occurred within two hours of each other and give a sense of just how terrifying it must be for the people affected.

My hopes and best wishes go out to everyone affected by this catastrophe.

Monday, March 07, 2011

The Rise of the Tablet and the Innevitable Death of the Netbook

Last week I added a 10.1" Motorola Xoom to my gadget bag at the expense of a Netbook. As tablets grow in popularity I predict the Netbook's days are numbered.

Shortly after buying an Asus EeePC 701 in 2008 I described it to anyone who would listen as the best technology purchasing decision I'd ever made. It cost £200, was thin, light, and cheap. It booted Windows and loaded Office in under 10 seconds - only the paltry 800x600 display resolution was a legitimate cause of grief.

I used it to write most of my first book during my daily commute, and it was light and thin enough for me to throw in my bag for holidays or trips where I wasn't keen on bringing my laptop along (at the time my laptop was as 17" Vaio desktop replacement that weighed the better part of a metric fucktonne).

Light and with a full-day battery life,  Netbooks were a cheap second computer for lightweight computing tasks and surfing the web.

A one trick pony

Growing up, my parents ran a typewriter sales and repair company. I watched as the typewriter was gradually (and then very quickly) replaced with the desktop computer. For a small while "word processors" were a popular alternative - significantly cheaper than computers, and with most of the features of Word Perfect 5.1.

As PCs, laptops, and printers become cheap and ubiquitous, word processors grew more fanciful in an effort to compete. They offered more fonts and options but at a higher price. Before long, like most one-trick ponies, it was quietly covered with a sheet and put out of its misery.

I had a distinct feeling of deju-vu when late last year  I went in search of a replacement for my EeePC in the hopes of finding something cheaper, lighter, and a little faster. Instead I was presented with devices that were:
  • More expensive.
  • Thicker and heavier.
  • Slower to load and lacking SSDs.
At the same time, my new Macbook weighs around two kilograms and is no more than an inch thick. I can use it to write my book, write my code, edit photos, and pretty much anything else I could want to do.

It's true that a MBP is a lot more expensive than a Netbook - and bulkier - but it's not as though you would buy a Netbook instead of a real laptop. It's an additional device, so it's actually competing with tablets or smartphones - and a smartphone / tablet combo has a lot more to offer.

Smartphones and tablets make Netbooks a quaint irrelevancy

Modern smartphones, led by iPhone and Android, have largely filled the niche of mobile web browsing.

The arrival of the tablet is the final nail in the coffin, with a 10" tablet neatly filling the gap between smartphone and laptop.

With bright, high resolution displays, tablets offer an unparalleled experience for watching video. Games designed for tablets are created specifically for portable hardware featuring a touch screens and accelerometers. Similarly the rich ecosystem of apps is optimized specifically for smartphone and tablet platforms.

Typing on a 10.1" touchscreen is certainly no worse than typing on an undersized Netbook keyboard. Walking into meetings these days I'm increasingly finding people have left their laptops behind and are instead bringing along their tablets.

If you need to type, bring a laptop. If weight is an issue, bring your tablet

Tablets provide an optimized experience for portability, mobility, and touch-based input with a rich selection of apps and games designed with their size and power in mind.

Laptops are cheaper, lighter, and more powerful than ever before. They offer a rich ecosystem of apps and provide the perfect platform where text input is required.

Netbooks can still provide a great platform for getting online, but so can laptops and tablets. Laptops may one day give way to tablets and smartphones entirely, and apps may move entirely online, but Netbooks - like word processors in the 80's - will inevitably fall victim to competitors that offer a more dynamic ecosystem of apps, games, and features at an increasingly comparable price.

Monday, February 21, 2011

Mobile World Congress: Slides, Smoothies, Collectable Pins, and Gadgets Galore

On the scale on which these things are measured, Mobile World Congress doesn't have a reputation for being a "fun" event. Exciting, vibrant, interesting, and worthwhile - sure. But the number of suits and ties in attendance generally precludes the sort of party atmosphere people expect at events like SXSW or Google I/O.

Less fun, that is, until now

It turns out that if you want to see serious folks in serious suits take a ride down a slide all you need to do is build it: and they will come.

By 9:30 on Monday morning the pristine environment of the Android stand - tucked away in a corner of Hall 8 - was a heaving mass of developers, CEOs, reporters, and collectable pin enthusiasts.


The Android stand (here's some more pictures) at MWC was all about openness and inclusion. The highlight for me was the 40 or so 3rd party developers who (rightly) stole the show. They worked tirelessly, demonstrating their apps and showcasing just what's possible on the Android platform. Developers take note: this could be you next year.

Typically at MWC Tuesday is the busiest day, with Wednesday tapering off and Thursday seeing the halls empty and abandoned by midday. Not this year. The stand was packed every day from 9:00 when they opened the gates to 7 when they flashed the lights. Even on Thursday when most stands are rolling up the carpet after lunch, we had a full house until the lights went off at 4pm.


Android Gurus, 3rd party developers, and a device bar with over 80 different Android powered handsets kept the crowd entertained. The obligatory slide was in constant use, and free smoothies (the Honeycomb - flavored with honey and lychee - was my pick) were on offer served by a bevy of friendly antipodean bartenders, who towards the end of the event served as the kingpins of a roaring trade in collectable Android pins.

Have you got any pins?

So it turns out that all you need to transform a clean-cut three-piece-suited CEO into a screaming fanboi is the introduction of limited edition Android collectable pins.

What started as a curiosity on day one exploded into full-blown pin-mania by Tuesday. There were 86 of these on offer at MWC - here's a few of my favorites.


Of course what we're really here for is the gadgets

And we weren't disappointed. There were some great new handsets on display this year, including LG's fascinating Optimus 3D features a 3D display that doesn't require special glasses.

The Samsung stand was a gold mine of awesome sauce with the frankly stunning Galaxy S II and the Honeycomb-sporting Galaxy Tab 10.1 tablet. As usual the screens on these devices where gorgeous - and the 10.1" Galaxy Tab was surprisingly light - I'd like to spend a little more time with both.

Tablets were the big news of the show, with the Samsung Tab 10.1 and the LG G-Slate joining the Motorola Xoom as forthcoming tablet devices running Android Honeycomb. HTC's also announced their first Android tablet (the HTC Flyer), a 7" tablet that will apparently run Gingerbread before receiving an OTA update to bring it up to Honeycomb.

I'm a fan of HTC's industrial design, so I'm excited to see what they come up with in the tablet market.

A+++ Would attend again

Any trip to Barcelona means great food and plentiful drink and this visit was no exception.

While in Barcelona I had the great pleasure of hanging out with the folks who make up the Barcelona GTUG. These guys are as awesome as they are welcoming. MWC is famous for its extravagant parties but hanging out with these guys in a crowded local bar was a definite highlight.

Between the fun of the Android stand, the excitement of getting to play with new toys, and the gluttonous pleasure of Spanish cuisine it was an incredible experience. The only question now is how do we top it next year?

Only time will tell, but I saw the designers behind this year's stand sketching plans for a two story slide...

Wednesday, February 09, 2011

Strategies for Honeycomb and Backwards Compatibility

Each new Android release heralds two things: A raft of new developer APIs, and a chorus of questions on how to use them while staying backwards compatible.

Android 3.0 (Honeycomb) is notable in that it introduces Fragments, possibly the most fundamental change to how Activity UIs are constructed since Android 1.0. To add to the excitement, Honeycomb is also the first Android platform release optimized specifically for extra-large screen (tablet) devices.

The good news is that we plan to have the same fragment APIs available as a static library for use with older versions of Android; the plan is to go right back to 1.6.

The easiest short-term fix is to create separate sets of Activities
When the static Fragments library becomes available you'll be able to skip this step entirely (or simply deprecate these Activities from your application). 
The introduction of Fragments (and to a lesser degree the Action Bar) represents a significant change to the code the lives within your Activity classes.

The following technique demonstrates how you can  create two separate sets of Activities: one set that supports Fragments and another set that is designed to work without them.

To select the right set of Activities at runtime, you need to include a launcher Activity in your manifest that detects support (or lack thereof) for Fragments and then starts the appropriate Activity.

<activity
  android:name="InitialActivity"
  android:label="@string/app_name">
  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
</activity>


Within InitialActivity, you can use reflection to check if Fragments are supported on the current device.

  private static boolean fragmentsSupported = false;

  private static void checkFragmentsSupported() throws NoClassDefFoundError {
    fragmentsSupported = android.app.Fragment.class != null;
  }

  static {
    try {
      checkFragmentsSupported();
    } catch (NoClassDefFoundError e) {
      fragmentsSupported = false;
    }
  }


Then within onCreate forward the application to the "real" first Activity that either uses Fragments or not depending on the capabilities of the device.

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent startActivityIntent = null;
    if (!fragmentsSupported)
      startActivityIntent = new Intent(this, MainNonFragmentActivity.class);
    else
      startActivityIntent = new Intent(this, MainFragmentActivity.class);

    startActivity(startActivityIntent);
    finish();
  }
}


Because you're calling finish immediately after starting the new Activity, the back button behaviour of your application works as expected.

Within the MainNonFragmentActivity you simply inflate a layout resource that doesn't use Fragments

setContentView(R.layout.non_fragment_main);

While the MainFragmentActivity inflates a layout that does.

What about the rest of the Honeycomb APIs?

The upcoming static Fragment library means you probably won't need to implement the previous technique in order to use Fragments as the building blocks of your UI, but what about the other new Honeycomb APIs like the Action Bar and Animators?

Let's ignore the non-Fragment Activities and focus on the scenario where Fragments are available, but none of the other Honeycomb APIs are.

The first step is to determine the availability of the new APIs. You can implement the same exception catching technique I used above for each of the classes you wish to use, but I've found it simpler to bundle all the new APIs together and build only two variations:

  private static boolean shinyNewAPIsSupported = 
    android.os.Build.VERSION.SDK_INT > 10;

Maintaining two sets of Activities doesn't require a parallel set of Fragments, layouts and resources

Once again, I'm going to create a parallel set of Activities: One that uses the shiny new APIs like the Action Bar and animations, and another that uses traditional techniques to create a similar user experience.

The technique described above can be used in the same way - this time using the shinyNewAPIsSupported variable to determine which Activity to start.

Because most of the user-interface logic is contained within the Fragments rather than the Activity, these parallel Activities don't do much beyond inflate slightly different layouts. Where the Action Bar is available the Activity will handle the effect of navigation and action clicks. If the Action Bar isn't available, the layout used will likely incorporate a custom version that mimics its behavior.

Only the highlighted ActionBarFragment in the following snippet would be different between the pre- and post-Honeycomb app layout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <fragment class="com.paad.hc_backwards.ActionBarFragment"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"/> 
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <fragment class="com.paad.hc_backwards.SelectionFragment"
      android:layout_weight="3"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>
    <fragment class="com.paad.hc_backwards.ContentFragment"
      android:layout_weight="1"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>
  </LinearLayout>
</LinearLayout>


The key is that both sets of Activities will use the same fragments. Interaction between and within Fragments is usually maintained within each fragment, so only code related to the Action Bar (and other missing APIs) will need to be changed within the two Activity sets.

I expect all the apps I use on my phone to be optimized for tablets

Now lets take a look at the changes inherent in the introduction of the extra-large display. Fragments are designed specifically to make it easier to create flexible layouts, so I'm going to assume the existence of either Honeycomb or the static Fragment library when considering our options.

Device independent pixels (dp) and flexible layouts (like Relative Layout and Linear Layout) let your app scale to the dimensions and orientation of tablets. However, an app running on a 10" landscape device 1280 pixels across has a hell of a lot of whitespace when it was designed for a 4" portrait display at 480 pixels.

Consider the typical app design pattern where making a selection on one Activity determines what content is displayed another. Making a selection hides the selection Activity and displays the selected content.

Using Fragments you can easily construct layout variations for different screens

On a tablet it makes sense to position the selection and content Fragments within a single Activity, while on a phone only one should be visible at a time.

You can handle this as we did pre-Honeycomb by creating a res/layout-xlarge resource folder into which we put the side-by-side layout to use on an extra-large (tablet display).

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <fragment class="com.paad.hc_backwards.SelectionFragment"
    android:id="@+id/selection_fragment"
    android:layout_weight="3"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />
  <fragment class="com.paad.hc_backwards.ContentFragment"
    android:id="@+id/content_fragment"
    android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  </fragment>
</LinearLayout>


In practice, we'll usually want to define a portrait and landscape specific mode using port or land resource qualifiers:

res/layout-xlarge-port
res/layout-xlarge-land

For phones, we'll use the same Fragments, but the layout (stored in res/layout) would contain only one Fragment stored in a containing layout.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/selection_fragment_frame"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <fragment class="com.paad.hc_backwards.SelectionFragment"
    android:id="@+id/selection_fragment"
    android:tag="full_screen_fragment"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />
</FrameLayout>


Within our code this produces a dilemma

The selection and content Fragments will interact slightly differently in phone or tablet mode. In both cases, making a selection should be reflected in the content Fragment - however in the phone layout this should also replace the selection Fragment with the newly updated content Fragment.

public void makeSelection(int i) {
  boolean extraLargeScreen = getResources().getConfiguration().screenLayout >
                            Configuration.SCREENLAYOUT_SIZE_LARGE;
  if (!extraLargeScreen) {
    FragmentTransaction ft = fragmentManager.beginTransaction();
    ft.hide(selectionFragment);
    ft.add(R.id.selection_fragment_frame, contentFragment);
    ft.addToBackStack(null);
    ft.commit();
  }
  contentFragment.setSelection(i);
}


Note that by calling addToBackStack we ensure that pressing the back button will undo this transaction, hiding the content Fragment and displaying the selection Fragment.

Fragments are a great way to componetize your UI

The new Android 3.0 (Honeycomb) SDK introduces a number of great new APIS, many of them designed to make it easier to build tablet version of your apps by providing a flexible mechanism for building different layouts depending on screen size and orientation. The availability of a static Fragment library will simplify the process of creating flexible layouts that are backwards compatible.

It is my firm belief that any app developed for mobile should be available for tablets. When I put my credentials into a shiny new tablet, I expect it to install all the apps I use on my phone - and I expect all of them to be optimized for the tablet form factor.

That's not to say you shouldn't create apps that are designed to work only on tablets, but I believe these tablet-specific editions should be made available side-by-side with phone versions that have been optimized to work on tablets.

Wednesday, February 02, 2011

Android Web Market, In App Billing, and Buyer Currency

Today during the Android Honeycomb Event we launched a couple of really exciting new features Android. As well as a closer look at what's possible with the Honeycomb SDK, we also announced:
There's more details on all three at the Android Developer Blog, and you can watch the launch event on YouTube.

Web Based Android Market

This is long awaited and seriously cool. Finally we developers have a homepage on the web for our Android apps. Not only that, but now we can install apps OTA simply by pressing install and the app of our choice will be automagically pushed to our phone.

My question to you: Have you uploaded the 512x512 alpha blended app icon and 1024x500 full bleed feature graphic? If the answer is no, then you have (at best) a 72x72 icon stretched into jaggy hell representing your app to would be users. That's probably something you want to do something about sooner rather than later.

To celebrate web landing pages for apps I've put together this list of the apps that I've been using on my Android devices.

Buyer Currency Support

You can now specify different prices for different currencies - and even more importantly, as a result users will always see the app priced in their local currency. No more "~" symbols or strange foreign currencies.

In App Billing

More ways for developers to monetize their apps can only be a good thing. A simpler purchase process for users benefits everyone.