Wednesday, December 19, 2007

On the Road with Android

This week finds me at the Google offices in jolly old London after a quick dash out to Belgium last week. I have had the chance to meet the Mobile developers based here in London and give them an introduction to Android, as well as do the same for 70ish external developers from the London area. It has been a fun week of Android hackathons, brainstorming for Android application ideas and occasionally finding bugs and holes in the documentation.



It has been really valuable spending enough time with a group of motivated developers to move beyond the first steps and into real development work. A couple of my temporary office mates here are already well on their way to implementing a general puzzle application for Android. It will enable you to choose your favorite puzzle engines to install and then play a selection of puzzles downloaded on demand from a server – quite an ambitious project for a first try, but these guys are pretty determined and hope to have a prototype of the first puzzle (battleships) working before I hit the road again on Friday. They are also treating the implementation as a chance to learn the architecture: learning the right way to use the architectural pieces in Android rather than opting for the quick and easy shortcuts, which is the best way to really learn a new platform in my experience (don't compromise, be true to your vision).



The week is far from over yet, with another internal and external hackathon planned, and as many more ideas sessions as we can cram in.



As for the London offices – well they are fantastic. Right in the middle of everything, Jaffa Cakes in the kitchens (if you don't know what a Jaffa Cake is, or how to eat one in particular, check out this informative video on the subject). There are also a wealth of pubs within easy walking of the offices, a welcome feature for an ex-pat like me.



With the holidays getting close, don't forget that a new SDK version was announced last week with several improvements. It might be worth grabbing that before taking off for the holidays, just in case you get the urge to do some Android coding while trying to work out if you ate just a bit too much for dinner.



Happy Holidays...

Friday, December 14, 2007

Life can be tough; here are a few SDK improvements to make it a little easier

It's been just over a month since we gave developers the first early peek at the Android SDK. We've been hard at work since then on some nifty new stuff we think you'll really like. We hope to show that to you soon, but in the meantime, we wanted to fix some of the important issues you've raised. We're very pleased to announce the immediate availability of m3-rc37a. (What a great name for a droid!)



Our servers are quivering in anticipation of the opportunity to deliver these bits fresh to your desktop. Don't be shy! But if you need further enticement to download the new version, here are a few of the improvements you'll find therein:




  • The new default skin for the emulator is HVGA, portrait mode. That's the one you should focus on for your submissions for the Android Developer Challenge.

  • We've added the ability to inject SMS messages into the emulator, which will allow you to more easily test IntentReceivers for incoming SMS messages.

  • The choppy audio problem in the emulator on Windows should now be solved.

  • There's a new emulator control panel that you can use to control network events like radio state changes and incoming calls.
  • The Eclipse plugin now does color syntax highlighting on the XML files, such as AndroidManifest.xml.

  • Some of the more annoying bugs in the Eclipse plugin have been fixed; for instance, the application launcher retries if the first try times out while waiting for the emulator to start, and "R.java" files are no longer flagged as read-only.



You can find a full list of changes for this and every release at the Release Notes page. If you're looking for tips on upgrading your SDK installation, we have those too.



We hope that these humble tweaks make your life just a little bit better, or at least, the part of your life you spend writing code.

Wednesday, December 5, 2007

Google Developer Podcast: Android



Dianne Hackborn and Jason Parks are two of the architects on the Android engineering team, and in this podcast they talk to us about the Android platform from a technical perspective.



Dianne and Jason share a background at both Be and PalmSource, and talk about how that experience has been applied to Android. Other topics covered include:




  • Some history behind the project

  • The high level architecture of Android. For example, how Linux processes handle the VM and manage security (the VM doesn't handle it)

  • Details on the Dalvik VM and how it is optimized for small devices

  • The architecture: From Intents to Views to Permissions and more

  • How XML is slow, but the tools convert the XML to a nicer format for you

  • The tooling and steps for building an application on Android

  • How so many objects have a URL, and how the environment is like a mini-SOA (Services across processes instead of across the network)

  • Thoughts on how you program for small devices, and things to watch out for if you move from the desktop

  • The control, or lack of control that you have over the application lifecycle

  • "Everything you do drains the battery"

  • The thread story: they exist, you don't have to deal with them if you don't want to, and the UI

  • Using XMPP for messaging



You can download the episode directly, or subscribe to the show (click here for iTunes one-click subscribe).

Thursday, November 29, 2007

A Maze of Twisty Little Passages



The end of last week was Thanksgiving in the US, the tradition is to be with family, eat too much food and watch football (not necessarily in that order).



Apparently some folks took the chance to work on Android projects too. We are highlighting a few of the projects that caught our eye.



One of the coming of age rituals of any new platform is the porting of the Z-machine – the interpreter used in the Zork series of games from Infocom. Now Android has the Z-machine thanks to sussman and mariusm. The project, called Twisty, is available on Google code hosting. Thanks for the lost productivity you guys.



Testing is also a hot topic on our Google groups. While JUnit is bundled with the Android SDK to make it possible to do unit testing, there are many other kinds of testing, like automated acceptance testing. Positron builds on the Android instrumentation features from the SDK to make automated acceptance testing of Android applications possible. The author, phil.h.smith, has a pretty good introduction on how to use Positron as well.



Plugins for other IDEs are another favorite on the Android Google groups. While there are only rumblings about a NetBeans plugin at present, the idea-android project already has an early release for IntelliJ IDEA thanks to aefimov.box and intelliyole.



Dion Almaer also picked up on a crossover GWT/Android project which looks pretty amazing too. Chronoscope is an open source charting and visualization library written in GWT. The team were able to take the library, and with 8 hours of playing with Android, had a port to the Android platform.



Of course, there are many more Android projects springing up all the time, as a search of the android label on Google code hosting will demonstrate. It's great to see all this activity just a couple of weeks after the SDK was released.

Tuesday, November 20, 2007

A Stitch in Time



Background: While developing my first useful (though small) application for Android, which was a port of an existing utility I use when podcasting, I needed a way of updating a clock displayed on the UI at regular intervals, but in a lightweight and CPU efficient way.



Problem: In the original application I used java.util.Timer to update the clock, but that class is not such a good choice on Android. Using a Timer introduces a new thread into the application for a relatively minor reason. Thinking in terms of mobile applications often means re-considering choices that you might make differently for a desktop application with relatively richer resources at its disposal. We would like to find a more efficient way of updating that clock.



The Application: The rest of the story of porting the application will be detailed in future blog entries, but if you are interested in the application in question and the construction of it, you can read about it in a not-so-recent Developer.com article about using Matisse (a GUI builder for Swing). The original application is a Java Swing and SE application. It is like a stopwatch with a lap timer that we use when recording podcasts; when you start the recording, you start the stopwatch. Then for every mistake that someone makes, you hit the flub button. At the end you can save out the bookmarked mistakes which can be loaded into the wonderful Audacity audio editor as a labels track. You can then see where all of the mistakes are in the recording and edit them out.



The article describing it is: http://www.developer.com/java/ent/print.php/3589961



In the original version, the timer code looked like this:



class UpdateTimeTask extends TimerTask {
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;

timeLabel.setText(String.format("%d:%02d", minutes, seconds));
}
}

And in the event listener to start this update, the following Timer() instance is used:

if(startTime == 0L) {
startTime = evt.getWhen();
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, 200);
}


In particular, note the 100, 200 parameters. The first parameter means wait 100 ms before running the clock update task the first time. The second means repeat every 200ms after that, until stopped. 200 ms should not be too noticeable if the second resolution happens to fall close to or on the update. If the resolution was a second, you could find the clock sometimes not updating for close to 2 seconds, or possibly skipping a second in the counting, it would look odd).



