Posts Tagged ‘Android application architecture’

I wrote some time ago very favorably about future of Android and Android-related job market. Unfortunately, recent events have forced me to re-consider my opinion. I mean Google’s acquisition of Motorola Mobility.

In short, I think this is a big mistake on Google’s side which is very damaging for Android in a long run and, frankly I’m no longer confident in its future. Here is why.

There were 3 main strengths that made Android a dominating force of mobile OS market:

1. Google was a partner to hardware (phone) vendors

2. Android provided cross-platform application layer. Due to this the same application binaries could run on any Android phone notwithstanding underlying hardware

3. Android is free.

Having all those 3 strengths in place Android inhibited emergence of a potential competitor. Why phone vendors would consider another OS even if it had all 3 strengths given that they already have Android?

Until now Google followed Microsoft model: they were providing OS which was used by many hardware (phone) vendors. Google and hardware vendors were partners. After Motorola acquisition they are competitors. Now hardware vendors could not be so certain about using Android. What if at some point Google creates a new version of Android and releases it through Motorola without providing access to it for other hardware vendors. What may prevent them from playing such trick? Remember, for example, that Google didn’t publish Android 3 source? Naturally, as a result of the acquisition other hardware vendors will start hedging their bets by increasing use of other OS, e.g. Windows Mobile. At least Microsoft has proven that it has no intention competing on hardware.

So, strength #1 is no longer there after Motorola Mobility acquisition.

Without it there will be many vendors willing and capable to offer a mobile OS with those 3 strengths.

For example, Microsoft. It (almost) never competes with hardware vendors as I mentioned. Given its financial resources it can easily make new versions of Windows Mobile free or almost free. And with its C# and CLI experience it is absolutely capable of building a cross-platform application layer.

Another contender could be a combination of Intel/Nokia MeeGo and Java cross-platform application layer from Oracle. And those companies have enough money to make their OS free.

Maybe Google believes that Android will be still viable due to its excellent quality? Sorry, but this is not so obvious.

Some time ago I wrote a post where I described my software architect opinion on Android. Internal quality of Android code and code design is far from perfect.

Also, Android bug backlog is growing and serious issues are not addressed for long time.

Take a look at this bug as an example. Sometimes when you send SMS using Android phone to person A it is somehow sent to person B. Pretty serious, right? You would not like this happening to you, probably, would you?

The issue was first reported in June 2010 (more than a year ago). There is 1800+ comments from people having the problem. And this is how the story ends:

Comment 1817 by ksb…@gmail.com, Jun 19, 2011

Instead of worrying about “bots” or whatever and seeming to minimize this problem, you should worry about how your ligitimate customers feel about this issue!

I just sent a text to one girlfriend that my HTC Evo shows was actually sent to her. BUT, the problem is that my girl in Mexico texted me and asked why I sent her a text in English about going to Las Vegas!! That’s completely MESSED UP guys!

I switched to this from my Iphone cause the Iphone home key wouldn’t work, but this is worse! Fix this or I’ll definitely be going back. Apple never screwed up my personal life!!!

Comment 1818 by bweb…@dslextreme.com, Jun 22, 2011

This problem happened to me at the worst of all possible times with the most sensitive of all txt msgs. Becasue of this, my marriage is now in turmoil. Screw Google! I’m going to trash my new Galaxy S and get a Windows 7 phone. I’m talking to a lawyer about being heavily compensated for damages. Never, ever, ever buy a Google phone…that’s the word that I’m going to spread.

Comment 1819 by chicmagn…@gmail.com, Jun 22, 2011

FIX THIS! I just got a Nexus S and the same thing happened to me… I am SOOOOO lucky I didn’t call the person it went to by accident names… This is an AWFUL bug!

Comment 1820 by jrobbins@google.com, Jun 23, 2011

I’m going to block further comments on this issue because it is suspected of placing excessive load on one part of our server-side software for Google Project Hosting.

Labels: Restrict-View-Commit

Comment 1821 by jrobbins@google.com, Jun 28, 2011

Corrected permissions to just block additional comments because of server load.

Instead of fixing the issue Google folks just decided to block users complaining since their complains overload Android bug tracking system.

[Update Aug 24, 2011] It seems that closing channels for feedback about Android problems becomes Google policy.

Overall, Android OS shows all signs of underfunded technology project. Apparently Google just don’t allocate enough money to hire enough properly qualified developers to deliver code of proper quality and to fix the known bugs. Otherwise I can’t explain the issues I am observing.

And having this Google decided to spend $12B on buying Motorola instead of investing enough in Android OS. Nice move, Mr Page 🙂


