17 September 2014

Messaging on Android Wear

By Timothy Jordan, Developer Advocate

Sending messages on Android Wear feels as easy as it was to pass notes back in school. Remember when your friends always felt nearby? That feeling is why I love staying in touch with friends and family using my wearable.

Your messaging app likely already works on Android Wear. With just a few more lines of code you can unlock simple but powerful features that let your users communicate even more effortlessly.

Message notifications for free

If your Android app uses notifications to let the user know about new messages, these will work automatically on their wearable. That is, when you build notifications with the NotificationCompat.Builder class, the system takes care of displaying them properly, whether they appear on a handheld or wearable. Also, an "Open on phone" action will be added so it's easy for the user to reply via the app on their handheld.

Google+ Hangouts message.

Reply like a champ

Messages on Wear get really exciting when you can reply directly from the watch with your voice. In addition to being super convenient, this always gives me a Dick Tracy thrill… but maybe that's just me. =]

To add this functionality, it's as simple as adding an action to the notification via WearableExtender that includes a RemoteInput to your notification. After the user replies, you'll just grab their voice input as a string from the RemoteInput included in the Intent. You can even include text responses the user can easily select from a list by passing an array of them to the setChoices method of the RemoteInput. More details and code can be found here.

WhatsApp message with the reply by voice action.

See who is texting

Messages are more meaningful when you are connected to the sender. That's why we recommend you include the photo of the sender as the background of the notification. As soon as the user taps into the message, they also see who it's from, which will make it matter more (or maybe that other thing, depending on who it is).

You should add a photo with a resolution of at least 400x400, but we recommend 640x400. With the larger size, the background will be given parallax scrolling. If the background is to be included in the apk, place it in the res/drawable-nodpi directory. Then call setBackground() on your WearableExtender and add it to your notification. More details and code can be found here.

Path Talk message with a clear picture of the sender.

Custom actions

Basic notifications with reply by voice and a good background image are the most important parts to get done right away. But why stop there? It's easy to extend the unique parts of your service to the wearable. A simple first step is adding in a custom action the way Omlet does. These are just actions defined with the WearableExtender that raise an intent on the handheld.

Omlet includes two extra actions with every message: Like and Check-In. Check-In sends along the user's current location.

Custom Layouts

Custom interaction on the wearable, like the following example from TextMe, is straightforward to implement. They have what appears to be a simple notification with an action that allows the user to select an emoticon. However, to show this emoticon picker, they are actually issuing a notification from the wearable. The round trip looks something like this:

  1. The handheld gets a new message, issues a notification setLocalOnly(True), and sends a message to the wearable using the Data Layer API
  2. The wearable receives that message using the WearableListenerService and issues a custom notification with a PendingIntent to launch an activity when the user views the notification
  3. That activity has a custom layout defined with the Wearable UI Library
  4. Once the user selects an emoticon, the wearable sends a message back to the handheld
  5. The handheld receives that message and sends it along to the server

Custom layouts are documented in more depth here.

TextMe allows users to reply with a quick emoticon.

Next steps

Make your messaging service awesome by providing rich functionality on the user's wearable. It's easy to get started and easy to go further. It all starts at developer.android.com/wear.

16 September 2014

Google Play Services 6.1

gps

Today, we’re excited to introduce the latest version of Google Play services to help you easily build on the newest features from Google and optimize your apps.

Google Play services 6.1 adds Enhanced Ecommerce analytics support from Google Tag Manager and offers new improvements to the Google Drive Android API. With the latest release, we’re also including a refresh of the Google Fit developer preview, so that you can test your fitness apps on any Android device.

Analytics

Launched in Google Play services 5.0, Enhanced Ecommerce is an analytics extension designed to provide richer insights into pre-purchase shopping behavior and into product performance. It’s a great way to gain visibility into the full customer journey, helping you understand how different user acquisition campaigns are performing at a granular level. By including support for Enhanced Ecommerce in Google Tag Manager with the latest release of Google Play services, we are supercharging your ability to regularly update and manage tags on mobile apps more easily, so that you can consistently measure product impressions, shopping funnel events, and more.

Drive

To make it easier to use Drive, we added enhancements to the Google Drive Android API. With the new Completion Events feature, you can see when actions are committed to the server and improve the response time to conflicts. Material design elements have been incorporated into the File Picker UI, along with the addition of Recent and Starred views. A new setParents() method enables you to organize files and folders, while the previous Contents class has been replaced with a simpler DriveContents class.

