Sunday, January 10, 2010

RemoteViews as hypertext document

In the previous blog entry I tried to demonstrate, how a web programming construct, the feed can be implemented using LiveFolders. In this entry, I would like to highlight another relatively obscure feature of the Android API, the RemoteViews widget and argue that RemoteViews are similar in nature to another web programming construct, the hypertext document itself.

RemoteViews is the key mechanism behind the AppWidget feature of the Android platform. There are many good introductions to AppWidgets (like this or this) so I will be short. AppWidget is a representation of an Android application on the home screen. The application can decide, what representative information it publishes on the home screen. As the screen estate is limited, the representation is obviously condensed, e.g. an application executing a long-running task can publish the progress indicator as home screen widget. The technical problem is that it is not evident, how to embed functionality (even condensed functionality) from another running application into the Launcher, the default home screen provider. If Launcher delegated the refreshing/redrawing of the views embedded from another application to that application, then malfunction of that application could disrupt the Launcher itself - something to be definitely avoided as the home screen is the last refuge of the users if something goes wrong with apps. Different platforms apply similar strategy. The idea is that the home screen application does not invoke other executables when it draws the home screen, it rather uses some sort of description of the widget UI in data format and displays that. For example that is the reason Symbian forces the programmer to implement widgets as HTML/JavaScript applications and that is the reason Android decoupled the applications from the Launcher view structure

The workhorse behind Android AppWidgets is the RemoteViews widget. RemoteViews is a parcelable data structure (so it can be sent through Android IPC) that captures an entire view structure. The creator of the RemoteViews sets up this data structure, by specifying the base layout and setting field values. This has no effect on the UI and therefore background components like services, broadcast event handlers, etc. can also do it. In fact, AppWidgets are broadcast event receivers, they process broadcasts from Launcher and respond with RemoteViews. When the RemoteViews data structure is received and deserialized, it can be applied to any ViewGroup of the UI and can therefore appear on the UI of another application. From this point of view, it works just like a hypertext document except that RemoteViews describes Android views and not general web controls.

RemoteViews is a powerful construct that can be easily used outside of the context of AppWidgets. I present now a simple Activity and a Service where the Service provides an entire formatted View (and not just the data) that can be displayed easily by the Activity. Even though this is against the Big Book of service-oriented architectures (services should provide raw data and the consumers should care about formatting), there are lot of use cases for this construct. For example the output data of the service may not be so easy to display (e.g. in case of a map application) or you would like to tie the output of the service with advertisement, logo or link to your main application (a PendingIntent in Android parlance). In this case your Service (broadcast receiver, etc.) may just return the View structure you would like the client application to display. In the web world, web widgets are formatted mini webpages to be embedded into other web pages, hence the similarity of this web technology with RemoteViews.

Click here to download the example program.

There are three points to note here.
  • Check ITimeViewService.aidl under the src/aexp/remoteview directory and see how the remote method returns a RemoteViews instance.
  • Check TimeViewService.java and see how the RemoteView is constructed and updated. To make the point of returning formatted views as opposed to raw data, I added two formatted TextViews and a ProgressBar embedded into two LinearLayouts to the view structure returned by the service.
  • Check RemoteView.java and see how the RemoteView is applied to the view structure of that Activity. Everything under the "Get view data" button comes from the service when the RemoteViews is inflated into the view structure of the Activity.

RemoteViews has disadvantages, however. It cannot serialize any Views, e.g. it cannot serialize an EditText view. I am aware of only this article about the restrictions of views the RemoteViews can serialize/deserialize.

Thursday, December 31, 2009

LiveFolders as feeds