By entering hardware production Google Android moves from partnership with phone vendors to competition with them.

In  seems Google adopts Apple business model. It is worth reminding that very few companies were successful in a long run trying to produce both hardware and software. Apple is rather an exception and it takes Steve Jobs genius to pull this through (I have big doubts that Apple will be as successful as it is now without Steve).

Overall, I think this Google move will cause re-structuring of mobile OS market and change the trends we had observed until now. Hardware vendors will start looking for alternatives to Android. There may be several options:

  • Broader adoption of Windows Mobile
  • Forking of Android source so that to create another OS based on Android but evolving independently (something like CentOS guys did with RedHat code)
  • Support for some alternative mobile OS like MeeGo modified to become cross-platform one like Android

In short, mobile market enters a period of uncertainty and if you plan to build you career on Android, watch very attentively what is going on mobile market.

[Update from Sep 20, 2011. Things started evolving exactly as I predicted in this post. Look here for an example]



Read Full Post »

Disclaimer: the blog post represents just a personal opinion of the author. If you disagree with what you are going to read in the post below, this is fine: you may be right and I may be wrong; I have no desire to argue with you.

Being software architect, I have tried for some time to formulate my impression of Android OS as a technology. Unfortunately it is somewhat controversial.

Here is my opinion. Android OS is a strange case of a brilliant architecture at a strategic level with quickly deteriorating quality at deeper levels. The deeper you look, the lower quality of architecture and design you see. It becomes “curioser and curioser” as you go deeper and deeper.

Good software should be simple and elegant, right? Now take a look at Android application integration layer. It is anything but simple and elegant. Rather overly complicated and bloated.

Or look, for example, at design of Android SDK classes and APIs. Why, for example, such classes as Activity or Serviceare subclasses of Context class? It is like deriving Car class from Road class. Yes, those two entities work together, but deriving Activity and Service from Context is a violation of both SRP and LSP principles. Would not it be much more clean to pass an instance of Context into Activity as a parameter of onCreate() method? Similarly to how ServletContext is passed into Servlet as a parameter to init() method in JEE SDK – clean and simple design.

Often there is feeling that certain parts of Android architecture were designed by several people working simultaneously who never had chance to talk to each other. Look, for example at ContentProvider and Service. Both encapsulate certain data and functionality, both play a role of Model in MVVM pattern. So we have a substantial overlap in their purpose and functionality. But the only common parent they have is Object class…

ContentProvider class design is very indicative to quality of Android SDK design. It looks like somebody started with intent to provide an infrastructure for encapsulating data and accessing it through REST-type API. Seems like a good idea, right?

However somewhere in the process it was probably decided to use ContentProvider for encapsulating predominantly SQLite relational database. As a result Android SDK ended up with inventing a rather fancy URI-like way to query straight SQL DB. What for? Just to show that Android is different? The irony is that at the end of the day SQL is used under cover to query the DB…

Intent class plays multiple roles, so it would be natural to have separate subclasses of Intent class for e.g. message passing and publish/subscribe functionalities, right? But there is no such subclasses (look here for details).

There are more examples…

I wonder why having Google resources Android managers can not make it well architected and designed software?

Overall, Android internals do not look good. So if you are a developer who looks for a job to get fun and aesthetic pleasure from it, you may think twice before getting into Android development.

All this said, I’m still convinced that Android is going to be a dominant OS in mobile market. It is like early versions of Windows: terribly designed but unstoppable as a market force.

Read Full Post »

We have discussed in earlier posts:

Now it’s time to summarize our findings. We’ll discuss commercial future of Android OS and Android job market in this post.

Disclaimer: the blog represents just a personal opinion of the author. If you disagree with what you are going to read in the post below, this is fine: you may be right and I may be wrong; I have no desire to argue with you.

In my opinion, there is a high probability that Android OS will play for mobile software market the same role as Windows has played for desktop/laptop computer software market. Think of contemporary Android OS as something like Windows 3.0 – not a complete winner yet, but a contender with high chances to become a winner.

Why do I think so? Several reasons:

  • Free license which allows any manufacturer to use Android OS
  • Brilliant strategic decision to use Java as a language for Android application development. This made it possible to run the same application binaries on any hardware platform which a device manufacturer is going to come up with. This immediately places Android OS ahead of many other contenders like MeeGo etc. We have discussed this earlier.
  • Market share accumulated up to the moment and its dynamics (see here)
  • Google weight behind Android OS

None of competitors has this combination of advantages. Given this, Android has all chances to dominate the mobile market unless Google folks were to do something very unfortunate.