Google Fit

Initially introduced in August, the Google Fit Developer Preview has been refreshed to enable you to test your new fitness apps on any Android device. We expect to make additional changes to the APIs, so please check back with us on new developments.

Stay tuned!

We will be rolling out Google Play services 6.1 over the next few days, after which we will publish the documentation and make the SDK available.

To learn more about Google Play services and the APIs available to you through it, visit the Google Services section on the Android Developers site.

Android One: Bringing Your Apps to the Next Five Billion

Posted by Rich Hyndman, Developer Advocate

With the launch of Android One, more people across the world will have access to high-quality and affordable smartphones, packed with plenty of processing power and running the latest version of Android. These devices are available now in India and soon in Indonesia, the Philippines, and South Asia, so now is a good time to make sure your apps are ready for these new markets. This post highlights a few areas to consider.

These days, we often talk about smooth, 60fps transitions and keeping apps jank-free, and rightly so — performance is a critical metric for app quality. But in the user experience hierarchy of needs, an app should first and foremost do its job reliably and consistently.

If your app has search functionality, will user requests time out entirely? Do you think it is more important that a result is returned in a timely manner, or that the result is returned at all? If you're trying to build a robust app to reach the next five billion, it might be less about returning a result immediately, and more about returning a result at all. To address this challenge, why not include an option to users to “notify me with the results” when a search query is running on a slow network? Your app can then take as long as it needs to successfully retrieve the data in the background and show a notification when complete. The difference in user experience between an app that times out on a slower network and one that caters to user-specific needs will be very impactful for driving mobile app adoption.

There are also ways to test app performance without flying around the globe. The Android Emulator has network speed and network delay emulation settings, which can become an integral part of your testing strategy. If you’re testing on physical hardware, try turning off WiFi and switching the network to 2G only; how well does your app perform? Do search pages load? Does data refresh? These issues can often be fixed with relatively minor changes to your app logic or by leveraging a SyncAdapter. Check out our blog post on sync in the Google I/O app for more ideas.

Another key area for you to be aware of is app memory utilization. As part of the KitKat launch, we added new tools to the SDK for analyzing memory use and new APIs like isLowRamDevice(). We also just added a Memory Monitor to Android Studio 0.8.10 (currently in Canary). Much of this is documented in our Best Practices for Performance guide.

Moving forward, the Android L release has a strong focus on battery usage and analysis. Project Volta introduces new tools, such as Battery Historian and new APIs like JobScheduler, that can really help optimize battery use of your app.

By ensuring your app works well on slower networks, uses minimal memory, minimizes battery usage and doesn’t have a larger-than-necessary APK, you will help the next five billion discover, use and love your app.

10 September 2014

Conference Data Sync and GCM in the Google I/O App

By Bruno Oliveira, tech lead of the 2014 Google I/O mobile app

Keeping data in sync with the cloud is an important part of many applications, and the Google I/O App is no exception. To do this, we leverage the standard Android mechanism for this purpose: a Sync Adapter. Using a Sync Adapter has many benefits over using a more rudimentary mechanism such as setting up recurring alarms, because the system automatically handles the scheduling of Sync Adapters to optimize battery life.

We store the data in a local SQLite database. However, rather than having the whole application access that database directly, the application employs another standard Android mechanism to control and organize access to that data. This structure is, naturally, a Content Provider. Only the content provider's implementation has direct access to the SQLite database. All other parts of the app can only access data through the Content Resolver. This allows for a very flexible decoupling between the representation of the data in the database and the more abstract view of that data that is used throughout the app.

