Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Monday, September 17, 2012

Significant keep-alive performance flaw in iOS' NSURLConnection

The problem

I've recently done a lot of research to understand a perplexing performance problem haunting the iOS port of a commercial component I maintain at work (originally developed for Android).  Specifically, the problem presents itself when the user navigates repeatedly to a specific screen in the application which issues an HTTP HEAD request (via HTTPS) to determine if a particular static resource has been modified.  Normally, you would think, a quick and light-weight operation.

However, the performance penalties we were seeing in this simple usage of NSURLConnection was a measurable delay of approximately 600ms, despite a round-trip time to our servers of only ~80ms over our local Wi-Fi network.  Now I'm sure at this point a well informed reader is going to exclaim: but wait, this is HTTPS, there's a well known and significant handshaking penalty versus HTTP!  Of course, this same penalty exists for our Android version of the application, however this workflow on Android does not present any significant delay.

So, what's going on?

The short answer: the connection has been closed.  While NSURLConnection does support HTTP keep-alive, it has a client-imposed timeout of just 12 seconds even for HTTPS.  This may seem like a reasonable timeout when you look at the problem with 1995 goggles: loading a complete web page efficiently without requiring a separate connection for each resource on the page.  However, in today's world the model is much richer.  Web services dominate the landscape of mobile applications (even when the browser is the client), using the web for more discrete data exchange where appropriate and moving the rest client-side.

And this data exchange frequently happens over HTTPS.  Borrowing from Google's own SPDY proposal: the future of the web depends on a secure network connection.  SPDY requires SSL and yet is designed for efficiency.  A paradox only if you don't embrace long keep-alive timeouts.

Does it matter?

The practical implication of NSURLConnection's short timeouts for users is a noticeable but not immediately reproducible delay experienced within applications that utilize web services over HTTPS.  A common user scenario making for an easy repro case on a large number of mobile apps out there (go ahead, try yours) is the login screen.  Logging in implies a secure connection, and often users are expected to take some time to awkwardly type their cat's name: Mr!Cuddl3s.  I timed myself with this exercise: 13 seconds.  In this amount of time, any HTTPS connections already opened to your application's domain have been closed and so here comes the 600ms+ SSL connection penalty before the user sees a frustrating message: "Your username or password does not match".  Returning to the input field, you recheck your username, delete the password, and start again.  If you were fast enough, you're quickly ushered off to the main screen for the application.  If, however, you took more than 12 seconds again to retype things, you will see that penalty one more time.  This is likely to repeat many times in the user's interaction with your application: idling on various screens reading content, setting the phone down for just a moment, etc.

TCP/SSL handshaking overhead shown in the Amazon Mobile app (Android  left, iOS right)
The above image and linked YouTube video demonstrates the impact from the user's perspective of the 12 second connection timeout.  As you see, the first request is much slower on iOS because Android has re-used the previously established HTTPS connection set-up through prior interaction with the app.  Subsequent requests are identical in performance until after the user idles for 12 seconds again, bringing the favor back to Android once again.

But what about optimization best practices?