When I ported the application to use the Android SDKs, this code actually compiled in Eclipse, but failed with a runtime error because the Timer() class was not available at runtime (fortunately, this was easy to figure out from the error messages). On a related note, the String.format method was also not available, so the eventual solution uses a quick hack to format the seconds nicely as you will see.



Fortunately, the role of Timer can be replaced by the android.os.Handler class, with a few tweaks. To set it up from an event listener:



private Handler mHandler = new Handler();

...

OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
};


A couple of things to take note of here. First, the event doesn't have a .getWhen() method on it, which we handily used to set the start time for the timer. Instead, we grab the System.currentTimeMillis(). Also, the Handler.postDelayed() method only takes one time parameter, it doesn't have a "repeating" field. In this case we are saying to the Handler "call mUpdateTimeTask() after 100ms", a sort of fire and forget one time shot. We also remove any existing callbacks to the handler before adding the new handler, to make absolutely sure we don't get more callback events than we want.



But we want it to repeat, until we tell it to stop. To do this, just put another postDelayed at the tail of the mUpdateTimeTask run() method. Note also that Handler requires an implementation of Runnable, so we change mUpdateTimeTask to implement that rather than extending TimerTask. The new clock updater, with all these changes, looks like this:



private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
final long start = mStartTime;
long millis = SystemClock.uptimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;

if (seconds < 10) {
mTimeLabel.setText("" + minutes + ":0" + seconds);
} else {
mTimeLabel.setText("" + minutes + ":" + seconds);
}