The I/O app maintains with two main kinds of data: conference data (sessions, speakers, rooms, etc) and user data (the user's personalized schedule). Conference data is kept up to date with a one-way sync from a set of JSON files stored in Google Cloud Storage, whereas user data goes through a two-way sync with a file stored in the user's Google Drive AppData folder.

Downloading Conference Data Efficiently

For a conference like Google I/O, conference data can be somewhat large. It consists of information about all the sessions, rooms, speakers, map locations, social hashtags, video library items and others. Downloading the whole data set repeatedly would be wasteful both in terms of battery and bandwidth, so we adopt a strategy to minimize the amount of data we download and process.

This strategy is separating the data into several different JSON files, and having them be referenced by a central master JSON file called the manifest file. The URL of the manifest file is the only URL that is hard-coded into the app (it is defined by the MANIFEST_URL constant in Config.java). Note that the I/O app uses Google Cloud Storage to store and serve these files, but any robust hosting service accessible via HTTP can be used for the same purpose.

The first part of the sync process is checking if the manifest file was changed since the app last downloaded it, and processing it only if it's newer. This logic is implemented by the fetchConfenceDataIfNewer method in RemoteConferenceDataFetcher.

public class RemoteConferenceDataFetcher {
    // (...)
    public String[] fetchConferenceDataIfNewer(String refTimestamp) throws IOException {
        BasicHttpClient httpClient = new BasicHttpClient();
        httpClient.setRequestLogger(mQuietLogger);
        // (...)

        // Only download if data is newer than refTimestamp
        if (!TextUtils.isEmpty(refTimestamp) && TimeUtils
            .isValidFormatForIfModifiedSinceHeader(refTimestamp)) {
                httpClient.addHeader("If-Modified-Since", refTimestamp);
            }
        }

        HttpResponse response = httpClient.get(mManifestUrl, null);
        int status = response.getStatus();
        if (status == HttpURLConnection.HTTP_OK) {
            // Data modified since we last checked -- process it!
        } else if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
            // data on the server is not newer than our data - no work to do!
            return null;
        } else {
            // (handle error)
        }
    }
    // (...)
}

Notice that we submit the HTTP If-Modified-Since header with our request, so that if the manifest hasn't changed since we last checked it, we will get an HTTP response code of HTTP_NOT_MODIFIED rather than HTTP_OK, we will react by skipping the download and parsing process. This means that unless the manifest has changed since we last saw it, the sync process is very economical: it consists only of a single HTTP request and a short response.

The manifest file's format is straightforward: it consists of references to other JSON files that contain the relevant pieces of the conference data:

{
  "format": "iosched-json-v1",
  "data_files": [
    "past_io_videolibrary_v5.json",
    "experts_v11.json",
    "hashtags_v8.json",
    "blocks_v10.json",
    "map_v11.json",
    "keynote_v10.json",
    "partners_v2.json",
    "session_data_v2.681.json"
  ]
}

The sync process then proceeds to process each of the listed data files in order. This part is also implemented to be as economical as possible: if we detect that we already have a cached version of a specific data file, we skip it entirely and use our local cache instead. This task is done by the processManifest method.

Then, each JSON file is parsed and the entities present in each one are accumulated in memory. At the end of this process, the data is written to the Content Provider.

Issuing Content Provider Operations Efficiently

The conference data sync needs to be efficient not only in the amount of data it downloads, but also in the amount of operations it performs on the database. This must be done as economically as possible, so this step is also optimized: instead of overwriting the whole database with the new data, the Sync Adapter attempts to preserve the existing entities and only update the ones that have changed. In our tests, this optimization step reduced the total sync time from 16 seconds to around 2 seconds on our test devices.

In order to accomplish this important third layer of optimization, the application needs to know, given an entity in memory and its version in the Content Provider, whether or not we need to issue content provider operations to update that entity. Comparing the entity in memory to the entity in the database field by field is one option, but is cumbersome and slow, since it would require us to read every field. Instead, we add a field to each entity called the import hashcode. The import hashcode is a weak hash value generated from its data. For example, here is how the import hashcode for a speaker is computed:

public class Speaker {
    public String id;
    public String publicPlusId;
    public String bio;
    public String name;
    public String company;
    public String plusoneUrl;
    public String thumbnailUrl;

    public String getImportHashcode() {
        StringBuilder sb = new StringBuilder();
        sb.append("id").append(id == null ? "" : id)
                .append("publicPlusId")
                .append(publicPlusId == null ? "" : publicPlusId)
                .append("bio")
                .append(bio == null ? "" : bio)
                .append("name")
                .append(name == null ? "" : name)
                .append("company")
                .append(company== null ? "" : company)
                .append("plusoneUrl")
                .append(plusoneUrl == null ? "" : plusoneUrl)
                .append("thumbnailUrl")
                .append(thumbnailUrl == null ? "" : thumbnailUrl);
        String result = sb.toString();
        return String.format(Locale.US, "%08x%08x", 
            result.hashCode(), result.length());
    }
}