LiveFolders exist in Android since version 1.5. The mechanism was advertised as a lead feature of Android 1.5/1.6 but somehow it failed to take hold. There are excellent introductions to LiveFolders, for example this one so I cut short here. Folder is an element of the Android desktop (technically, the Launcher application) that contains "links" to e.g. Android applications. More exactly, these "links" fire Intents and those intents can launch applications, open data sources, etc. A LiveFolder is different from a normal folder in that the content of the folder (folder items and their graphical representations) is not statically stored but is generated dynamically by a ContentProvider. There is a discovery mechanism based on Activities handling the android.intent.action.CREATE_LIVE_FOLDER intent. The Launcher discovers all the Activites handling this intent, invokes them by sending the intent, in response these Activities return the URIs of the LiveFolders' ContentProviders. If the user creates an icon for a LiveFolder and opens this icon, the Launcher will know the URI of the ContentProvider behind the LiveFolder, will list its content (as icon grid or list) and allow the user to activate an item in the LiveFolder which will fire an intent, opening a contact for example.

So far so good but I would like you to think a bit further. So we have these LiveFolders that
  • Allow applications to produce items of interest
  • And these items of interest, when "clicked", activate other actions.
Doesn't is sound familiar? Feeds in web programming are just like that. Android UI already has some elements of web programming (like the Back button) and now it has feeds. Feeds are not only fashionable nowadays but have deep roots in dataflow programming (here is a short introduction if you want to know more) and clever application frameworks like Yahoo Pipes were built around them.

Sadly, exploiting this possibility is not easy now. The only LiveFolder client I am aware of is Launcher itself and aggregating/manipulating feeds is not easy. I am attempting to do just that in this blog post. I will show you how to create a LiveFolder of non-starred contacts of two existing LiveFolders: All contacts and starred contacts.

Click here to download the live folder aggregating application.

Did you know that you can star contacts? I did not but there is a LiveFolder for starred contacts.


Install the application. Now if you select the Add menu on the Launcher main screen, select Folders, you will see the Nonstarred folder. Add that folder and it appears on the home screen. If you open that folder, you will see all non-starred contacts in it. If you click any such contact, the Contact application is opened and the contact is displayed.





We generate the non-starred LiveFolder from to other LiveFolders. The application has two parts, an Activity that is invoked by Launcher to discover the LiveFolder. This is the part of the application that itself discovers other LiveFolders to retrieve the URIs of the two source LiveFolders. These URIs are then passed to the ContentProvider that aggregates the two source LiveFolders into a third one. The interesting part is the fake Cursor we return to the LiveFolder client which really accesses in-memory data and not SQLite database as it is usual with Android applications.

As a bonus track, I share with you a simple LiveFolder client that helps you to discover other LiveFolders.

Click here to download the live folder client application.


So far so good but I am not satisfied. In order to achieve the ease of manipulating RSS feeds in web programming, more automation is necessary. I intend to do it later, after I experimented with another idea.

Monday, November 23, 2009

Droidcon+ODEX file disassembly

First, the advertisement. I will make a longer presentation at Droidcon London 2009 about Dalvik bytecode in general, using Dedexer examples. This will be a longer version of my previous, short presentation (also in podcast). If central London is convenient for you, please, come. Otherwise I will share the presentation after the event.

To celebrate the event, I finished the symbolic ODEX disassembly feature in Dedexer (look for version 1.8). This means that instead of ugly offsets, Dedexer now correctly decompiles the method and field names for execute-inline, iget/iput-quick and nvoke-virtual-quick instruction families if the dependency files are available. So instead of this:

.line 3041
invoke-virtual-quick {v5},vtable #0x2c
move-result-object v2
.line 3042
iget-object-quick v3,v5,[obj+0x28]
invoke-virtual-quick {v3},vtable #0xe
move-result-object v0
.line 3043
execute-inline {v2},inline #0x4
move-result v1

You will get this:

.line 3041
invoke-virtual-quick {v5},android/app/Activity/android/app/Activity/getPackageName ; getPackageName()Ljava/lang/String; , vtable #0x2c
move-result-object v2
.line 3042
iget-object-quick v3,v5,mComponent Landroid/content/ComponentName; ;[obj+0x28]
invoke-virtual-quick {v3},android/content/ComponentName/android/content/ComponentName/getClassName ; getClassName()Ljava/lang/String; , vtable #0xe
move-result-object v0
.line 3043
execute-inline {v2},Ljava/lang/String/length ; length()I , inline #0x4
move-result v1


Much better, isn't it? See you at Droidcon and I will explain how to interpret the code fragment above.