So should an individual consider a career of Android application developer? My answer is: it depends. Depends on what the individual looks for.

If it is only money and career growth, the answer is “yes”. There already is a big job market for Android developers and it will grow quickly.

Here is an illustration to this point. Once upon a time I lived in Ireland and worked there as a developer. Since those times I use irishjobs.com web site as a sort of indicator for demand for a particular skill. If you go there today and search for Android-related jobs in Dublin, you’ll get back a list of 2846 vacancies advertised by employers and recruiters. If you do the same search for Java-related jobs, it returns 3026 vacancies. Android jobs are overtaking Java jobs! Isn’t it impressive?

Clearly, the job market for Android developers is very hot with all consequences like higher salaries, faster career growth etc.

However if you are looking for an interesting job where you will be getting fun, you may think twice before taking an Android job. We’ll discuss this aspect of Android jobs in the next post.

[Update Aug 21, 2011] Recent events forced me to reconsider some of the opinions expressed in this post. Please look here.

Read Full Post »

In earlier posts we discussed:

Today we are going to discuss various mechanisms through which parts of an Android application collaborate. For lack of better term we’ll call all those mechanisms together as “communication layer” (to my knowledge, Android documentation does not offer any term for this).

As we mentioned earlier, Android application framework implements several communication patterns within its communication layer:

Message passing

This is probably the first communication mechanism which a developer encounters while learning Android application development. It is used to start an Activity or a Service. It is implemented via three methods on Context class (which we discussed in one of earlier posts) and one method on Activity class:

In both cases Intent class plays a role of a message passed.

How does Android know which Activity or Service should receive the message? There are two ways how this is done:

  • Intent may specify a name of the target component explicitly. Such Intents are called “explicitIntents” and they specify a target component via setComponent() or setClass() methods of Intent class. This type of Intent-based communication mechanism does not implement late binding pattern while all others do implement it
  • Target component is defined by a rather fancy resolution mechanism based on Intent filters.

Please note, in case of message passing communication mechanism the message (an instance of Intent class) is delivered to only one component or not delivered at all.


Publish/subscribe communication mechanism involves the same Intent class as a message and the same intent filters as a resolution mechanism defining target components, but it works quite differently. Intents used for publish/subscribe communication are called “broadcast Intents”. Those broadcast Intents can be delivered to BroadcastReceiversonly. Since BroadcastReceiver is a class and Activity and Service are classes as well, neither Activity nor Service can receive the broadcast Intent (Java prohibits multiple inheritance).

Also, unlike Intent used for message passing, a single broadcast Intent can be delivered to many target components.

In fact, Android implements 2 different publish/subscribe mechanisms each o which has two versions (regular one and sticky one):

You are still not confused, right?

Normal broadcast mechanism delivers the Intent to all eligible BrodcastReceivers asynchronously and they act on it independently, i.e. one BrodcastReceiver can’t affect either how another BrodcastReceiver is reacting on the Intent or whether the Intent is delivered to another BroadcastReceiver. It is a regular pub/sub pattern.

Ordered broadcast mechanism delivers the Intent to eligible BrodcastReceives in a sequential manner, i.e.toone at a time. Due to this each BrodcastReceiver can potentially:

  • Use results produced by previous BroadcastReceivers that worked on the same Intent
  • If needed, abort further processing of the Intent

By executing ordered broadcast, a component which initiated it gets opportunity to receive the result of processing the Intent by all BroadcastReceivers in the chain.

Ordered broadcast actually is an implementation of chain-of-responsibility design pattern.

Sticky broadcasts are versions of the corresponding regular broadcasts. The difference is the Intent is available until it is explicitly removed by removeStickyBroadcast() method of Context class. Please note, this type of broadcast should be used with great caution since not removing the sticky Intents will result in a memory leak.

Conclusion on Intent-based communication mechanisms

All communication mechanisms described so far make use of Intent class as a message. Please note, that majority of corresponding methods are implemented by Context class so they can be theoretically used by all subclasses on the Context class.

By this point one may start thinking that all Android application communication mechanisms are using Intent class. Not at all.

Late binding of ContentProvider

ContentProvider class is essentially a wrapper around SQLite database in most cases although theoretically it can use other persistence mechanisms to store/retrieve data. You can read more about the class and its usage here.

There are many ways how Android code can use ContentProviders. Some of them include getting an object which acts as a proxy to the ContentProvider (normally it is an instance of a subclass of ContentProviderClient, which implements proxy design pattern). Some of them return an instance of Cursor class which allows iterating through data set returned by ContentProvider. In all cases the concrete ContentProvider which is going to be used is identified through URI (see details here).