mHandler.postAtTime(this,
start + (((minutes * 60) + seconds + 1) * 1000));
}
};


and can be defined as a class member field.



The if statement is just a way to make sure the label is set to 10:06 instead of 10:6 when the seconds modulo 60 are less than 10 (hopefully String.format() will eventually be available). At the end of the clock update, the task sets up another call to itself from the Handler, but instead of a hand-wavy 200ms before the update, we can schedule it to happen at a particular wall-clock time — the line: start + (((minutes * 60) + seconds + 1) * 1000) does this.



All we need now is a way to stop the timer when the stop button is pressed. Another button listener defined like this:



OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
};


will make sure that the next callback is removed when the stop button is pressed, thus interrupting the tail iteration.



Handler is actually a better choice than Timer for another reason too. The Handler runs the update code as a part of your main thread, avoiding the overhead of a second thread and also making for easy access to the View hierarchy used for the user interface. Just remember to keep such tasks small and light to avoid slowing down the user experience.



So that's it for the first of what will be a series of Android tips. Hopefully this will save you a little head scratching on what will probably be a fairly common thing to want to do (i.e. make something happen or update at regular intervals in a lightweight way in your application). There is plenty of more material from my experience of porting this very simple application which will be covered in some of the future "tips" articles. There are some other great tips being discussed as well as an opportunity ask questions at the Android Developers Discussion Group.

Friday, November 16, 2007

Android: the first week

Wow, what a week! The response from the community on Monday's Android SDK release has been overwhelming. Our forums have been flooded and we're glad to be helping people dig in writing new applications.



A handful of quick notes for this Friday evening:




  1. We've released a quick point-revision of the SDK to fix some high-priority issues. You can now download M3-RC22a and read the release notes. Don't forget to get Eclipse to update the ADT plugin.


  2. A couple of good articles on the web for your reading pleasure:



  3. Finally, we've split our forums into topic areas to make them a bit easier to manage. Be sure to check out the details and join the discussion.



Have a great weekend, and happy Android coding.

Tuesday, November 13, 2007

Just show me the code

OK, you've downloaded the SDK and are now ready to build the next killer app for mobile (and maybe win some $$$ in the process ;)



Activities? Intents? SimpleCursorAdapter? Huh? Hmm...how do I proceed?



Well, that depends on your style. Some will want to carefully go through all the documentation top-to-bottom, while others may prefer to just dive right into code.



Either path will eventually lead to the sample applications provided in the SDK — these samples will be invaluable in your quest for Android mastery. The samples include:




API Demos

A 'kitchen sink' application that covers the most useful aspects and components of the Android APIs. You'll see different implementations of Activities, Services, Notifications, Layouts, as well as methods for working with graphics and text. This application provides a good source of templates for your projects as well as a reference to 'How do I do this?'-type questions.


Lunar Lander

A game which demonstrates how to load and draw graphics, animation techniques, taking user input, saving state when the user pauses the game, and more. Coding shouldn't be this fun!


Note Pad

You'll learn how to use Intents to open a new screen, access a local database, and more. This sample is a good introduction to application flow and life cycle management, which are vital in developing more complex applications.



Source code and resources for these applications are available in the SDK (samples/) as well as online: http://code.google.com/android/samples/



Here are some suggestions on what to do next:




  • Read through each application's manifest file (AndroidManifest.xml) to learn about the typical structures in an Android application.

  • Modify the code to familiarize yourself with the building and testing process.

  • Use a particular code snippet as either a base template or to get some needed functionality for your own project (why reinvent the wheel?)



Put these sample applications through their paces; and if you get stuck, please post your questions to the Android Developers Discussion Group.

Monday, November 12, 2007

This is the droid you're looking for

Following last week's announcement of the Open Handset Alliance, today we're happy to offer an early look at the Android SDK. We're eager to get feedback from lots of developers in our discussion group. We're also providing developer documentation and this blog to help you get up and going.



You're probably wondering about what's available today. This preview of the SDK will allow you to develop Android applications that you can run, test, profile, and debug using the emulator and the other included tools. Note that the look and feel of the user interface in the emulator is a placeholder for a final version that is under development.



One of our goals in releasing the Android SDK is to unleash the creativity of application developers on the platform. We'd also like to get feedback early enough that we can make changes before the first Android-powered devices are available to the public. We plan to release updates to the SDK regularly which means that there will be additions and changes to the APIs and user experience — subscribe to this blog to stay up to date.



We're really looking forward to seeing all the amazing applications that developers will create on an open mobile phone platform. In fact, you may even want to enter your application into the Android Developer Challenge — a USD$10 million challenge sponsored by Google to support and recognize developers who build great applications for the Android platform.