Monday, November 2, 2009

Another book: Android Wireless Application Development

Somebody contacted me by LinkedIn whether I would write a review about this book from Addison-Wesley. Why not, replied I, if I get the book to read and it is understood that I am not a professional reviewer. I got the book, read it and here are my subjective impressions.


Gee, there are SO MANY THINGS in Android - that was the lingering feeling after having read the book. Because the authors' strong intention is not to make compromises. They methodically go through every feature of the Android API, including 1.5 features. Have you heard about AppWidgets before? Or LiveFolders? I admit that I have not but now I know about them because the book mentioned it.

The enormous breadth of the discussion comes with a cost, however. Even though everything (or almost everything) is mentioned, very few topics are discussed in depth. For example I checked the most popular topics of this blog - unit tests, adapters. The Android unit testing framework is discussed as a bulleted list (no code examples) and the ArrayAdapter example uses Strings as backing data which causes so many problems for developers. I even managed to find the topic of hybrid applications (mashup of web technologies and Android applications, like the JavaScript handlers that an Android app can implement) that was not discussed at all (go to the lean Hello, Android book if you are interested, how this very fashionable approach works in Android).

It is best to handle this book as an inventory of Android features and as such, it is very valuable. Such an inventory takes 573 pages, as of version 1.5. I wonder what that number will be in 3 years time.

Wednesday, October 28, 2009

Spinner and its data behind

I got another comment asking about Spinner and the data behind the widget. The author of the comment wanted to know, how to associate data to the item the Spinner displays. Then that associated data would be used to look up some other data source.

Click here to download the example program.

In order to understand the trick, one has to know, how Adapters work in general and ArrayAdapter in particular. Adapters are objects that are able to turn data structures into widgets. The widgets are then displayed in a List or in a Spinner. So the two questions an Adapter answers are:
  • What widget or composite view to associate with a data structure with a certain index.
  • How to extract data from the data structure and how to set field(s) of the widget or composite view according to this data.
ArrayAdapter's answers are:
  • Each widget for any index is the same and is inflated from the resource whose ID the ArrayAdapter receives in its constructor.
  • Each such a widget is expected to be an instance of TextView (or descendant). The widget's setText() method will be used with the string format of the item in the supporting data structure. The string format will be obtained by invoking toString() on the item.
Knowing these facts, the solution is very simple. We back ArrayAdapter with our own data structure. In this simple example MyData structure has just two fields but we can use structures with arbitrary complexity. The only thing we have to care about is that the data object's toString() method will be used to obtain the text which is displayed in the Spinner. Hence we made sure that toString() returns just one field of the object. The other field will be retrieved from MyData when the item is selected. Our application is written in such a way that then the other field is displayed in a separate text field.

Tuesday, October 27, 2009

Lists and focuses

I received another seemingly trivial question in a comment. The situation is simple: we have a ListView and it contains TextViews. The user clicks (touches) a list row and the row gets highlighted until the user removes his or her finger (releases the mouse button in case of the emulator). Then comes the mistery. If you put a Button into the row, this highlight does not happen. How come?

Download the example program from here.

The secret is the quite complicated relationship between the ListView's selection algorithm and the focus. Button is focusable, basic TextView is not (Button is really just a specialized TextView). ViewGroup (whose child is LinearLayout which encapsulates one list row) delegates the focus to its first focusable child if it is not prevented to do so. As list row gives away the focus to the first focusable child (the Button) and the user did not touch the Button's area, neither the list row, nor the Button is selected. All this happens in "touch mode", try to select the row with the down/up key and you will see a completely different selection algorithm in action - the row is highlighted but the Button is not.



In order to achieve the selection effect you see in the screenshot, the ViewGroup must be prevented giving away the focus. The example program implements a quick and dirty solution: the Button is not focusable (ButtonListAdapter, line 47). More elegant solution would be to declare the ViewGroup (inflated from the buttonrow.xml layout) with FOCUS_BLOCK_DESCENDANTS flag. Conveniently, not being focusable does not prevent the Button in receiving events, click on the action button and the row counter increases nicely.