Overall, it is a typical late binding pattern.

Late binding and Inter-process Procedure Communication (IPC) of Service

If you think it’s all communication mechanisms, you are mistaken.

Apart of ContentProvider class there is Service class which architecturally plays the same role of Model in MVVM architecture pattern. We have discussed the hypothetical reasons why Android has two different classes to fulfill the same role in the previous post here.

There are two types of Service and each requires a separate communication mechanism:

  • Local Service which runs within the same process where it is invoked. Architecturally it is similar to ContentProvider apart that it has its own lifecycle and it is not necessarily backed by DB. A version of late binidng is used to access the local services
  • Remote Service which runs within another process from where it is invoked. Such type of service is accessed through a sort of IPC call implemented using AIDL (Android Interface Definition Language)

It is worth mentioning that the same Service may be used as both Local and Remote; the difference is in where the component which invokes the Service is located (within the same process or in another process).

You can read more about using Services here and here.

Read Full Post »

OK, we looked at Android application architecture background and architectural patterns implemented by Android application architecture. Now let’s talk about main parts of an Android application.

In this post we’ll introduce main “personages” of Android application architecture.

Android application usually consists of:

Java classes

The diagram below represents a class hierarchy of main classes from Android SDK a developer has to deal with while developing Android application:

There are much more classes than that, but those are the main ones. Classes highlighted in yellow are those a developer has to deal with (e.g. extend) directly. Other classes are important as well, but they are relatively rarely used directly.

View class is a base class for all GUI widgets. Android application GUI is a tree of instances of its subclasses i.e. GUI widgets. One can build the tree programmatically, but this is not how you should do this. GUI is normally defined by an XML GUI definition (layout file) and inflated (Android term) automatically into a tree of corresponding objects at runtime.

Activity class and its subclasses are the ones that provide logic behind the GUI. Actually it corresponds to ViewModel in Model-View-ViewModel architecture pattern (MVVM). Relationship between subclasses of Activity and GUI layout is 1-to-1; normally each subclass of Activity has one GUI layout associated with it and vice-versa. Activity has a lifecycle.

During the lifecycle Activity can be in one of three states:

  • Active and running when its GUI is in the foreground (technically speaking – on top of activity stack)
  • Paused if its GUI lost focus but it is still visible. No code is executed in this state
  • Stopped if its GUI is not visible. No code is executed in this state

Activity code runs only when the Activity GUI is visible and has focus. Also there is no guarantee that Activity object and its associated objects are in memory while the Activity is paused or stopped (very important point to remember; we discussed this Android memory management peculiar feature earlier).

ContentProvider class and its subclasses correspond to Model in MVVM architecture. In most practical cases it is a wrapper around SQLite database with rather fancy URI-based way to query the database. Theoretically nobody prevents a developer from building ContentProvider which will be using something else instead of DB for storing data. However given that query() method of ContentProvider returns Cursor object which is quite similar to JDBC ResultSet interface and the way how the query is made, nobody would doubt that the real purpose of ContentProviders is to encapsulate a database.

I don’t know how Android team came to such design, but my guess is here we have a combination of two good but not very compatible ideas.

Here is why I think so. The whole idea of content provider is likely inspired by AJAX application architecture. AJAX applications normally use MVVM architecture where Model is represented by particular URIs on a server side (however this has changed somewhat since introduction of HTML5 which allows storing data locally). Indeed, the fact that ContentProvider class is queried by URIs and makes extensive use of MIME types points to AJAX as an origin of the design. Remember, Google folks were developing a lot of AJAX software, e.g. Gmail, Google Docs etc, so it was natural to borrow ideas from AJAX application architecture for them.

Probably somebody else came with another cool idea: how great it would be to have a fully functional relational database running on a mobile device! (note, this was happening at around 2005 when mobile phones were much less powerful than now). And as a result they combined two good ideas into one ContentProvider class. As it often happens in software development combining two great ideas not always results in a good design; in Android case we have rather confusing ContentProvider design.

Service class and its subclasses are something which I have difficulty to classify. I think, Google folks have the same difficulty (please read their javadocs). They classify it by mostly describing what it is not. I would personally classify it as a special type of Model, serving a bit different use case than ContentProvider does.

In my opinion, architecturally design of Android Service was inspired by OSGI services.

I think Service is the solution Google folks came up with to solve a logical problem they created in Android application architecture with its threading model.

Think of this: Activity is active and running only when its GUI is on foreground. As soon as another Activity GUI comes in front of the current one, the current one stops running even if it was doing something. And what if you need to perform certain operation even when the process which tries to perform it is not on foreground? You can’t do this with Activity. You can’t do this with ContentProvider as well since it does not have its own lifecycle and it can run only while Activity which uses it is active.

Here Service comes to the rescue. It can be executed even when the process it runs within is not on a foreground. So if you develop Activity which must perform a long running operation which should be completed even while running in background, you should create Service implementing that operation and invoke it from Activity.

Service has a lifecycle as well. This means that it can be instantiated and run by Android application framework under certain conditions (we’ll discuss this later).

As I mentioned, as a Model, Service is somewhat of more general purpose than ContentProvider. It can use DB, but its API is not bound to DB as ContentProvider API does. In many cases Services are used to connect to external servers.

BroadcastReceiver class and its subclasses serve as “subscribers” in publish/subscribe (or pub/sub) communication mechanism implemented by Android application architecture.

Intent class and its subclasses serve as messages in message passing and publish/subscribe communication mechanisms implemented by Android application architecture.

We’ll discuss the communication mechanisms in another post later on.

Of course, Android application developer is not limited to just extending Android SDK classes. She can write her own classes as she wants. But all they will be just “helper classes” of sorts for those main classes derived from Android SDK classes.

Android manifest

Android manifest is another important part of Android application. The idea has been clearly inspired by Eclipse plug-in manifest.

Android manifest is an XML file and it serves several functions. Here is Google description of manifest functions:

  • It names the Java package for the application. The package name serves as a unique identifier for the application.
  • It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched.
  • It determines which processes will host application components.
  • It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
  • It also declares the permissions that others are required to have in order to interact with the application’s components.
  • It lists the Instrumentation classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they’re removed before the application is published.
  • It declares the minimum level of the Android API that the application requires.
  • It lists the libraries that the application must be linked against.

Please note the second point. It means even if there is a class extending Activity, ContentProvider , BroadcastReceiver or Service within an application, the class can’t be used unless it is explicitly described in Android manifest.


Any modern GUI application technology uses resources in some form. Android applications are not an exception of the rule. They use following types of resources:

  • Pictures
  • GUI layouts (XML files)
  • Menu definitions (XML files)
  • Textual strings

The way resources are referenced by Android applications is somewhat unusual. Normally in Java resources are identified by strings. Such strings may contain e.g. a path and a name of a file containing the picture or an ID of particular string etc. The problem with such approach is that mistakes in those references could not be caught during code translation.

Let’s consider following example. A file named mybutton.png contains a picture for a button. A developer makes a mistake and types mybuton.png as a reference to the resource in the code instead of using the correct file name. As a result the code is instructed to use nonexistent resource, but the code will compile just fine. The mistake may be discovered only during testing (and may not be discovered at all).

Google folks came with an elegant solution to the problem. Android application build generates a special Java class named R (just a single letter name) for each package where classes use resources. This class has a number of static final data members. Each such data member is a reference to a particular resource and they are used in Android Java code for referencing resources. Due to this each mistake in referencing resources is discovered at compile time.


Android applications use several different types of files:

  • “General purpose” files
  • Database files
  • Opaque Binary Blob (OBB) files (those represent encrypted file systems on its own that can be mounted for the application)
  • Cached files

Although ultimately they are all just Linux files, it makes sense to consider them as separate types of files since they are handled by different Android APIs and stored separately. There is also a distinction between files stored in internal device storage and in external device storage (the latter may be not present or disappear/appear at any moment).

APIs for working with the files are implemented by Context class which is an ancestor for Activity and Service classes. We already discussed this class here.

That’s all for now. In the next post we’ll discuss how different parts of Android applications communicate between them.

Read Full Post »

In this post we’ll be talking about architectural patterns used by Android application architecture.

Why understanding of patterns implemented by a certain architecture is important? Because it puts a new architecture we are learning into context of our previous experience and allows us to leverage our previous knowledge and skills.

Android documentation never mentions any pattern; at least I haven’t seen such references. But in reality Android does implement a number of patterns and architectural styles and I will show you this.

Android application architecture is a framework-based application architecture as opposite to a free-style application architecture.

What is the difference? A free-style application written in Java starts from a class with main() method and a developer is free to do pretty much whatever she/he wants.

As opposite to this a framework-based application is based on an existing framework and a developer extends certain classes or implements interfaces provided by the framework to build an application; the application can’t run outside of/without the framework it was built upon. Examples are Java web applications where a developer implements Servlet interface or extends one of its subclasses, or Eclipse RCP application where a developer extends one of Editor and View classes.

Framework-based architectures limit freedom of developers by prescribing what to do and how to do certain things. But in return they eliminate necessity to write a lot of “boilerplate” code and (hopefully) enforce well thought through design patterns.

There are many application frameworks available in Java. However Android team decided to build their own framework. Probably one of the reasons why they did it was necessity to support unique Android Java memory management.

In a “regular” Java an object is kept in memory until it is garbage collected. The garbage collection occurs only if an object does not have any reference to it from other “live” objects (see more details here). In Android it is not so. If a certain GUI gets hidden (it is not visible on the screen), there is no guarantee that it will be kept in memory even if the application intends to use it later. It might be kept in memory alright if Android OS has enough free memory, but it can be garbage collected as well at any moment when the OS finds that it needs more free memory. The same is true for processes as well. If an application process does not show any GUI to the user at the moment, it can be legitimately terminated by Android OS (there is one exception to this rule related to Android Services; we’ll discuss this later).

Here is an example. Let’s assume our application has GUI screen A and GUI screen B. A user accesses screen A first and then screen B; at this point screen A is not visible anymore. This means screen A and all logic that supports it may or may not be kept in memory. Since there is no guarantee that objects associated with screen A exist in memory while screen B is shown, the developer writing screen B logic must not expect that a certain object instantiated for screen A is still in memory. A side result of this is that Android architecture enforces “shared nothing” architectural style for Android applications. This means that different parts of Android application can invoke each other and communicate between them only in an explicit way; there is no shared state between them in-memory.

Well, what happens if the user decides to return back to screen A? She will probably expect to see the GUI in the same state as she left it, right? Here is how Android application framework solves the problem: it introduces so-called lifecycle methods in certain classes an application developer has to implement in order to create the application. Those methods are called by Android application framework at predefined transitional moments, e.g. when a GUI which was shown gets hidden or a GUI which was hidden gets to the forefront again etc. A developer can implement logic for storing and restoring state of objects inside those methods.

Such way of handling hidden GUIs and presence of “Back” button on Android devices makes it necessary to have a sort of GUI stack where the current visible GUI gets on top of the stack and all others are pushed down the stack (“push” stack operation). Pressing “Back” button removes the GUI which was on the top of the stack and shows the one which was below it in the stack (“pop” stack operation). Such stack exists in Android indeed. It is called sometimes “activity stack” and sometimes “back stack” in Android documentation.

Android application architecture follows very modern Model-View-ViewModel (MVVM) architectural pattern in how it handles relationships between GUI and a logic supporting the GUI. This is actually good news for Android developers since this is the latest and greatest architecture for GUI applications at the moment.

MVVM architecture was created in attempt to solve a disparity of skills which occurs when e.g. a Java developer tries to build GUI in Swing or a Visual C++ developer tries to build GUI in MFC. Developers are smart folks and have many skills, but building nice and sexy GUIs requires quite different talents than those the developers usually have. It is work more suitable for GUI designers. Good GUI designers are more artists and a user experience professionals than experts in designing and writing code, so we can’t expect from them writing a good code. Clearly, it would be better if a GUI designer was designing a GUI and a developer was writing a code which implements a logic behind the GUI, but such technologies as Swing or MFC simply do not allow this.

MVVM architecture overcomes this contradiction by clearly separating responsibilities:

  • GUI development is done by a GUI designer in technology more or less natural for this task (XML)
  • Logic behind the GUI is implemented by a developer as ViewModel (which actually means Model of View) component
  • Functional relationships between GUI and ViewModel are implemented through bindings that essentially define rules like “if a button A is clicked, method onButtonAClick() should be called on ViewModel”. Bindings can be written in the code or defined in a declarative way (Android uses both types of bindings)

MVVM architecture is used in one way or another by all modern GUI technologies like Microsoft WPF and Silverlight, Oracle (former Sun) JavaFX, Adobe Flex, AJAX.

We mentioned that different parts of Android application can invoke each other and communicate between them only in an explicit way. How this is done? Android application framework uses several communication patterns:

Don’t worry if some of the above sounds confusing. We’ll discuss all this in greater details in later posts.

That’s all for now.

Read Full Post »

In this post we’ll look at Android Application architecture.

Here is the official Google introduction in the topic. Frankly, I find it not very helpful. It dives immediately in details of “how” without ever explaining “what” and “why”. So here is my version and I hope it may bring you a bit more clarity. However I strongly encourage you to read the Google article since it contains a lot of useful data which I’m not going to repeat in my blog.

Android OS architecture – a bit of history

As often in IT many things could not be explained unless one knows history of particular software. That’s why we need to take a brief look at Android OS history.

