Sunday, May 1, 2011

Deep Linking in Android Applications

I'd like to write a little bit about best practice ideas for loading data in Android applications. I'm hoping to encourage you to rethink how you visualize an Android application. In general I'm going to advocate the use of implicit intents and loaders. Here's my main point of the post:

Good Android applications can be started from any Activity.

Here's the issue. A lot of mobile programmers come from a history of designing applications that load view controllers in a sequence. iOS and WinMo applications typically launch by firing up a specific controller. Many developers will make this a splash page or a welcome screen of some sort. From there, users navigate through the app, but the developer is always sure that the code in the starting controller has executed. It often becomes a sort of dumping ground for "init" code.

 Android isn't designed this way. You should think of your Android application as a mesh of Activities like a web site is a mesh of pages. You can't (and shouldn't) control how your user enters your application. Consider for example. A sizable amount of traffic to the site does not come in through the home page. Many people post links to specific product pages and the design encourages traffic to enter any place in the site. Effectively there is no front door.

 Good applications on Android are the same. They all offer deep-linking through the Intent mechanism. In this post, I'm not going to describe how intents work. I'll assume you know the basics. Most app developers know how to start an activity using an explicit intent:

startActivity(new Intent(context, MovieActivity.class));

Note that the explicit intent includes a class reference to the Activity you're launching. While this gets the job done, it doesn't open any doors for other apps to deep link into yours. Instead you should use an implicit intent such as the following:

startActivity(new Intent("app://com.example.movies/viewmovie/5"));

 Using an implicit intent enables other applications to launch this activity directly. However, if your application isn't designed correctly this may cause problems. What if you haven't loaded the data you need for the activity? Let's imagine that you have a master-detail arrangement where activity A shows a list and activity B shows the detail for a list item. In a poor application design, activity A loads the data for all items and passes the information to activity B.


In a better design, activity A loads only the data required to display the list. It should pass only an id to activity B which will load the detail page on it's own.


Each activity should have it's own Loader. The Android 3.0 SDK made the idea of loaders official, but the principle of each activity loading it's own data is solid even in older versions of the SDK.

No comments:

Post a Comment