Every time an entity is updated in the database, its import hashcode is saved with it as a database column. Later, when we have a candidate for an updated version of that entity, all we need to do is compute the import hashcode of the candidate and compare it to the import hashcode of the entity in the database. If they differ, then we issue Content Provider operations to update the entity in the database. If they are the same, we skip that entity. This incremental update logic can be seen, for example, in the makeContentProviderOperations method of the SpeakersHandler class:

public class SpeakersHandler extends JSONHandler {
    private HashMap mSpeakers = new HashMap();

    // (...)
    @Override
    public void makeContentProviderOperations(ArrayList list) {
        // (...)
        int updatedSpeakers = 0;
        for (Speaker speaker : mSpeakers.values()) {
            String hashCode = speaker.getImportHashcode();
            speakersToKeep.add(speaker.id);

            if (!isIncrementalUpdate || !speakerHashcodes.containsKey(speaker.id) ||
                    !speakerHashcodes.get(speaker.id).equals(hashCode)) {
                // speaker is new/updated, so issue content provider operations
                ++updatedSpeakers;
                boolean isNew = !isIncrementalUpdate || 
                    !speakerHashcodes.containsKey(speaker.id);
                buildSpeaker(isNew, speaker, list);
            }
        }

        // delete obsolete speakers
        int deletedSpeakers = 0;
        if (isIncrementalUpdate) {
            for (String speakerId : speakerHashcodes.keySet()) {
                if (!speakersToKeep.contains(speakerId)) {
                    buildDeleteOperation(speakerId, list);
                    ++deletedSpeakers;
                }
            }
        }
    }
}

The buildSpeaker and buildDeleteOperation methods (omitted here for brevity) simply build the Content Provider operations necessary to, respectively, insert/update a speaker or delete a speaker from the Content Provider. Notice that this approach means we only issue Content Provider operations to update a speaker if the import hashcode has changed. We also deal with obsolete speakers, that is, speakers that were in the database but were not referenced by the incoming data, and we issue delete operations for those speakers.

Making Sync Robust

The sync adapter in the I/O app is responsible for several tasks, amongst which are the remote conference data sync, the user schedule sync and also the user feedback sync. Failures can happen in any of them because of network conditions and other factors. However, a failure in one of the tasks should not impact the execution of the other tasks. This is why we structure the sync process as a series of independent tasks, each protected by a try/catch block, as can be seen in the performSync method of the SyncHelper class:

// remote sync consists of these operations, which we try one by one (and
// tolerate individual failures on each)
final int OP_REMOTE_SYNC = 0;
final int OP_USER_SCHEDULE_SYNC = 1;
final int OP_USER_FEEDBACK_SYNC = 2;

int[] opsToPerform = userDataOnly ?
        new int[] { OP_USER_SCHEDULE_SYNC } :
        new int[] { OP_REMOTE_SYNC, OP_USER_SCHEDULE_SYNC, OP_USER_FEEDBACK_SYNC};

for (int op : opsToPerform) {
    try {
        switch (op) {
            case OP_REMOTE_SYNC:
                dataChanged |= doRemoteSync();
                break;
            case OP_USER_SCHEDULE_SYNC:
                dataChanged |= doUserScheduleSync(account.name);
                break;
            case OP_USER_FEEDBACK_SYNC:
                doUserFeedbackSync();
                break;
        }
    } catch (AuthException ex) {
        // (... handle auth error...)
    } catch (Throwable throwable) {
        // (... handle other error...)

        // Let system know an exception happened:
        if (syncResult != null && syncResult.stats != null) {
            ++syncResult.stats.numIoExceptions;
        }
    }
}

When one particular part of the sync process fails, we let the system know about it by increasing syncResult.stats.numIoExceptions. This will cause the system to retry the sync at a later time, using exponential backoff.

When Should We Sync? Enter GCM.

It's very important for users to be able to get updates about conference data in a timely manner, especially during (and in the few days leading up to) Google I/O. A naïve way to solve this problem is simply making the app poll the server repeatedly for updates. Naturally, this causes problems with bandwidth and battery consumption.

To solve this problem in a more elegant way, we use GCM (Google Cloud Messaging). Whenever there is an update to the data on the server side, the server sends a GCM message to all registered devices. Upon receipt of this GCM message, the device performs a sync to download the new conference data. The GCMIntentService class handles the incoming GCM messages:

public class GCMIntentService extends GCMBaseIntentService {
    private static final String TAG = makeLogTag("GCM");

    private static final Map MESSAGE_RECEIVERS;
    static {
        // Known messages and their GCM message receivers
        Map  receivers = new HashMap();
        receivers.put("test", new TestCommand());
        receivers.put("announcement", new AnnouncementCommand());
        receivers.put("sync_schedule", new SyncCommand());
        receivers.put("sync_user", new SyncUserCommand());
        receivers.put("notification", new NotificationCommand());
        MESSAGE_RECEIVERS = Collections.unmodifiableMap(receivers);
    }

    // (...)

    @Override
    protected void onMessage(Context context, Intent intent) {
        String action = intent.getStringExtra("action");
        String extraData = intent.getStringExtra("extraData");
        LOGD(TAG, "Got GCM message, action=" + action + ", extraData=" + extraData);

        if (action == null) {
            LOGE(TAG, "Message received without command action");
            return;
        }

        action = action.toLowerCase();
        GCMCommand command = MESSAGE_RECEIVERS.get(action);
        if (command == null) {
            LOGE(TAG, "Unknown command received: " + action);
        } else {
            command.execute(this, action, extraData);
        }

    }
    // (...)
}

Notice that the onMessage method delivers the message to the appropriate handler depending on the GCM message's "action" field. If the action field is "sync_schedule", the application delivers the message to an instance of the SyncCommand class, which causes a sync to happen. Incidentally, notice that the implementation of the SyncCommand class allows the GCM message to specify a jitter parameter, which causes it to trigger a sync not immediately but at a random time in the future within the jitter interval. This spreads out the syncs evenly over a period of time rather than forcing all clients to sync simultaneously, and thus prevents a sudden peak in requests on the server side.

Syncing User Data

The I/O app allows the user to build their own personalized schedule by choosing which sessions they are interested in attending. This data must be shared across the user's Android devices, and also between the I/O website and Android. This means this data has to be stored in the cloud, in the user's Google account. We chose to use the Google Drive AppData folder for this task.

User data is synced to Google Drive by the doUserScheduleSync method of the SyncHelper class. If you dive into the source code, you will notice that this method essentially accesses the Google Drive AppData folder through the Google Drive HTTP API, then reconciles the set of sessions in the data with the set of sessions starred by the user on the device, and issues the necessary modifications to the cloud if there are locally updated sessions.

This means that if the user selects one session on their Android device and then selects another session on the I/O website, the result should be that both the Android device and the I/O website will show that both sessions are in the user's schedule.

Also, whenever the user adds or removes a session on the I/O website, the data on all their Android devices should be updated, and vice versa. To accomplish that, the I/O website sends our GCM server a notification every time the user makes a change to their schedule; the GCM server, in turn, sends a GCM message to all the devices owned by that user in order to cause them to sync their user data. The same mechanism works across the user's devices as well: when one device updates the data, it issues a GCM message to all other devices.

Conclusion

Serving fresh data is a key component of many Android apps. This article showed how the I/O app deals with the challenges of keeping the data up-to-date while minimizing network traffic and database changes, and also keeping this data in sync across different platforms and devices through the use of Google Cloud Storage, Google Drive and Google Cloud Messaging.

02 September 2014

The Beautiful Design Summer 2014 Collection on Google Play

Posted by Marco Paglia, Android Design Team

It’s that time again! Last summer, we published the first Beautiful Design collection on Google Play, and updated it in the winter with a fresh set of beautifully crafted apps.

Since then, developers have been hard at work updating their existing apps with new design ideas, and many new apps targeted to phones and tablets have launched on Google Play sporting exquisite detail in their UIs. Some apps are even starting to incorporate elements from material design, which is great to see. We’re on the lookout for even more material design concepts applied across the Google Play ecosystem!

Today, we're refreshing the Beautiful Design collection with our latest favorite specimens of delightful design from Google Play. As a reminder, the goal of this collection is to highlight beautiful apps with masterfully crafted design details such as beautiful presentation of photos, crisp and meaningful layout and typography, and delightful yet intuitive gestures and transitions.

The newly updated Beautiful Design Summer 2014 collection includes:

Flight Track 5, whose gorgeously detailed flight info, full of maps and interactive charts, stylishly keeps you in the know.

Oyster, a book-reading app whose clean, focused reading experience and delightful discovery makes it a joy to take your library with you, wherever you go.

Gogobot, an app whose bright colors and big images make exploring your next city delightful and fun.

Lumosity, Vivino, FIFA, Duolingo, SeriesGuide, Spotify, Runtastic, Yahoo News Digest… each with delightful design details.

Airbnb, a veteran of the collection from this past winter, remains as they continue to finesse their app.

If you’re an Android designer or developer, make sure to play with some of these apps to get a sense for the types of design details that can separate good apps from great ones. And remember to review the material design spec for ideas on how to design your next beautiful Android app!.


25 August 2014

Powerful New Messaging Features with GCM

By Subir Jhanb, Google Cloud Messaging team

Developers from all segments are increasingly relying on Google Cloud Messaging (GCM) to handle their messaging needs and make sure that their apps stay battery-friendly. GCM has been experiencing incredible momentum, with more than 100,000 apps registered, 700,000 QPS, and 300% QPS growth over the past year.

At Google I/O we announced the general availability of several GCM capabilities, including the GCM Cloud Connection Server, User Notifications, and a new API called Delivery Receipt. This post highlights the new features and how you can use them in your apps. You can watch these and other GCM announcements at our I/O presentation.

Two-way XMPP messaging with Cloud Connection Server

XMPP-based Cloud Connection Server (CCS) provides a persistent, asynchronous, bidirectional connection to Google servers. You can use the connection to send and receive messages between your server and your users' GCM-connected devices. Apps can now send upstream messages using CCS, without needing to manage network connections. This helps keep battery and data usage to a minimum. You can establish up to 100 XMPP connections and have up to 100 outstanding messages per connection. CCS is available for both Android and Chrome.

User notifications managed across multiple devices

Nowadays users have multiple devices and hence receive notifications multiple times. This can reduce notifications from being a useful feature to being an annoyance. Thankfully, the GCM User Notifications API provides a convenient way to reach all devices for a user and help you synchronise notifications including dismissals - when the user dismisses a notification on one device, the notification disappears automatically from all the other devices. User Notifications is available on both HTTP and XMPP.

Insight into message status through delivery receipts

When sending messages to a device, a common request from developers is to get more insight on the state of the message and to know if it was delivered. This is now available using CCS with the new Delivery Receipt API. A receipt is sent as soon as the message is sent to the endpoint, and you can also use upstream for app level delivery receipt.

How to get started

If you’re already using GCM, you can take advantage of these new features right away. If you haven't used GCM yet, you’ll be surprised at how easy it is to set up — get started today! And remember, GCM is completely free no matter how big your messaging needs are.

To learn more about GCM and its new features — CCS, user notifications, and Delivery Receipt — take a look at the I/O Bytes video below and read our developer documentation.

05 August 2014

Material design in the 2014 Google I/O app

By Roman Nurik, lead designer for the Google I/O Android App

Every year for Google I/O, we publish an Android app for the conference that serves two purposes. First, it serves as a companion for conference attendees and those tuning in from home, with a personalized schedule, a browsing interface for talks, and more. Second, and arguably more importantly, it serves as a reference demo for Android design and development best practices.

Last week, we announced that the Google I/O 2014 app source code is now available, so you can go check out how we implemented some of the features and design details you got to play with during the conference. In this post, I’ll share a glimpse into some of our design thinking for this year’s app.

On the design front, this year’s I/O app uses the new material design approach and features of the Android L Developer Preview to present content in a rational, consistent, adaptive and beautiful way. Let’s take a look at some of the design decisions and outcomes that informed the design of the app.

Surfaces and shadows

In material design, surfaces and shadows play an important role in conveying the structure of your app. The material design spec outlines a set of layout principles that helps guide decisions like when and where shadows should appear. As an example, here are some of the iterations we went through for the schedule screen:

First iteration
Second iteration
Third iteration

The first iteration was problematic for a number of reasons. First, the single shadow below the app bar conveyed that there were two “sheets” of paper: one for the app bar and another for the tabs and screen contents. The bottom sheet was too complex: the “ink” that represents the contents of a sheet should be pretty simple; here ink was doing too much work, and the result was visual noise. An alternative could be to make the tabs a third sheet, sitting between the app bar and content, but too much layering can also be distracting.

The second and third iterations were stronger, creating a clear separation between chrome and content, and letting the ink focus on painting text, icons, and accent strips.

Another area where the concept of “surfaces” played a role was in our details page. In our first release, as you scroll the details screen, the top banner fades from the session image to the session color, and the photo scrolls at half the speed beneath the session title, producing a parallax effect. Our concern was that this design bent the physics of material design too far. It’s as if the text was sliding along a piece of paper whose transparency changed throughout the animation.

A better approach, which we introduced in the app update on June 25th, was to introduce a new, shorter surface on which the title text was printed. This surface has a consistent color and opacity. Before scrolling, it’s adjacent to the sheet containing the body text, forming a seam. As you scroll, this surface (and the floating action button attached to it) rises above the body text sheet, allowing the body text to scroll beneath it.

This aligns much better with the physics in the world of material design, and the end result is a more coherent visual, interaction and motion story for users. (See the code: Fragment, Layout XML)

Color

A key principle of material design is also that interfaces should be “bold, graphic, intentional” and that the foundational elements of print-based design should guide visual treatments. Let’s take a look at two such elements: color and margins.

In material design, UI element color palettes generally consist of one primary and one accent color. Large color fields (like the app bar background) take on the main 500 shade of the primary color, while smaller areas like the status bar use a darker shade, e.g. 700.

The accent color is used more subtly throughout the app, to call attention to key elements. The resulting juxtaposition of a tamer primary color and a brighter accent, gives apps a bold, colorful look without overwhelming the app’s actual content.

In the I/O app, we chose two accents, used in various situations. Most accents were Pink 500, while the more conservative Light Blue 500 was a better fit for the Add to Schedule button, which was often adjacent to session colors. (See the code: XML color definitions, Theme XML)

And speaking of session colors, we color each session’s detail screen based on the session’s primary topic. We used the base material design color palette with minor tweaks to ensure consistent brightness and optimal contrast with the floating action button and session images.

Below is an excerpt from our final session color palette exploration file.

Session colors, with floating action button juxtaposed to evaluate contrast
Desaturated session colors, to evaluate brightness consistency across the palette

Margins

Another important “traditional print design” element that we thought about was margins, and more specifically keylines. While we’d already been accustomed to using a 4dp grid for vertical sizing (buttons and simple list items were 48dp, the standard action bar was 56dp, etc.), guidance on keylines was new in material design. Particularly, aligning titles and other textual items to keyline 2 (72dp on phones and 80dp on tablets) immediately instilled a clean, print-like rhythm to our screens, and allowed for very fast scanning of information on a screen. Gestalt principles, for the win!

Grids

Another key principle in material design is “one adaptive design”:

A single underlying design system organizes interactions and space. Each device reflects a different view of the same underlying system. Each view is tailored to the size and interaction appropriate for that device. Colors, iconography, hierarchy, and spatial relationships remain constant.

Now, many of the screens in the I/O app represent collections of sessions. For presenting collections, material design offers a number of containers: cards, lists, and grids. We originally thought to use cards to represent session items, but since we’re mostly showing homogenous content, we deemed cards inappropriate for our use case. The shadows and rounded edges of the cards would add too much visual clutter, and wouldn’t aid in visually grouping content. An adaptive grid was a better choice here; we could vary the number of columns on screen size (see the code), and we were free to integrate text and images in places where we needed to conserve space.

Delightful details

Two of the little details we spent a lot of time perfecting in the app, especially with the L Developer Preview, were touch ripples and the Add to Schedule floating action button.

We used both the clipped and unclipped ripple styles throughout the app, and made sure to customize the ripple color to ensure the ripples were visible (but still subtle) regardless of the background. (See the code: Light ripples, Dark ripples)

But one of our favorite details in the app is the floating action button that toggles whether a session shows up in your personalized schedule or not:

We used a number of new API methods in the L preview (along with a fallback implementation) to ensure this felt right:

  1. View.setOutline and setClipToOutline for circle-clipping and dynamic shadow rendering.
  2. android:stateListAnimator to lift the button toward your finger on press (increase the drop shadow)
  3. RippleDrawable for ink touch feedback on press
  4. ViewAnimationUtils.createCircularReveal for the blue/white background state reveal
  5. AnimatedStateListDrawable to define the frame animations for changes to icon states (from checked to unchecked)

The end result is a delightful and whimsical UI element that we’re really proud of, and hope that you can draw inspiration from or simply drop into your own apps.

What’s next?

And speaking of dropping code into your own apps, remember that all the source behind the app, including L Developer Preview features and fallback code paths, is now available, so go check it out to see how we implemented these designs.

We hope this post has given you some ideas for how you can use material design to build beautiful Android apps that make the most of the platform. Stay tuned for more posts related to this year’s I/O app open source release over the coming weeks to get even more great ideas for ways to deliver the best experience to your users.