Initial development of Android OS has been started in 2003 by a startup company called Android Inc. The company was bought by Google in 2005. My guess is that main features on Android architecture were defined in that timeframe. And they were not just result of Android Inc work; Google architectural philosophy and financial resources definitely influenced Android architecture. I will give several examples later on.

Also if you remember 2003-2005 were years on AJAX applications boom. I think this had a substantial influence on Android application architecture: in many aspects it is closer to a typical AJAX application architecture than to any sort of desktop GUI application architecture based on Java or C# or C++ or VB etc.

I don’t know why it happened. My guess is it was brought by somebody from Google since Google folks at that time apparently thought that Rich Internet Applications would be a solution to all problems – think of Google docs or Gmail. Also I think it was neither particularly good or bad idea. Just keep in mind that it is very different from what you are used to if your background is desktop applications.

Also influence of Eclipse architectural philosophy is visible in choice of GUI implementation approach. It is closer to SWT than to Swing.

Interestingly, somebody with a decision making power came from Windows world as well J You can see it in Android code convention using fabulous MS-born “Hungarian notation”.

Android architectural layers

Android operational system has three distinctively different and very much separated architectural layers:

  1. Underneath it has a somewhat modified and stripped down version of Linux as I mentioned in one of my previous posts.
  2. On top of the Linux layer it has application infrastructure layer which consists of Dalvik Java virtual machine, web browser, SQLite database, certain infrastructure “plumbing” and Java APIs
  3. And, finally, a layer of Google-made Android applications. In a certain sense they are an extension to the application infrastructure layer since a developer working on Android application can use them or parts of them as building blocks for her own application

Let’s look at those layers one by one.

Linux layer

Imagine you are an architect of a startup company. You have to develop OS for a new type of devices. What would you do?

You have basically two choices: start from scratch and implement your own ideas or use some existing OS and adopt it for your device.

Implementing everything from scratch always sounds compelling for software developers. Somehow we all believe that this time we can do better than others did or ourselves did in the past.

However this is not always a very practical idea. For example, Linux kernel replacement cost estimate (probably somewhat inflated) suggests that if somebody decided to build a thing similar to Linux kernel as it is now, they would need several billion dollars to do this.

If you run Android Inc, you definitely don’t have such money. If you run Google, you have such money, but you would probably think twice before spending them on building custom OS nuts and bolts. Also you would need to spend several years until you get where e.g. Linux already is; several years of delay may make you critically late to the market.

In a similar situation Apple decided to build their Mac OS and iOS on Free BSD code base. Android Inc decided to use Linux as a base for Android. Both Free BSD and Linux codes are available free of charge and provide a robust foundation for building whatever Apple or Google needed.

However one could not just run a standard Linux on mobile devices at the time (although now it is possible). The devices had very little RAM and very little persistent memory. CPUs were very weak in comparison to CPUs available on computers where Linux was normally used. As a result Android developers had to minimize Linux footprint before using it.

If you look at Linux from a high level, it is a combination of Linux kernel (which is a“must have” part) and many other parts that are optional. Actually one can run Linux kernel on its own without anything else. So Google had to have Linux kernel as a part of Android anyway. Besides this they looked at other optional parts available and added those that they considered desirable. For example, they added IPTables (network firewall) and Ash shell. Noteworthy they added Ash shell and not Bash despite the latter is much more powerful; apparently the decision was made based on smaller Ash footprint.

Also Android developers have had to modify Linux kernel so that to add support for hardware that is used by mobile devices and which is not typically available on computers. You can find more about this here.

Overall, choosing Linux as a foundation for Android made a huge impact on all aspects of Android OS. Its build is essentially a version of Linux build process. Its code is managed by git (a tool developed for managing Linux code). And so on.

While all this is interesting, if your goal is just to develop Android application, you probably won’t even touch all this Linux stuff ever (with exception of browsing Android filesystem with Ash commands). Most you need to know about Android while developing an application is Android application infrastructure layer.

You may ask what if you want to develop a native application for Android anyway. This is strictly discouraged by Google. Technically you can do this, but you won’t be able to distribute your code through normal channels. So think twice before you start doing native development on Android unless you are working on Android Open Source Project (AOSP), i.e. Android OS itself.

Application infrastructure layer

While there is a lot of similarity between how foundational parts of Apple iOS and Android OS were created, there is a striking difference between architectural decisions on Application infrastructure layer made by architects of both OS.