There is significant precedence on the web suggesting that this is not a reasonable default.  A variety of libraries that I sampled do not exhibit this behaviour (Apache HttpClient, Android's implementation of HttpURLConnection, and serf).  None had such a short timeout, let alone even a client-initiated shutdown at all.  The same conclusion holds true for HTTPS servers in production: a sampling of Google, Facebook, and Amazon servers suggest they are all willing to let HTTPS connections linger for minutes, not seconds.

Surely there is some reasoned thinking behind this behaviour, right?  Well, perhaps.  I can find little material publicly available except a brief thread on Apple's Mac Network Programming mailing list where an Apple engineer draws the conclusion that the closure is to support the radio's ability to enter an idle state.  While it is true that cellular radios have complex power saving state management (searching the web for material on Radio Resource Control [RRC] or Fast Dormancy has no shortage of white papers), I question the argument that the connection closure truly is in alignment with the details of the radio.

The first piece of evidence against this comes from the nature of RRC's lack of specificity or standard on timing windows.  Apple simply cannot know whether the network would ask the device to enter this idle state in 2 seconds, 10 seconds, or 15 seconds.  So a naive, hardcoded timeout of 12 seconds is seemingly just as likely to incur the worst possible performance as it is the best.

Furthermore, the hardcoded timeout is consistent between 3G and Wi-Fi connections which of course have very different radio stacks and performance optimizations.  In the case of Wi-Fi, this appears to have even changed significantly from iOS 4 to iOS 5, with no change to NSURLConnection's behaviour.  In my  extremely informal testing on iOS 5, I found that the radio entered a low power state in just a few seconds, indicating that the radio is to resume normal operation to handle the connection closure if the user switches off the screen just a few seconds after an HTTP request.  Hardly an edge case.

Admittedly, we're getting into white paper territory ourselves here to properly and convincingly prove that this timeout harms battery life (let alone carrier network performance!).  I'm not prepared to go through that much rigor just yet.  Instead, I'd like to simply make a call to Apple to reconsider this behaviour and re-evaluate their own internal research.  And, if you're reading Apple, please feel free to reach out to me if there is interest in a thorough and more academic study on this topic.  I'd be happy to help.

What next?

NSURLConnection is intentionally opaque, offering no features to customize the underlying mechanics, making it easy for Apple to adjust them without fear of breaking backward compatibility.  Unfortunately this means that there's no convenient way to work around the problem if your app uses NSURLConnection.  While it is possible to switch to a third party such as ASIHTTPRequest, I don't personally recommend this approach as this transition makes it more difficult for Apple to implement or enforce reasonable connection management policies.

The API is designed for Apple to implement best practices, so let's ask that they do exactly that.

Tuesday, April 13, 2010

Logcat, Improved.

Logcat is a staple for most Android developers out there and I'm certainly no exception. I often have at least one terminal dedicated to logcat with sometimes many more with various combinations of options to control how I'm filtering the output.

Recently it occurred to me that most of this work is designed to separate my program from the noise of the entire platform. The numeric argument printed after the tag in the logcat output is the pid responsible for that log line which I had used in the past to do this sort of filtering but it was a pain when the app crashed or was reinstalled because the pid would change.

Enter my proclogcat script. This script tracks the pid as the process is killed and restarted and takes care of automating the adb shell ps | grep <process> logic on first launch. The best part is the script can be combined with Jeffrey Sharkey's excellent coloredlogcat script (or my modified version of it) for beautiful results.



Download: proclogcat

To use, simply copy it somewhere in your PATH and invoke either manually as adb logcat | proclogcat <process> or in a function as is discussed in the script source code.

Tuesday, December 15, 2009

Gracefully supporting multiple Android platform versions in a single release

The Android platform has been aggressively updating since version 1.0 and now we're starting to a see a much more interesting mix of device types, manufacturers, and even platform versions out in the wild. Unfortunately sometimes this can be frustrating for developers wanting to look forward to support new features and conveniences, but to still support devices that are on longer update cycles (like with the G1).

The pattern shown here will deal with multiple platform versions although can easily be applied in other situations. First of all, let's start with a preface about minSdkVersion, targetSdkVersion, and the Eclipse target platform. The *SdkVersion attributes are defined in the manifest <uses-sdk> tag and define the minimum platform version your app can be installed onto (and tested on!), and the highest version that you tested to and were aware of during development. It is important that you test your application on all versions between and including min and target. The Eclipse target platform is the specific version that Eclipse will be compiling against, this is what permits us to compile code that actually does link specifically against the newer platform features. This is usually set the same as your targetSdkVersion.

Now let's consider a practical example of a music player application which needs to implement a service in the foreground state during playback. Prior to API level 5, this was done with the Service.setForeground call, but level 5 and beyond deprecated this method due to widespread abuse. Instead, a new method was introduced (Service.startForeground) which can be used to achieve this affect as well as setting an ongoing notification in the status bar. In many ways this is handy as the notification and foreground state were naturally already tied together, now there's an API combining them. But problems start when you try to test new code using this method on platform versions below 2.0 (API level 5). Specifically, Dalvik will throw a VerifyError when attempting to initialize the class containing the call to startForeground for the first time, even if the call is in a conditional statement. This method does not exist on pre-2.0 devices, and so cannot be included in your code in this way.

A naive approach would be to simply use reflection to test for and execute startForeground, but thankfully Java offers a much more elegant design pattern for just this sort of thing. The basic idea is to create an abstract API that the rest of your application can access which hides the specific implementation of what's being performed, and does so in such a way that prevents the VM from initializing an unsupported class on an older platform. So you might try defining something like this:


public abstract class PlayerNotification {
public static PlayerNotification getInstance() {
if (Integer.parseInt(Build.VERSION.SDK) <= 4)
return PreEclair.Holder.sInstance;
else
return EclairAndBeyond.Holder.sInstance;
}

public abstract void showNotification(Service context, int id, Notification notification);
public abstract void hideNotification(Service context, int id);

private static class PreEclair extends PlayerNotification {
...
}

private static class EclairAndBeyond extends PlayerNotification {
...
}
}


Now your service could be modified to make use of this new abstract API as such:


public MyService extends Service {
private static final int NOTIF_PLAYING = 1;
private final PlayerNotification mNotification =
PlayerNotification.getInstance();

...

public void setForegroundAndShowNotification(Notification n) {
mNotification.showNotification(this, NOTIF_PLAYING, n);
}

public void stopForegroundAndHideNotification() {
mNotification.hideNotification(this, NOTIF_PLAYING);
}
}


Great, this sounds very simple and easy to follow. Let's return to the full implementation of PlayerNotification:


private static class PreEclair extends PlayerNotification {
private static class Holder {
private static final PreEclair sInstance = new PreEclair();
}
private NotificationManager getNotificationManager(Context context) {
return (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
public void showNotification(Service context, int id, Notification n) {
context.setForeground(true);
getNotificationManager(context).notify(id, n);
}
public void hideNotification(Service context, int id) {
context.setForeground(false);
getNotificationManager(context).cancel(id);
}
}

private static class EclairAndBeyond extends PlayerNotification {
private static class Holder {
private static final EclairAndBeyond sInstance = new EclairAndBeyond();
}
public void showNotification(Service context, int id, Notification n) {
context.startForeground(id, n);
}
public void hideNotification(Service context, int id) {
context.stopForeground(id);
}
}


And that's it as far as code goes! Assuming that you have already updated your AndroidManifest.xml to include the appropriate <uses-sdk> attributes, you're ready to start testing. Use the Android SDK tools to create AVDs for each of the major platform releases from your minimum supported version to your current target and deploy your app on each to make sure you have not made any mistakes.

For further reading about how Java guarantees this approach, read about the initialization on demand holder idiom. This is what allows us to prevent the wrong implementing class from initializing in the VM (and thus causing verification errors).

You can find two working examples of this pattern in my Five app: one using reflection and one matching the explained example

Tuesday, March 17, 2009

Building, running, and debugging Android source

There is a lot of confusion surrounding the work flow in the Android source tree, so allow me to simplify:
  1. Follow the initial instructions for downloading the source at:

    http://source.android.com/download

  2. Set up your environment to build the engineering build for the generic device and generic product. This is similar to the SDK, but with a few pieces missing.

    $ source build/envsetup.sh
    $ lunch 1

  3. To build for the first time:

    $ make

    If you have a multi-core system, you can build with make -jN where N is twice the number of cores on your machine. This should speed up the first build considerably.

  4. To launch the emulator from your build:

    $ ./out/host/<your-machine-type>/bin/emulator

    On my system <your-machine-type> is linux-x86.

    NOTE: The emulator knows where to find system and data images as a result of running lunch 1 above. This sets the environment variable ANDROID_PRODUCT_OUT to point to the target directory. For this example, it should be out/target/product/generic/.

  5. If you wish to make changes to the source code, there are handy utilities that have been exposed to your environment by source build/envsetup.sh above. For example, if you modify the Email app and just want to rebuild it:

    $ mmm packages/apps/Email

  6. To see your changes in the emulator you can run:

    $ adb remount
    $ adb sync


    Which will copy the regenerated Email.apk file into the emulator's /system/app folder, triggering the PackageManager to automatically reinstall it.

  7. Or if you change framework resources in frameworks/base/core/res/res/ you could regenerate framework-res.apk with:

    $ mmm frameworks/base/core/res

    Or if you modified even the framework itself you could run:

    $ mmm frameworks/base

    To sync these changes you must restart the running framework and sync, as with this handy sequence:

    $ adb remount
    $ adb shell stop
    $ adb sync
    $ adb shell start

  8. Finally, to debug your changes you can use the DDMS tool to select a process for debug and then attach Eclipse to it. If you have the Eclipse Android Development plugin installed, there is a special DDMS perspective which you can use to choose the process for debug. To attach Eclipse to it, see these instructions:

    http://source.android.com/using-eclipse

    This document also describes how to use Eclipse for development. Any IDE should work with the proper finagling though. Just note that the IDE won't really be an integrated environment: the final output of APKs, system.img, and even the generation of R.java files will have to be done by make!

    A note about the processes in Android:

    • system_process houses all things under frameworks/base/services. This includes the PackageManagerService, StatusBarService, etc. It has many, many threads (one for each service, and then one main UI thread), so be wary when debugging.
    • com.android.acore hosts Launcher (home), Contacts, etc. You can determine the apps/providers that run here by looking for android:process="android.process.acore" in the various AndroidManifest.xml files in packages/.

    Also remember that the "framework" (under frameworks/base/core/java) is not hosted by any one process. It is a library used by most processes, so to debug code there you can usually use a simple demo app that takes advantage of whatever you changed and debug that app's process. A useful trick for setting up your debug connection is to call Debug.waitForDebugger() during some startup part of an application or system service.

UPDATE 2009-07-24: The original ONE_SHOT_MAKEFILE line I gave for rebuilding the framework has been deprecated. mmm frameworks/base is now the recommended way to rebuild the framework code.

Wednesday, August 27, 2008

Generate Callback Listener Helpers from AIDL

As I redesign Five I find myself tweaking/expanding the callback listeners in my interface which are handled through the RemoteCallbackList class in the service implementation. This class is great, however for each call code must be written similar to:

int N = mCallbacks.beginBroadcast();

for (int i = 0; i < N; i++) {
try {
mCallbacks.getBroadcastItem(i).onSomeEvent();
} catch (RemoteException e) {}
}

mCallbacks.finishBroadcast();

This can quickly pollute the service implementation, and even if you factor these calls out to a separate class it can be a pain to create and maintain them. So, I came up with a solution in the form of a Perl script which takes as input an AIDL file defining the callback interface and outputs a class implementing the extended RemoteCallbackList. To use, simply type:

$ ./aidl-cbliststub.pl < IFooListener.aidl > IFooListenerCallbackList.java

Download: aidl-cblistsub.pl

Monday, August 25, 2008

Android Instrumentation Example

As Android approaches maturity with its recent 0.9r1 release, I began to think its time that my main project updates to match. I decided to take another look at Android's instrumentation and unit testing features to build robust tests for my critical services and activities. Unfortunately, there isn't anything new in the way of documentation however there is now is an example we can use in ApiDemos.

Looking at the new ApiDemos we see that there is a new tests directory which contains a second AndroidManifest.xml with no user activities defined. This is important as this structure allows us to have two separate APKs, one for production and one for testing, so our main distribution and build doesn't need to be polluted. Unfortunately, this approach is not compatible with the Eclipse plugin, and so we must define everything in an external build environment.

For convenience, I packaged the complete ApiDemos project with my Ant build environment here: ApiDemos-instrumentation-build.tar.gz. To build, start the emulator and run the following commands:

$ adb shell rm /data/app/ApiDemos.apk
$ ant install
$ cd tests && ant install

It is essential above that you remove the old ApiDemos.apk as the instrumentation APK must be signed with the same key as the package it tests.

Once we've got both APKs installed we can begin running our unit tests. There is no UI in Android for this, however it can be invoked more conveniently through adb as such:

$ adb shell am instrument -w com.android.samples.tests/android.test.InstrumentationTestRunner

This will run all defined tests and print a dot character for each successful test, F for failure, or E for invocation error. See the javadoc in tests/src/com/android/samples/AllTests.java for more sample command lines to run individual test cases or specific tests within them.

My main project, Five, has recently been updated to include unit tests in the five-client component, with more test coverage to follow in the next few weeks. For a non-trivial test case, see my CacheServiceTest.

NOTE: Previously, I was using the masa Android plugin for Maven, however it has not yet been updated to support 0.9r1. I feel that using Maven for this would have been cleaner, but the Ant approach is sufficient for this simple demonstration. Once updated, I will return here and finish this example with a more sophisticated build environment to automate testing.

Thursday, August 7, 2008

Android on the HTC Vogue

As many of you know, the Vogue can run Android quite nicely with support for sending/reciving SMS, incoming and outgoing calls, GPRS, touch screen, etc thanks to dzo over at Xda-Developers. See his posts and materials here: http://it029000.massey.ac.nz/vogue/.

Several folks from freenode/#android have access to this device, myself included, and have been developing tools and applications to further explore the platform on real hardware. Those tools are being hosted at the android-random project page. There is a simple file manager (Glance), a much-improved threaded text messaging app (Messages), and perhaps most importantly of all a RemoteLogcat tool that allows us to observe the running devices logcat (normally accessible through adb logcat) by piping it to a server on the public Internet.

Recently, I created an emulator skin that can be used to simulate this device's resolution during development. Simply download vogue-skin.tar and unpack it into $ANDROID_SDK/tools/lib/images/skins along with the other default skins. Then fire up the emulator as:

$ emulator -skin vogue

The skin has no decorations, just a simple 240x320px layout, but this should give you a pretty good idea how different Android can be on this device.

Thursday, July 31, 2008

Interruptible I/O example using HttpClient

Recently I found myself considering some of the gotchas of threaded, blocking I/O as I've been using it on Android. Specifically, how do we gracefully handle interruptions demanded by the user or the system to free resources? After some thought there seems to be three basic strategies with Java:
  • 1. Use non-blocking I/O, which is generally clumsy and unintuitive for most Java engineers.
  • 2. Cancel blocking I/O threads by simply setting a stop flag and discarding the reference to the thread. The thread will clean itself up after an arbitrary length of time up to its transmit or connect timeout.
  • 3. Close the socket owning the input stream on which the blocking thread is waiting.
It seems that #2 is the most popular choice on Android however I would like to make a case for #3 as a cleaner method of tidying resources on user request. With this approach, we can be certain to quickly close any open files, relinquish database, object, or file locks, and allow the thread to clean up its resources quickly. As it turns out, using HttpClient makes this approach relatively painless, but there are a few gotchas in this pattern that we must watch out for.

So, to get started we need to create our StoppableDownloadThread class which allows us to encapsulate our interrupt logic.
public class StoppableDownloadThread extends Thread
{
private String mURL;

private HttpGet mMethod = null;

/* Volatile stop flag used to coordinate state between the two
* threads involved in this example. */
protected volatile boolean mStopped = false;

/* Synchronizes access to mMethod to prevent an unlikely race
* condition when stopDownload() is called before mMethod has
been committed. */
private Object lock = new Object();

public StoppableDownloadThread(String url)
{
mURL = url;
}
}
This simply outlines our basic strategy for stopping and synchronization. A simple volatile boolean flag and a monitor lock to share the HttpGet handle should do just fine. Now let's continue with the implementation of the run() method:
public void run()
{
HttpClient cli = new DefaultHttpClient();
HttpGet method;

try {
method = new HttpGet(mURL);
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}

/* It's important that we pause here to check if we've been stopped
* already. Otherwise, we would happily progress, seemingly ignoring
* the stop request. */
if (mStopped == true)
return;

synchronized(lock) {
mMethod = method;
}

HttpResponse resp = null;
HttpEntity ent = null;
InputStream in = null;

try {
resp = cli.execute(mMethod);

if (mStopped == true)
return;

StatusLine status = resp.getStatusLine();

if ((ent = resp.getEntity()) != null)
{
long len;
if ((len = ent.getContentLength()) >= 0)
mHandler.sendSetLength(len);

in = ent.getContent();

byte[] b = new byte[2048];
int n;
long bytes = 0;

/* Note that for most applications, sending a handler message
* after each read() would be unnecessary. Instead, a timed
* approach should be utilized to send a message at most every
* x seconds. */
while ((n = in.read(b)) >= 0)
{
bytes += n;
System.out.println("Read " + bytes + " bytes...");
}
}
} catch (Exception e) {
/* We expect a SocketException on cancellation. Any other type of
* exception that occurs during cancellation is ignored regardless
* as there would be no need to handle it. */
if (mStopped == false)
e.printStackTrace();
} finally {
if (in != null)
try { in.close(); } catch (IOException e) {}

synchronized(lock) {
mMethod = null;
}

/* Close the socket (if it's still open) and cleanup. */
cli.getConnectionManager().shutdown();
}
}
This is a pretty standard example of an HTTP GET using HttpClient4, however do note that we have strategically placed checks against our stop flag to avoid leaving the download thread in an inconsistent state when it's being cancelled. We're not done yet though as we still need to implement the stop part of the interface so that our main thread (or any other thread) can abort the download thread:
public void stopDownload()
{
if (mStopped == true)
return;

/* Flag to instruct the downloading thread to halt at the next
* opportunity. */
mStopped = true;

/* Interrupt the blocking thread. This won't break out of a blocking
* I/O request, but will break out of a wait or sleep call. While in
* this case we know that no such condition is possible, it is always a
* good idea to include an interrupt to avoid assumptions about the
* thread in question. */
interrupt();

/* A synchronized lock is necessary to avoid catching mMethod in
* an uncommitted state from the download thread. */
synchronized(lock) {
/* This closes the socket handling our blocking I/O, which will
* interrupt the request immediately. This is not the same as
* closing the InputStream yieled by HttpEntity#getContent, as the
* stream is synchronized in such a way that would starve our main
* thread. */
if (mMethod != null)
mMethod.abort();
}
}
This completes our basic interface, but we still don't have a usable example here. There's no communication between our download thread back to the user in any meaningful way as would be required for an Android application. For that I have modified the above code slightly and introduced an Android layer in the form of a working demo. Source code for the full example: CancelHttpGet.tar.gz.

Friday, May 30, 2008

Details on the next public SDK

I had hoped to reserve judgment until after an official announcement from Google, however after speaking with Dan Morrill and Jason Chen at Google I/O, it seemed clear that the OHA, up the corporate chain, has not taken the development community seriously. I have confirmed that the ADC winners have now received an updated version of the SDK which they are bound by NDA to keep private. These projects are thus forced to be closed until the NDA restrictions are lifted, which include no source release, performance benchmarking, discussion of new features, screenshots, etc. These restrictions are expected to last until the next public SDK is dropped.

So, when is the next public release? Surely after over 3 months since M5 and only a few major releases so far it should be close, perhaps landing after round 2 of the ADC is over? Not so. The SDK is not expected until either shortly before handset launch later this year, or perhaps on or after that date. We can rest assured that there will be significant changes in this release: modified and new APIs, new core SDK features (like Wi-Fi, bluetooth, etc), modified UI, and of course many important bug fixes. As a result, our applications will require substantial revision to work [well] on this new version, reducing the likelihood that losing ADC entries will be able to "compete" for visibility on the handsets as they launch. Not to mention, generally stressing the larger development community with excessive unnecessary work and "wandering" development with no clear indication of what's coming and when.

I see this as a serious problem, running directly counter to the claims of openness and developer support, however Google and the OHA apparently do not feel that a commitment to openness is binding in the face of proprietary inconvenience.

So, I feel there is no choice but to suspend my development on the current platform and await the launch of handsets. Hopefully I will be able to catch up quickly and still offer a stable and feature-rich application within the first few months of handset availability. That said, I will now be starting on the desktop client for my media streaming system. If anyone is interested, my project is currently open source and I am actively interested in contributors, even if you want to work on the Android component using M5 *grin*.

Tuesday, April 15, 2008

My ADC Submission: Five, a media distribution technique

I have created a system by which your music can be accessed anytime on the go using your cell phone's wireless data connection. Simply install the server software onto your home PC and configure the phone to connect to it. Initially, the meta database will be downloaded and then from there only changes will be synced to the phone. The media itself is retrieved on demand and cached to the storage card. In my real-world tests with a remote server and simulating GPRS or EDGE data throughput has been very promising, requiring only 3 - 8 seconds of buffer time before most content can be played.

For more screenshots and info, see http://android-five.googlecode.com. The system, though currently closed, will be opened under the terms of the GPL after the first round challenge winners are announced, regardless of outcome.

I will also be posting a video this week, showing my system in action. Stay tuned.

Wednesday, March 5, 2008

Tool to read Android binary XML files

I have successfully reverse engineered a good portion of the Android binary XML file format that is found inside of Android package files (.apk). With this tool, you can explore the XML layout, drawable, and animation files used in the applications distributed with the SDK (phone, browser, contacts, etc). My primary motivation for doing this was to simply observe some of the common practices and get a sense for what Google is doing internally that isn't necessarily available through their API demos and samples. Below you can find two links to download either the stand-alone convertor or the collected output as run over every APK file found in the phone's /system directory:

Download: axml2xml.pl
Download: android-xmldump.tar.gz

Please note that this tool was a very quick hack and some of the XML files I found failed to parse. Not many, and the only ones I found were raw XML documents (not Android resources) so I didn't bother to explore any further incompatibilities. If you find any resources that fail to parse or have any insight into the format, feel free to leave a comment and I will investigate when I have time.

EDIT 2012-08-22: Android's come a long way since this post.  It's now possible to use the aapt tool to read the contents of XML documents (and a whole lot more) of APK files.  For example:

android dump xmltree foo.apk AndroidManifest.xml

Sunday, March 2, 2008

Custom Android list widget to access large sorted lists on touch devices

I have developed a custom Android widget for m5-rc14 that automatically (and efficiently) sections a sorted list by alphabet letters and offers a side-bar widget for quickly jumping to each section. This widget could be very useful for any project offering an extremely large list to the user, such as a music player showing artists or albums.

Some things left out with this widget are a smooth scroll to the selected position as well as a finer control for sections that have large item counts themselves. More to come later :)

Here's a screenshot using dummy data:



Download: AlphabetListView.tar.gz

Licensed under the GPLv2.

EDIT 2012-08-22: This approach represents very old design patterns for Android and has been broadly replaced by upstream components such as the fast scroll mode of ListView.

Wednesday, January 9, 2008

Asynchronous Service Example

Many folks have been asking about asynchronous services (using the Binder) in Android and I decided to whip up a quick example showing how this is intended to work with the current SDK (m3-rc37a). There are rumors from Google that they will be improving things soon and providing a better example, but in the mean time this example should clear up a lot of the confusion:

AsyncService.tar.gz

UPDATE: The project must be built using ant (not Eclipse) because of an SDK bug regarding the invocation of the aidl tool. There are also reports that even ant won't work on Windows due to yet more bugs in aidl. The code does work as Google intended, though, and in the next SDK release they are committed to having these issues resolved.

UPDATE2: Google released m5-rc14 and, as promised, the bugs are fixed and their included RemoteService example has been updated to show similar functionality.

Friday, December 28, 2007

Android VNC, Part Deux

I decided to create my own VNC implementation and have posted code and binaries over at Google Code. There, you'll find instructions for installing and using the VNC server with a Windows Mobile device using .NET VNC Viewer. Here's a low-quality photo I snapped to get you interested:


The application running is my Android RSS reader, also hosted by Google Code.

Sunday, December 23, 2007

Android RFB / VNC implementation

Looks like the Android team has created a functional VNC server implementation natively in their surfaceflinger library (/system/lib/libsurfaceflinger.so). After some further exploration, it is possible to actually connect to and use this VNC server, although there are very strict requirements of the client.

First off, you will need to proxy the connection as it only permits connections on the local interface. For this, I have simply cross-compiled a simple TCP proxy and invoked it on the emulator:

arm-none-linux-gnueabi-gcc -static -o proxy simple-tcp-proxy.c
adb push proxy /data/proxy
adb shell /data/proxy 0.0.0.0 5901 127.0.0.1 5900


Then you must redirect port 5901 on the local machine using the Android telnet interface:

$ telnet localhost 5554
Trying 127.0.0.1...
Connected to localhost.localdomain.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK
redir add tcp:5900:5901
OK


Now you can connect from your local workstation:

xvncviewer -noauto localhost

Note: the VNC connection will fail if the client suggests any unsupported pixel format (bit depth, endianness(?), etc). So make sure you use -noauto to disable the initial 8bpp performance test and also use a 16bpp native display on your workstation. If your client requests 24 or 32bpp, the server will reject and hang indefinitely. See adb logcat to determine if you have triggered this behaviour.

A few comments on this implementation:
  • You may only specify 16bpp pixel format, with the true colour flag on and a 565 bit pattern. This creates problems trying to use it from mobile devices with tools like .NET VNC Viewer which default specifies a 655 bit pattern when you force a 16bpp encoding. I wrote a very simple proxy that understands the RFB protocol and "fixes" some of this brokenness, but the experience is still less than desirable.
  • Only the raw encoding is supported, with no incremental updates. This causes atrocious performance problems on the client, making it impractical to use an existing mobile device to interact with the Android RFB server. I tried, it's bad. I think the only real option to proceed would be to extend my proxy to have a deeper understanding of the full RFB protocol, interpretting and re-encoding the data sent from the native Android RFB server. This seems like excessive work, and ultimately is work that should go into the native server. Perhaps I will still do it, though, just to prove it's possible.
For reference and further reading, see my android-developers post on the subject.

UPDATE: I have created my own VNC server implementation on Android to work around these problems.

Tuesday, November 20, 2007

Android RSS Reader

I started an Android RSS reader project to help learn the new Google Android APIs in preparation for the Android Developer Challenge. The irony as I tested overwhelmed me: