Sunday, March 16, 2008

My first meeting with the SimpleAdapter widget

Such a shame. Normally, Android developers have their SimpleAdapter adventures right at the beginning of their Android development career, meanwhile I met this beast just now. I wouldn't say that this UI feature is overdocumented and that there are truckloads of example programs out there (if there are, Google does not find them) so I decided to share my experiences with whoever cares to read this blog entry.

It all started with a very simple wish that I wanted to create a list like this:


Each list entry has two lines and the lines are styled differently. Fortunately, there is an example program at the ListActivity documentation page which happens not to work and takes the input behind the list from a database. So it took me some time to find my friend, the SimpleAdapter widget and to find out, how to use it.

You can download the example program from here.

The root of the problem is that each element of this list is a complex view, consisting of two TextViews (XML mangling because of blog engine limitations):

[?xml version="1.0" encoding="utf-8"?]
[LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"]

[TextView android:id="@+id/text1"
android:textSize="16px"
android:textStyle="bold"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/]

[TextView android:id="@+id/text2"
android:textSize="12px"
android:textStyle="italic"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/]
[/LinearLayout]

The corresponding SimpleAdapter maps an element from list of objects to this view.

SimpleAdapter notes = new SimpleAdapter(
this,
list,
R.layout.main_item_two_line_row,
new String[] { "line1","line2" },
new int[] { R.id.text1, R.id.text2 } );

Now this is not a trivial line of code. What it says is:
  • "list" is a reference to an object implementing the List interface. Each element in this list is an object implementing the Map interface. In our implementation example, the list is ArrayList and the elements in this list are HashMaps.
  • The layout describing one row in the main list is defined in layout/main_item_two_line_row.xml file.
  • In each individual HashMap, there are two key-value pairs. The keys are "line1" and "line2", the corresponding values are arbitrary objects whose toString() method yields the value displayed in the list row. In our case, the values are Strings.
  • Values stored with key "line1" will be displayed in the TextView whose id is "text1". Similarly, "line2" Map key is associated with "text2" TextView.
You can try the program following the instructions in the Start here entry. You can add items to the list using the menu.

Tuesday, March 11, 2008

Observing content

Android documentation makes the point about content providers that they are perfect tool for hiding data access details. The Android content provider API has a clever little feature, however, that allows applications (and services) to observe changes of a dataset. The use case is that some component manipulates the persistent dataset that other components depend upon. The usual pattern is that the component makes the changes then invokes some sort of notification interface so that the dependent components are aware that the dataset was changed. If such a strong coupling is not possible, the dependent components may even need to poll for changes.

The Android content provider framework allows a much more elegant design. As datasets are identified by unique URIs, it is possible to ask for notifications if a certain URI is changed. The framework is the following.

  1. Well-behaving content providers are expected to notify the content resolver if they do something that may potentially change their dataset. This includes insert and update operations but registering database cursors returned by query operations is also necessary because cursors may be used to update data.
  2. Components interested in dataset changes register at the content resolver. If any URI is manipulated that they registrated for, they get notification.
You can download the example program from here.

Click here to access the example program adapted to Android SDK 2.3.3.

The content observer framework depends on the cooperation of content providers and content observers. Content providers are expected to notify content resolver that they have updated the dataset. You can observe this in our well-known simple provider, SimpleStringDataProvider.java.

In insert method:

getContext().getContentResolver().notifyChange(uri, null);
This notifies all the observers registered for that particular URI that change happened.

In query method:

c.setNotificationUri(getContext().getContentResolver(), url);

where c is reference to a Cursor object. If the data behind the cursor's position is updated (Cursor.update*(), Cursor.commitUpdates()), the given URI will be notified.

The other side of the picture is the observer. In this simple example, the observer is located in the DPObserver activity. As the observer is unregistered using the observer object reference, the observer is registered at onStart() and unregistered at onStop() because after onStop() the state of the activity may be lost.

In registerContentObservers:

ContentResolver cr = getContentResolver();
stringsObserver = new StringsContentObserver( handler );
cr.registerContentObserver( SimpleString.Strings.CONTENT_URI, true, stringsObserver );


We requested notification for the content URI allocated to the Strings provider plus all its descendants. This is important because e.g. the Strings provider generates URIs for newly allocated items like the following: content://aexp.dpobserver.SimpleString/strings/[id] where [id] is an integer number. These URIs are not equals to the Strings provider's base URI, these are descendants of the base URI.

The observer object is a child of the android.database.ContentObserver class. Its onChange() method is called by the content resolver if there is a change of the data behind the URI the observer was registered for. Unfortunately the URI that triggered the invocation is not passed to the method. The onChange() method is called in the context of a Handler. In our case, this Handler uses the UI thread of the activity.

You can try the application by launching the DPObserver activity and monitoring the log (adb logcat from the command prompt). Whenever you add a new data item (by clicking a menu item), the onChange() will generate a log message.

Now comes the interesting bit. We actually registered another observer, that one for the URI of content://contacts/people and descendants which belongs to the Contacts application. Launch now the Contacts application and add a new user. You will see in the log that our activity got called (except if it was stopped by the application manager because it went into the background). At this point, we could access the Contacts content provider and find out, what entry was added. It would be much more easier if we had the URI of the added entry but finding the new entry is possible by looking for the entry with the highest ID. We could hook onto Contacts database manipulations with our own functionality. Isn't that interesting? ;-)

Friday, February 29, 2008

Autostarting services

Some privileged services start automatically in Android while the lowly applications I have written so far had to be started manually. I was not satisfied with the situation so I went after the Android bootup sequence.

The Linux layer under the JVM boots up normally, using the init script but I was not interested in that. I found that the Java services are all started by the System server (android.server.SystemServer) which does launch each system server in a hardwired way.

...
Log.i("SystemServer", "Starting Alarm Manager.");
sm.addService("alarm", new AlarmManagerService(context));
Log.i("SystemServer", "Starting Window Manager.");
wm = WindowManagerService.main(context, power);
sm.addService("window", wm);
...


There is no way getting our service autostarted this way but fortunately there is the android.intent.action.BOOT_COMPLETED intent which is broadcasted when the boot completes. One needs android.permission.RECEIVE_BOOT_COMPLETED permission to receive this intent.

Download the example program from here.

The example program has two parts: an intent receiver catching the BOOT_COMPLETED intent and a primitive service that counts down from 10 in every 3 seconds and logs the counter value. When it counts down, the service dies completely, this is necessary as there is no simple way to uninstall packages in the SDK so this service is not allowed to cause trouble later. Please, note the use of Handler for the timed countdown: you can't stay for too long in onStart() otherwise the application manager will shoot down the service.

Check the boot log below and you will find how the service is started. Each ... represents deleted log entries because meanwhile the boot process is happening and other services write the log.

D/BootCompletedIntentReceiver( 576): android.intent.action.BOOT_COMPLETED
...
D/BootCompletedIntentReceiver( 576): BackgroundService started
...
D/ActivityThread( 576): Creating service aexp.persistentapp.BackgroundService
D/BackgroundService( 576): onStart
I/ActivityManager( 510): Stopping service: {aexp.persistentapp/aexp.persistentapp.BackgroundService}
D/ActivityThread( 576): Stopping service aexp.persistentapp.BackgroundService@400bcb18
D/BackgroundService( 576): onDestroy
...
D/BackgroundService( 576): Counter: 10
...
D/BackgroundService( 576): Counter: 9
D/BackgroundService( 576): Counter: 8
D/BackgroundService( 576): Counter: 7
....
D/BackgroundService( 576): Counter: 6
D/BackgroundService( 576): Counter: 5
...

Friday, February 22, 2008

Android is the most modern application platform

Exceptionally, in this blog entry I intend to talk about philosophy instead of hard software code. There are so many mobile application platforms and some of them like Symbian is pretty widespread. So why the excitement about one more platform which is in addition Java-based - there are a number of Java-based mobile platform starting with J2ME, OSGi R4, Limo and so on. Everybody has one's own answer and I think the Android Developer Challenge is a great factor. However, one paper I wrote about 2 years ago (shameless self-advertisement ...) comes to my mind constantly when I work with Android. In that paper I analyzed mobile middleware patterns (get the presentation for here, the paper here). There are 4 major patterns in mobile middleware (quote from the introduction of the paper).

Context-awareness

Traditional middleware is strictly layered meaning that it shields the applications from events concerning the lower level of the stack. For example if a remote invocation cannot be sent, the middleware layer may retry and eventually send a general error to the service user. Context-awareness means that there is no such shielding and the application is aware of the environment situation. Context changes are inherently asynchronous and are often delivered in the form of events. It is important to note that only the application can decide what context events are important and how to handle them. For example when a business application notices that its cheap and fast proximity connection is no longer available, the application can revert using slower and more expensive cellular connection. The same option may not be available for a game which is not allowed to use more costly bearer and in case of disconnection, an error should be sent to the end user or the application may switch to standalone mode.

Reflection

Reflection generally means that the program is able to make computations on its own structure during its execution (retrieve the current structure, evaluate the structure against environmental constraints then update the structure if necessary). Reflection is a crucial technique in mobile computing, especially, if the application is expected to be context-aware. Even moderate number of context states yield large number of context state combinations. If the application and the middleware are built in monolithic fashion, the application and middleware code must be prepared for all possible context state combinations which quickly becomes intractable. Also, the memory footprint of the monolithic middleware increases with each context state combination handled. In order to keep the footprint minimal and the design of the system clear, the middleware needs to be decomposed into a collection of smaller components. The application chooses just the components it needs and composes the middleware that serves the application the best. In case of context changes, the application evaluates the context transition and possibly changes the instantiated components and/or their configuration.

Off-line access

Disconnection is an inherent property of mobile computing. The reason for disconnection can be physical (no coverage) or social (mobile access is too expensive or not acceptable in the given situation). In order to provide acceptable user experience, operation in disconnected mode must be available. The key technology to achieve disconnected operation is the relocation of relevant data and code to the mobile device. Data relocation can be achieved by pretty established data synchronization techniques.

Asynchronous communication

Networked computing is dominated by solutions following Remote Procedure Call (RPC) semantics. RPC mimics the procedure call on a single processor, the calling procedure is suspended for the duration of the call and execution continues in the called procedure. Therefore RPC is inherently synchronous. Mobile transport networks are characterized by long and variable delays and frequent transmission errors. In this environment communication must be asynchronous ( event-based or messagebased terms are also used for the same concept). This affects the communication semantics the middleware uses. Instead of procedure call semantics, communicationrelated events are delivered to the application.

The paper goes on and designs such a framework for OSGi but that's history. So you can imagine my surprise when I started to work with Android and saw the intent and the related service framework that realizes context-awareness and reflection. The decomposition of the Android application into intent handler activities implement one key element of the reflective vision - standalone components that can be reconnected as the environmental situation demands it - and the intent delivery framework is perfectly suitable for context-aware computing. The intent matching logic in the current Android implementation is pretty simple (exact match of action and categories) but it takes not much imagination to extend it with more sophisticated matching logic if the target platform's capabilities (e.g. power consumption, processor speed) allow it. Intent delivery is slow but service binding based on intent matching - so that the service is selected by an intent and then the selected service is called repeatedly - is sufficiently fast.

In addition, off-line operation - synchronizable content providers - are part of the platform. The only key element Android misses is a comprehensive asynchronous communication framework like queues. The XMPP service that has just been removed can be such a service.

Android is not just another Java-based mobile platform but actually the only platform that adopts the results of the mobile middleware research therefore it is interesting in itself, without the Android Developer Challenge and its prizes. Its fate depends mostly on business factors but it is still important to note that the Android platform's architecture is several steps ahead of the competing platforms.

Now back to coding. :-)

Update: Mr. Fan found this post so interesting that he translated it to Chinese. Here is the Chinese translation (I couldn't check it :-))

Wednesday, February 20, 2008

Location providers - climb the Triglav with Android

Android SDK as it is clearly encourages developers to deal with location-aware applications. Both the location provider and the map part of the system is sufficiently documented and is functional which is pretty much in contrast with e.g. the synchronization and bluetooth parts. Good tutorials have been written about how to use the Android location framework so I wanted to try something else. I wanted to see, how to introduce one's own location data into the system.

Android SDK comes with one built-in location provider called "gps". This location provider moves along a predetermined route - obviously around Google premises. I was curious whether it is possible to introduce one's own location provider into the system therefore I took apart android.server.LocationProviderService. I found that it is relatively easy to introduce one's own location track which is then presented as new location provider to Android applications. Creating a new location provider software module turned out to be more complicated and eventually I did not try that out. LocationProviderService is able to handle location providers with their own Java logic but unfortunately the classes of these providers are loaded by the own classloader of LocationProviderService. This means that it is not possible to deploy the location provider software module as a package (apk), one has to fiddle with the software base of the Android system.

I did not do it because, to my pleasant surprise, Android's own location provider turned to be a pretty versatile simulator itself. Deploying own location providers based on track data really works like a charm. The LocationProviderService loads providers from under the /data/misc/location directory (device-based path). Each subdirectory under this directory is a location provider and the name of the location provider equals to the name of the subdirectory. The files in the subdirectory define the provider. As an example, you can go to the tools subdirectory of the example program package and run pull_gps.bat (emulator needs to be running when you do this). This batch file will fetch the three files associated with the "gps" provider as gps_location, gps_nmea and gps_properties (their original names on the device are location, nmea and properties, respectively, under the subdirectory called gps). The properties file describes the properties of the location provider in an easy to understand textual format. The location file is the last known location and the nmea is the track info in NMEA format. Well, I am not familiar with location format and I don't know what NMEA format is. There are two other possibilities: instead of "nmea" file, you can have "kml" or "track". In case of "kml", the track data is in KML format while "track" is a very simple textual format. I went for the latter and didn't try the former one - erm, I left that execise to the interested reader. ;-)

You can download the example program from here.

The "track" format is simple. It looks like this:
time longitude latitude altitude [bearing speed]

Saturday, February 16, 2008

The rocky road to m5

Even though I slept over the release of m5-rc14 SDK release because of my hurdles with the synchronization framework, I lost no time test driving it. I ported the UI part of the sync example program to M5 which contains three activities and a content provider. The port was much more time consuming than I expected.

I knew in advance from the release notes that I will have troubles with the content provider because android.net.ContentURI has gone and was replaced by android.net.Uri. What I did not expect, however, is that because of minor schema changes, the layout and manifest XML files also require quite an amount of handwork. What was previously

[ListView id="@+id/android:list"


now has to become


[ListView android:id="@+id/android:list"

(XML mangling because of the blog engine limitations)
This required 7 changes in the layout files of the rather primitive application. The Android manifest was also changed for good. Gone are the class and value attributes and now everything is a name.

Before:
[activity class=".SyncExample2" android:label="SyncExample2"
After:
[activity android:name="SyncExample2" android:label="SyncExample2"]
Overall, 6 changes in the 21 lines of the Android manifest file.

Updating the content provider was really painful. The replacement of android.net.ContentURI with android.net.Uri and other class changes required 20 changes in the very simple content provider with 229 lines. I marked all changes as comments so you can review them in the code.

You can download the example program from here.

And when I thought that everything was done, it turned out that the NotificationManager (that I used fortunately at two places only) has also changed. Transient notifications are widgets nowadays and are created like this:

Toast.makeText(this, "message", Toast.LENGTH_SHORT).show();

In order not to make it boring, the documentation remarks merrily that android.widget.Toast may not be the final name of the thing. And I did not even mention the changes of the undocumented API that the content provider list views use - well, one uses undocumented API at one's own risk.

Overall, seemingly minor changes of API "beatification" cause significant work even on smaller programs. As a bonus, you may marvel at the new UI. Installed applications went to the main screen.



And look at this horizontal menu!

Thursday, February 14, 2008

Synchronization in Android

Note: this example program was written before the new m5-rc14 release of the SDK was published and therefore it refers to m3-rc37a SDK release. I intend to investigate the sync issue in the new release too.

The first thing I noted about Android content providers that they support synchronization. This fact has huge implications and shows, how well the Android mobile platform is designed. Synchronization is a key enabler in mobile applications but is often "engineered in" later into the platforms. This approach is about as realistic as "adding security later" to a non security-aware platform.

It is not surprising for an Android-hardened developer that synchronization does not work in the m3-rc37a release and the example program presented here is not able to accomplish any real synchronization. This statement would discourage lesser programmers but not the ones dealing with the Android platform! Decyphering the Android synchronization framework is an interesting exercise in itself even though that framework may change in the future. Key elements are already there and there are some interesting findings regarding synchronization as a service.

You can download the example program from here.



The naive observation that led me to deal with the Android synchronization framework is that the log clearly indicates a running synchronization service. The synchronization service (actually called android.content.ContentService) listens to data connection/disconnection events and logs these state changes. In order to actually activate the sync part of the service (other part of the service deals with the XMPP connection), the following steps should be taken.
  • The sync part of the service must be enabled by manipulating the sync_enabled property in the settings table. This is done by calling android.provider.Settings.Gservices.putString( cr,"sync_enabled","true" ). You noticed it well: the G in Gservices refers to Google. Clearly, Android sync framework programmers considered synchronization a Google service. In order for this call to succeed, the application must have android.permission.WRITE_SETTINGS permission (check the manifest of the example program).
  • Account information must be provided. Interestingly again, the service handling this logic is called GoogleLoginService. ContentService obtains account information from GoogleLoginService and if there are no accounts specified, synchronization stops. This is a bit frightening but in m3-rc37a release the account information is stored in a local SQLite table. Do the following:
    adb shell
    cd data/data/com.google.android.providers.googleapps/databases
    sqlite3 accounts.db

    INSERT INTO "accounts" VALUES(1,'user','password',1);

    .quit
  • The sync engine stores its settings, history and stats in a content provider under the content://sync/ tree. Strangely, this content provider is not implemented at all. The example program provides a naive implementation which is good enough to make the sync service work.
The sync service is ready for work now. In Android, only synchronizable data providers can be synchronized and this makes this whole exercise more valuable than just pure hacking. Content providers must jump some fences to become synchronizable. Pretty few built-in content providers of the SDK are synchronizable (you can examine these lists using the example program's "List sync providers" and "List content provider" menu items).

The steps necessary to make a content provider synchronizable are the following:
  • The content provider must be marked as synchronizable in the manifest (again, the XML fragment is mangled because of the limitations of the blog engine):
    [provider class=".SimpleStringDataProvider" android:authorities="aexp.syncexample.SimpleString"
    android:syncable="true"/]
  • The content provider must be able to provide a temporary version of itself. The method signature is the following:

    public ContentProvider getTemporaryInstance()

    The synchronization engine manipulates the temporary instance of the content provider and changes done on the temporary content provider are merged by another method the content provider must implement:

    public MergeResult merge(SyncContext context, ContentProvider diffs, boolean readOnly)

    This latter method gets the temporary content provider instance after one synchronization step is finished on it and merges it with the main content provider. Meanwhile, collisions may be detected (data changed incompatibly on both sides since the last synchronization) and as a result, synchronization may even be interrupted by the user.
  • And last, but not least, the synchronizable content provider must be able to return the SyncAdapter that is able to synchronize the provider.

    public SyncAdapter getSyncAdapter(Context context)

    The SyncAdapter instance abstracts the entire synchronization engine. The example program provides a dummy implementation.
This is not enough. The database structure of the content provider must be designed in such a way that the SyncAdapter supported by the content provider is able to manipulate it. There are different synchronization strategies and android.provider.SyncColumns provides a number of columns that may be useful implementing them. The content provider in the example program supports the most common one, the timestamp-based synchronization. In this method, the "version" of a data item is expressed by a high-resolution timestamp. Each item timestamped after the timestamp of the last synchronization is candidate for sync processing.

The interaction between the sync engine and the sync adapter can be followed on the the log below:

D/SyncExample( 614): syncDB
D/SyncExample( 614): After syncDB

D/Sync ( 467): running sync operation type: 1 url: content://aexp.syncexample.SimpleString
D/ActivityThread( 467): Installing external provider aexp.syncexample.SimpleString: aexp.syncexample.SimpleStringDataProvider

D/ActivityThread( 467): Installing external provider sync: aexp.syncexample.SyncSettingsProvider
I/Sync ( 467): Starting sync for aexp.syncexample.SimpleString
D/SyncAdapterStub( 614): syncStarting
D/SyncAdapterStub( 614): isReadOnly

D/SyncAdapterStub( 614): getServerDiffs, contentProvider: aexp.syncexample.SimpleStringDataProvider@40014470
D/SIMPLESTRINGDATAPROVIDER( 614): merge, diffs: aexp.syncexample.SimpleStringDataProvider@40014470
D/SIMPLESTRINGDATAPROVIDER( 614): merge, tempContentProvider: android.content.ContentProvider$Transport@400144a0 D/SyncAdapterStub( 614): writeSyncData: aexp.syncexample.SimpleString
D/SIMPLESTRINGDATAPROVIDER( 614): merge, diffs: null

D/SyncAdapterStub( 614): syncEnding

I/Sync ( 467): Ending sync for aexp.syncexample.SimpleString
D/Sync ( 467): finished sync operation type: 1 url: content://aexp.syncexample.SimpleString


  • In the first step, getServerDiffs is called on the SyncAdapter, using the temporary provider as input. In case of the timestamp-based adapter, the client-server communication must establish the timestamp at which this client and server synchronized last, send client changes after that timestamp and obtain changes from the server into the temporary provider.
  • In the second step, the provider's merge method is called with the temporary provider as parameter. At this point the content provider must reconcile the client-side database with the temporary database. During the merging, collisions may be detected when the client and the server both changed a data item since the last synchronization in non-compatible way. Eventually collisions may need to be escalated to the user who may even interrupt the synchronization process.
  • After this step, we have the reconciled database on the client side. The client now needs to notify the server about collision resolution and sends the client diffs one more time using the SyncAdapter's sendClientDiffs method. This step is not present in the log because our primitive synchronization example did not produce collisions.

After all this suffering, I guess, you would like to see a real synchronization session. I have to disappoint you: beside some scattered SyncML DS-related classes, I was not able to find any real sync adapter. Implementing a real synchronization engine takes a lot of time but I happen to have a SyncML-based engine implemented and I intend to put it under Android's sync framework. So stay tuned. :-)