Apple decided to use Objective C as a programming language and a runtime for iOS applications. Objective C looks like more or less natural choice for OS built on Free BSD foundation. One can think of Objective C as a generic C++ with a custom preprocessor that adds certain linguistical constructs. Somebody may wonder why they didn’t use just straight C which Free BSD is written in? I guess this is because Apple tends to do everything in their special”Apple” way. You can read more about this here.

The bottom line is that iOS applications are written more or less in the same language as the underlying OS.

Android applications are strikingly different in this aspect. They are written in Java which is very different technology than C++ (although with its syntax derived from C++).

Why it is so? Why e.g. Android applications are not written in C++? I could not find Google explanation on this, so I can just offer my own guess.

I think the main reason was a need to make the same application binaries working without changes across multitude of hardware. This is a special problem that Android OS architects had to deal with; Apple folks did not have this problem at all. iOS runs only on Apple-built hardware and Apple is in a complete control of it. For Android opposite is true: Google does not control hardware manufacturers. For example Android OS has to run on CPUs with x86, ARM and Atom architectures. Those architectures are incompatible at binary level.

If Android OS architects had chosen the same approach as Apple architects, Android application developers would need to build and distribute their apps in several binary versions simultaneously. This could be a huge problem which potentially could make the whole Android OS project a failure.

To make the same application binaries working across different hardware Google had to use a container-based architecture for their applications. In container-based architecture binaries are executed by a software container which isolates them from details of particular hardware the binaries are running on. Examples are Java and C#. In both languages binaries do not depend on a particular hardware and they are executed by virtual machines.

Well, there are other ways to achieve independence from hardware at binary level. For example one can use a hardware emulator e.g. well known QEMU. It allows emulating e.g. a device with ARM CPU on x86 platform and so on. Google could use C++ as an application development language and run those applications inside hardware emulators. Actually, Google uses such approach in their Android emulator which is built on top of QEMU.

The most likely they did not take hardware emulator route since in this case one has to run OS on the emulator as well which makes emulation scope much bigger and as the result the execution becomes much slower. To achieve faster execution one has to limit emulation to only parts where it could not be avoided, which in our case is Android application.

Whatever Google thinking process was they decided to use Java as a primary application development language and runtime.

I think this was a critical architectural decision which made Android standing out of a bunch of other competing Linux-derived mobile OSs that have been evolving at the time. Neither of them as far as I know offers binary portability at application level. Look e.g. at MeeGo. It uses C++ and QT framework; although QT framework is multi-platform one still has to have separate binaries built for each platform.

After deciding on Java they had to decide what Java virtual machine (JVM) to use. They could not use a standard JVM due to resource constrains. One possible choice was to use Java ME JVM developed for mobile devices. However Google was not completely happy with Java ME and they decided to develop their own version of JVM, so-called Dalvik JVM.

Dalvik JVM differs from other JVMs in following aspects:

  • It uses special DEX format for storing applications binaries vs. JAR and Pack200 formats used by standard Java virtual machines. Google claims that DEX results in smaller binaries than JAR. I think they could use Pack200 with the same success, but they decided to go their own way in this aspect
  • Dalvik JVM was optimized for running multiple JVM processes simultaneously
  • Dalvik JVM uses refister-based architecture vs. stack based architecture of other JVMs with intent to speed up the execution and to reduce binaries size
  • It uses its own instructions set (not a standard JVM bytecode)
  • One can run (if needed) several independent Android applications within a single JVM process
  • Application execution can span across several Dalvik JVM processes “naturally”(we’ll discuss what this means later). To support this it adds:
    • Special object serialization mechanism based on Parcel and Parcelable classes. Functionally it serves the same purpose as standard Java Serializable, but results in smaller data footprint and potentially it is more lenient towards differences in versions of classes
    • Special Android way to execute inter process calls (IPC) based on Android Interface Definition Language (AIDL)
  • Until Android 2.2 Dalvik JVM did not support JIT compilation which adversely impacted Android application performance. Adding it in 2.2 improves markedly execution speed for often used applications

Google folks revised standard Java JDK API packages as well. They removed some of the packages (e.g. everything related to Swing) and added a number of their own packages with names starting from “android”.

They also added certain open source packages that are not a part of a standard JDK. For example they added Bouncy Castle crypto API, HTTPClient which supports client-side portion of HTTP/HTTPS protocol.

Also Google added a web browser to the application infrastructure level. It is not exactly Google Chrome running on a mobile device, but it is very close since it is based on the same WebKit layout engine and it uses Chrome’s V8 JavaScript engine. Overall, it is pretty modern and fast state-of-the-art web browser. Android applications can use the browser as their integral part.

This is all for today. We’ll look at Android application architecture proper in the next posts.

Read Full Post »

Older Posts »