Skip to content

Software Development Blogs: Programming, Software Testing, Agile Project Management

Methods & Tools

Subscribe to Methods & Tools
if you are not afraid to read more than one page to be a smarter software developer, software tester or project manager!

Android Developers Blog
Syndicate content
An Open Handset Alliance Project.
Updated: 1 day 22 hours ago

What's New in Android 5.0 Lollipop

Mon, 10/20/2014 - 20:18

By Ankur Kotwal, Developer Advocate

Android 5.0 Lollipop is the biggest update of Android to date, introducing an all new visual style, improved performance, and much more. Android 5.0 Lollipop also extends across screens big and small, including phones, tablets, wearables, TVs and cars, to give your users access to information when they need it most.

To get you started on developing and testing on Android 5.0 Lollipop, here are some of the developer highlights with links to related videos and documentation.

User experience
  • Material design for the multiscreen world — Material Design is a new approach for designing apps in today’s multi-device world that takes a comprehensive strategy to visual, motion, and interaction design across a number of platforms and form factors. Android 5.0 brings Material Design to the platform, with a full set of tools for implementing material design in your apps. The system is incredibly flexible, allowing your app to express its individual character and brand with bold colors and a variety of responsive UI patterns and themeable elements.
  • Enhanced notifications — New lockscreen notifications let you surface content, updates, and actions to users at a glance, without needing to unlock their device. Heads-up notifications let you display content and actions in a small floating window managed by the system, no matter which app is in the foreground. Notifications are refreshed for Material Design and you can use accent colors to express your brand.
  • Concurrent documents in Overview — Now you can organize your app by tasks and present these concurrently as individual “documents” on the Overview screen. For example, instant messaging apps could declare each chat as a separate document. Users can flip through these on the Overview screen to find the specific chat they want and jump straight to it.
Performance
  • Android Runtime (ART) — Android 5.0 runs exclusively on the ART runtime. ART offers ahead-of-time (AOT) compilation, more efficient garbage collection, and improved development and debugging features. In many cases it improves performance of the device, without you having to change your code.
  • 64-bit support — Support for 64-bit ABIs provides additional address space and improved performance with certain compute workloads. Apps written in the Java language can run immediately on 64-bit architectures with no modifications required. NDK r10c includes 64-bit support, for apps and games using native code.
  • Project Volta — New tools and APIs help you build battery-efficient apps. Battery Historian, a tool included in the SDK, lets you visualize power events over time and understand how your app is using battery. The JobScheduler API lets you set the conditions under which your background tasks and other jobs should run, such as when the device is idle or connected to an unmetered network or to a charger, to minimize battery impact. More in this I/O video.
  • OpenGL ES 3.1 and Android Extension Pack — With OpenGL ES 3.1, you get compute shaders, stencil textures, and texture gather for your games. Android Extension Pack (AEP) is a new set of extensions to OpenGL ES that bring desktop-class graphics to Android including tessellation and geometry shaders, and use ASTC texture compression across GPU technologies. More on what's new for game developers in this DevBytes video.
  • WebView updates — We’ve updated WebView to support WebRTC, WebAudio and WebGL will be supported. WebView also includes native support for all of the Web Components specifications: Custom Elements, Shadow DOM, HTML Imports, and Templates. WebView is now unbundled from the system and will be regularly updated through Google Play.
Workplace
  • Managed provisioning and unified view of apps — to make it easier for employees to have a single device for personal and work use, framework enhancements offer a unified view of apps, notifications & recents across work apps and personal apps. Profile owner APIs, in the workplace context, let administrators create and manage work profiles and defined as part of a new managed provisioning process. More in this I/O video.
Media
  • Advanced camera capabilities — A new camera API gives you new capabilities for advanced image capture and processing. On supported devices, your app can capture uncompressed YUV capture at full 8 megapixel resolution at 30 FPS. You can also capture raw sensor data and control parameters such as exposure time, ISO sensitivity, and frame duration, on a per-frame basis.
  • Audio improvements — The sound architecture has been enhanced, with lower input latency in OpenSL, the addition of multichannel-mixing, and USB digital audio mode support. More in this I/O video.
Connectivity
  • BLE Peripheral Mode — Android devices can now function in Bluetooth Low Energy (BLE) peripheral mode. Apps can use this capability to broadcast their presence to nearby devices — for example, you can now build apps that let a device function as a beacon and transmit data to another BLE device. More in this I/O video.
  • Multi-networking — Apps can dynamically request networks based on capabilities such as metered or unmetered. This is useful when you want to use a specific network, such as cellular. Apps can also request platform to re-evaluate networks for an internet connection. This is useful when your app sees unusually high latency on a particular network, it can enable the platform to switch to a better network (if available) sooner with a graceful handoff.
Get started!

You can get started developing and testing on Android 5.0 right away by downloading the Android 5.0 Platform (API level 21), as well as the SDK Tools, Platform Tools, and Support Package from the Android SDK Manager.

Check out the DevByte video below for more of what’s new in Lollipop!



Join the discussion on
+Android Developers


Categories: Programming

Android 5.0 Lollipop SDK and Nexus Preview Images

Sun, 10/19/2014 - 07:12

Two more weeks!

By Jamal Eason, Product Manager, Android

At Google I/O last June, we gave you an early version of Android 5.0 with the L Developer Preview, running on Nexus 5, Nexus 7 and Android TV. Over the course of the L Developer Preview program, you’ve given us great feedback and we appreciate the engagement from you, our developer community. Thanks!

This week, we announced Android 5.0 Lollipop. Starting today, you can download the full release of the Android 5.0 SDK, along with updated developer images for Nexus 5, Nexus 7 (2013), ADT-1, and the Android emulator.

The first set of devices to run this new version of Android -- Nexus 6, Nexus 9, and Nexus Player -- will be available in early November. In the same timeframe, we'll also roll out the Android 5.0 update worldwide to Nexus 4, 5, 7 (2012 & 2013), and 10 devices, as well as to Google Play edition devices.

Therefore, now is the time to test your apps on the new platform. You have two more weeks to get ready!

What’s in Lollipop?

Android 5.0 Lollipop introduces a host of new APIs and features including:

There's much more, so check out the Android 5.0 platform highlights for a complete overview.

What’s in the Android 5.0 SDK?

The Android 5.0 SDK includes updated tools and new developer system images for testing. You can develop against the latest Android platform using API level 21 and take advantage of the updated support library to implement Material Design as well as the leanback user interface for TV apps.

You can download these components through the Android SDK Manager and develop your app in Android Studio:

  • Android 5.0 SDK Platform & Tools
  • Android 5.0 Emulator System Image - 32-bit & 64-bit (x86)
  • Android 5.0 Emulator System Image for Android TV (32-bit)
  • Android v7 appcompat Support Library for Material Design theme backwards capability
  • Android v17 leanback library for Android TV app support

For developers using the Android NDK for native C/C++ Android apps we have:

For developers on Android TV devices we have:

  • Android 5.0 system image over the air (OTA) update for ADT-1 Developer Kit. OTA updates will appear over the next few days.

Similar to our previous release of the preview, we are also providing updated system image downloads for Nexus 5 & Nexus 7 (2013) devices to help with your testing as well. These images support the Android 5.0 SDK, but only have the minimal apps pre-installed in order to enable developer testing:

  • Nexus 5 (GSM/LTE) “hammerhead” Device System Image
  • Nexus 7 (2013) - (Wifi) “razor” Device System Image

For the developer preview versions, there will not be an over the air (OTA) update. You will need to wipe and reflash your developer device to use the latest developer preview versions. If you want to receive the official consumer OTA update in November and any other official updates, you will have to have a factory image on your Nexus device.

Validate your apps with the Android 5.0 SDK

With the consumer availability of Android 5.0 and the Nexus 6, Nexus 9, and Nexus Player right around the corner, here are a few things you should do to prepare:

  1. Get the emulator system images through the SDK Manager or download the Nexus device system images.
  2. Recompile your apps against Android 5.0 SDK, especially if you used any preview APIs. Note: APIs have changed between the preview SDK and the final SDK.
  3. Validate that your current Android apps run on the new API 21 level with ART enabled. And if you use the NDK for your C/C++ Android apps, validate against the 64-bit emulator. ART is enabled by default on API 21 & new Android devices with Android 5.0.

Once you validate your current app, explore the new APIs and features for Android 5.0.

Migrate Your Existing App to Material Design

Android 5.0 Lollipop introduces Material Design, which enables your apps to adopt a bold, colorful, and flexible design, while remaining true to a small set of key principles that guide user interaction across multiple screens and devices.

After making sure your current apps work with Android 5.0, now is the time to enable the Material theme in your app with the AppCompat support library. For quick tips & recommendations for making your app shine with Material Design, check out our Material Design guidelines and tablet optimization tips. For those of you new to Material Design, check out our Getting Started guide.

Get your apps ready for Google Play!

Starting today, you can publish your apps that are targeting Android 5.0 Lollipop to Google Play. In your app manifest, update android:targetSdkVersion to "21", test your app, and upload it to the Google Play Developer Console.

Starting November 3rd, Nexus 9 will be the first device available to consumers that will run Android 5.0. Therefore, it is a great time to publish on Google Play, once you've updated and tested your app. Even if your apps target earlier versions of Android, take a few moments to test them on the Android 5.0 system images, and publish any updates needed in advance of the Android 5.0 rollout.

Stay tuned for more details on the Nexus 6 and Nexus 9 devices, and how to make sure your apps look their best on them.

Next up, Android TV!

We also announced the first consumer Android TV device, Nexus Player. It’s a streaming media player for movies, music and videos, and also a first-of-its-kind Android gaming device. Users can play games on their HDTVs with a gamepad, then keep playing on their phones while they’re on the road. The device is also Google Cast-enabled, so users can cast your app from their phones or tablets to their TV.

If you’re developing for Android TV, watch for more information on November 3rd about how to distribute your apps to Android TV users through the Google Play Developer Console. You can start getting your app ready by making sure it meets all of the TV Quality Guidelines.

Get started with Android 5.0 Lollipop platform

If you haven’t had a chance to take a look at this new version of Android yet, download the SDK and get started today. You can learn more about what’s new in the Android 5.0 platform highlights and get all the details on new APIs and changed behaviors in the API Overview. You can also check out the latest DevBytes videos to learn more about Android 5.0 features.

Enjoy this new release of Android!

Join the discussion on

+Android Developers
Categories: Programming

Google Play Services 6.1

Wed, 10/08/2014 - 19:05
gps

Google Play services 6.1 is now rolled out to devices worldwide, bringing you the newest features from Google to help you optimize your apps. You can get started developing today by downloading the Google Play services SDK from the Android SDK Manager.

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.

Learn more about how to use these new features in this DevBytes video.

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.

Get Started

To get started developing, download the latest Google Play services SDK from the Android SDK Manager. For details on the new APIs, take a look at the New Features documentation. For setup information, see Set Up Google Play Services SDK.

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.

We hope you enjoy this release of Google Play services!




Join the discussion on
+Android Developers


Categories: Programming

Updated Cross-Platform Tools in Google Play Game Services

Tue, 10/07/2014 - 22:51

By Ben Frenkel, Google Play Games team

Game services UIs are now updated for material design, across all of the SDKs.

Game developers, we've updated some of our popular developer tools to give you a consistent set of game services across platforms, a refreshed UI based on material design, and new tools to give you better visibility into what users are doing in your games.

Let’s take a look at the new features.

Real-time Multiplayer in the Play Games cross-platform C++ SDK

To make it easier to build cross-platform games, we’ve added Real-Time Multiplayer (RTMP) to the latest Google Play Games C++ SDK. The addition of RTMP brings the C++ SDK to feature parity with the Play services SDK on Android and the Play Games iOS SDK. Learn more »

Material Design refresh across Android, cross-platform C++, and iOS SDKs

We’ve incorporated material design into the user-interface of the latest Play Games services SDKs for Android, cross-platform C++, and iOS. This gives you a bold, colorful design that’s consistent across all of your games, for all of your users. Learn more »

New quests features and completion statistics

Quests are a popular way to increase player engagement by adding fresh content without updating your game. We’ve added some new features to quests to make them easier to implement and manage.

First, we’ve simplified quests implementations by providing out-of-the-box toasts for “quest accepted” and “quest completed” events. You can invoke these toasts from your game with just a single call, on any platform. This removes the need to create your own custom toasts, though you are still free to do so.

You also have more insight into how your quests are performing through new in-line quest stats in the Developer Console. With these stats, you can better monitor how many people are completing their quests, so you can adjust the criteria to make them easier to achieve, if needed. Learn more »

Last, we’ve eliminated the 24-hour lead-time requirement for publishing and allowing repeating quests to have the same name. You now have the freedom to publish quests whenever you want with whatever name you want.

New quest stats let you see how many users are completing their quests.

Multiplayer game statistics

Now when you add multiplayer support through Google Play game services, you get multiplayer stats for free, without having to implement a custom logging solution. You can simply visit the Developer Console to see how players are using your multiplayer integration and look at trends in overall usage. The new stats are available as tabs under the Engagement section. Learn more »

Multiplayer stats let you see trends in how players are using your app's multiplayer integration.

New game services insights and alerts

We’re continuing to expand the types of alerts we offer the Developer Console to let you know about more types of issues that might be affecting your users' gameplay experiences. You’ll now get an alert when you have a broken implementation of real-time and turn-based multiplayer, and we’ll also notify you if your Achievements and Leaderboard implementations use too many duplicate images. Learn more »

Get Started

You can get started with all of these new features right away. Visit the Google Play game services developer site to download the updated SDKs. For migration details on the Game Services SDK for iOS, see the release notes. You can take a look at the new stats and alerts by visiting the Google Play Developer Console.

Join the discussion on

+Android Developers
Categories: Programming

Tips for Error Handling with Android Wear APIs

Sat, 10/04/2014 - 04:54

By +Wayne Piekarski, Developer Advocate, Android Wear

For developers using the Android Wear APIs in Google Play services, it is important to correctly handle all the error conditions that can occur on legacy phones or when users do not have a wearable device. This post describes the best practice in handling error conditions with the GoogleApiClient connect() method. If you do not implement this correctly, your existing application functionality may fail for non-wearable users.

There are two ways that the connect() method can return ConnectionResult.API_UNAVAILABLE for wearable support with Google Play services:

  • When requesting Wearable.API on any device running Android 4.2 (API level 17) or earlier
  • When requesting Wearable.API when no Android Wear companion application or device is available

Google Play services provides a wide range of useful features such as integration with Google Drive, Wallet, Google+, and Google Play games services (just to name a few!). During initialization, the application uses GoogleApiClient.Builder() to make calls to addApi() to request the features that are necessary. The connect() method is then called to establish a connection to the Google Play services library, and it can return error codes if any API is not available.

If you request multiple APIs from a single GoogleApiClient, such as Drive and Wear, and the Wear support returns API_UNAVAILABLE, then the Drive request will also fail. Since Wear support is not guaranteed to be available on all devices, you should make sure to use a separate client for this request.

The best practice for developers is to implement two separate GoogleApiClient connections:

  • One connection for Android Wear support, and
  • A separate connection for all of the other APIs you need

This will ensure that the functionality of your app will remain for all users, whether or not there is wearable support available on their devices, as well as on older legacy devices.

It's important that you implement this best practice immediately, because your current users may be affected if not handled correctly in your app.

Join the discussion on

+Android Developers
Categories: Programming

Allthecooks on Android Wear

Wed, 09/24/2014 - 21:56

By Hoi Lam, Developer Advocate, Android Wear

The best cooking companion since the apron?

Android Wear is designed for serving up useful information at just the right time and in the right place. A neat example of this is Allthecooks Recipes. It gives you the right recipe, right when you need it.

This app is a great illustration of the four creative visions for Android Wear:

  1. Launched automatically
  2. Glanceable
  3. Suggest and demand
  4. Zero or low interaction

Allthecooks also shows what developers can do by combining both the power of the mobile device and the convenience of Android Wear.

Pick the best tool for the job

One particularly well-designed aspect of Allthecooks is their approach to the multi-device experience. Allthecooks lets the user search and browse the different recipes on their Android phone or tablet. When the user is ready, there is a clearly labelled blue action link to send the recipe to the watch.

The integration is natural. Using the on-screen keyboard and the larger screen real estate, Allthecooks is using the best screen to browse through the recipes. On the wearables side, the recipe is synchronised by using the DataApi and is launched automatically, fulfilling one of the key creative visions for Android Wear.

The end result? The mobile / Wear integration is seamless.

Thoughtful navigation

Once the recipe has been sent to the Android Wear device, Allthecooks splits the steps into easily glanceable pages. At the end of that list of steps, it allows the user to jump back to the beginning with a clearly marked button.

This means if you would like to browse through the steps before starting to cook, you can effortlessly get to the beginning again without swiping through all the pages. This is a great example of two other points in the vision: glanceable and zero or low interaction.

A great (cooking) assistant

One of the key ingredients of great cooking is timing, and Allthecooks is always on hand to do all the inputs for you when you are ready to start the clock. A simple tap on the blue “1” and Allthecooks will automatically set the timer to one hour. It is a gentle suggestion that Allthecooks can set the timer for you if you want.

Alternatively, if you want to use your egg timer, why not? It is a small detail but it really demonstrates the last and final element of Android Wear’s vision of suggest and demand. It is an ever ready assistant when the user wants it. At the same time, it is respectful and does not force the user to go down a route that the user does not want.

It’s about the details

Great design is about being user-centric and paying attention to details. Allthecooks could have just shrunk their mobile app for wear. Instead the Allthecooks team put a lot of thoughts into the design and leveraged all four points of the Android Wear creative vision. The end result is that the user can get the best experience out of both their Android mobile device and their Android Wear device. So developers, what will you be cooking next on Android Wear?

For more inspiring Android Wear user experiences, check out the Android Wear collection on Google Play!


Join the discussion on
+Android Developers


Categories: Programming

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

Tue, 09/23/2014 - 18:44
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:

Update (23 September 2014): Since this blog post was first published, the GCMBaseIntentService class has been deprecated. Please use the GoogleCloudMessaging API instead.

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.

Categories: Programming

Messaging on Android Wear

Wed, 09/17/2014 - 18:45

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.


Join the discussion on
+Android Developers


Categories: Programming

Google Play Services 5.0

Tue, 09/16/2014 - 22:45
gps

Google Play services 5.0 is now rolled out to devices worldwide, and it includes a number of features you can use to improve your apps. This release introduces Android wearable services APIs, Dynamic Security Provider and App Indexing, whilst also including updates to the Google Play game services, Cast, Drive, Wallet, Analytics, and Mobile Ads.

Android wearable services

Google Play services 5.0 introduces a set of APIs that make it easier to communicate with your apps running on Android wearables. The APIs provide an automatically synchronized, persistent data store and a low-latency messaging interface that let you sync data, exchange control messages, and transfer assets.

Dynamic security provider

Provides an API that apps can use to easily install a dynamic security provider. The dynamic security provider includes a replacement for the platform's secure networking APIs, which can be updated frequently for rapid delivery of security patches. The current version includes fixes for recent issues identified in OpenSSL.

Google Play game services

Quests are a new set of APIs to run time-based goals for players, and reward them without needing to update the game. To do this, you can send game activity data to the Quests service whenever a player successfully wins a level, kills an alien, or saves a rare black sheep, for example. This tells Quests what’s going on in the game, and you can use that game activity to create new Quests. By running Quests on a regular basis, you can create an unlimited number of new player experiences to drive re-engagement and retention.

Saved games lets you store a player's game progress to the cloud for use across many screen, using a new saved game snapshot API. Along with game progress, you can store a cover image, description and time-played. Players never play level 1 again when they have their progress stored with Google, and they can see where they left off when you attach a cover image and description. Adding cover images and descriptions provides additional context on the player’s progress and helps drive re-engagement through the Play Games app.

App Indexing API

The App Indexing API provides a way for you to notify Google about deep links in your native mobile applications and drive additional user engagement. Integrating with the App Indexing API allows the Google Search app to serve up your app’s history to users as instant Search suggestions, providing fast and easy access to inner pages in your app. The deep links reported using the App Indexing API are also used by Google to index your app’s content and surface them as deep links to Google search result.

Google Cast

The Google Cast SDK now includes media tracks that introduce closed caption support for Chromecast.

Drive

The Google Drive API adds the ability to sort query results, create folders offline, and select any mime type in the file picker by default.

Wallet

Wallet objects from Google take physical objects (like loyalty cards, offers) from your wallet and store them in the cloud. In this release, Wallet adds "Save to Wallet" button support for offers. When a user clicks "Save to Wallet" the offer gets saved and shows up in the user's Google Wallet app. Geo-fenced in-store notifications prompt the user to show and scan digital cards at point-of-sale, driving higher redemption. This also frees the user from having to carry around offers and loyalty cards.

Users can also now use their Google Wallet Balance to pay for Instant Buy transactions by providing split tender support. With split tender, if your Wallet Balance is not sufficient, the payment is split between your Wallet Balance and a credit/debit card in your Google Wallet.

Analytics

Enhanced Ecommerce provides visibility into the full customer journey, adding the ability to measure product impressions, product clicks, viewing product details, adding a product to a shopping cart, initiating the checkout process, internal promotions, transactions, and refunds. Together they help users gain deeper insights into the performance of their business, including how far users progress through the shopping funnel and where they are abandoning in the purchase process. Enhanced Ecommerce also allows users to analyze the effectiveness of their marketing and merchandising efforts, including the impact of internal promotions, coupons, and affiliate marketing programs.

Mobile Ads

Google Mobile Ads are a great way to monetise your apps and you now have access to better in-app purchase ads. We've now added a default implementation for consumable purchases using the Google Play In-app Billing service.

And that’s another release of Google Play services. The updated Google Play services SDK is now available through the Android SDK manager. For details on the APIs, please see New Features in Google Play services 5.0.




Join the discussion on
+Android Developers


Categories: Programming

Android One: Bringing Your Apps to the Next Five Billion

Tue, 09/16/2014 - 18:35
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.

Categories: Programming

Update on Android Wear Paid Apps

Mon, 09/08/2014 - 22:02

Update (8 September 2014): All of the issues in the post below have now been resolved in Android Studio 0.8.3 onwards, released on 21 July 2014. The gradle wearApp rule, and the packaging documentation, were updated to use res/raw. The instructions on this blog post remain correct and you can continue to use manual packaging if you want. You can upload Android Wear paid apps to the Google Play using the standard release wearApp release mechanism.

We have a workaround to enable paid apps (and other apps that use Google Play's forward-lock mechanism) on Android Wear. The assets/ directory of those apps, which contains the wearable APK, cannot be extracted or read by the wearable installer. The workaround is to place the wearable APK in the res/raw directory instead.

As per the documentation, there are two ways to package your wearable app: use the “wearApp” Gradle rule to package your wearable app or manually package the wearable app. For paid apps, the workaround is to manually package your apps with the following two changes, and you cannot use the “wearApp” Gradle rule. To manually package the wearable APK into res/raw, do the following:

  1. Copy the signed wearable app into your handheld project's res/raw directory and rename it to wearable_app.apk, it will be referred to as wearable_app.
  2. Create a res/xml/wearable_app_desc.xml file that contains the version and path information of the wearable app:
    <wearableApp package="wearable app package name">
        <versionCode>1</versionCode>
        <versionName>1.0</versionName>
        <rawPathResId>wearable_app</rawPathResId>
    </wearableApp>

    The package, versionCode, and versionName are the same as values specified in the wearable app's AndroidManifest.xml file. The rawPathResId is the static variable name of the resource. If the filename of your resource is wearable_app.apk, the static variable name would be wearable_app.

  3. Add a <meta-data> tag to your handheld app's <application> tag to reference the wearable_app_desc.xml file.
    <meta-data android:name="com.google.android.wearable.beta.app"
               android:resource="@xml/wearable_app_desc"/>
  4. Build and sign the handheld app.

We will be updating the “wearApp” Gradle rule in a future update to the Android SDK build tools to support APK embedding into res/raw. In the meantime, for paid apps you will need to follow the manual steps outlined above. We will be also be updating the documentation to reflect the above workaround. We're working to make this easier for you in the future, and we apologize for the inconvenience.


Join the discussion on
+Android Developers


Categories: Programming

The Beautiful Design Summer 2014 Collection on Google Play

Tue, 09/02/2014 - 16:10
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!.


Join the discussion on

+Android Developers
Categories: Programming

Powerful New Messaging Features with GCM

Mon, 08/25/2014 - 18:51

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.


Join the discussion on
+Android Developers


Categories: Programming

Material design in the 2014 Google I/O app

Tue, 08/05/2014 - 16:39
figure { margin: 0 0 20px 0; } figcaption { font-style: italic; opacity: 0.7; } figure img { padding: 0 !important; } blockquote { font-style: italic; }

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.


Join the discussion on
+Google Design


Categories: Programming

Learn How UX Design can Make Your App More Successful

Fri, 08/01/2014 - 02:39

By Nazmul Idris, a Developer Advocate at Google who's passionate about Android and UX design

As a mobile developer, how do you create 5-star apps that your users will not just download, but love to use every single day? How do you get your app noticed, and how do you drive engagement? One way is to focus on excellence in design — from visual and interaction design to user research, in other words: UX design.

If you’re new to the world of UX design but want to embrace it to improve your apps, we've created a new online course just for you. The UX Design for Mobile Developers course teaches you how to put your designer hat on, in addition to your developer hat, as you think about your apps' ideal user and how to meet their needs.

The course is divided into a series of lessons, each of which gives you practical takeaways that you can apply immediately to start seeing the benefits of good UX design.

Without jargon or buzzwords, the course teaches you where you should focus your attention, to bring in new users, keep existing users engaged, and increase your app's ratings. You'll learn how to optimize your app, rather than optimizing login/signup forms, and how to use low-resolution wireframing.

After you take the course, you'll "level up" from being an excellent developer to becoming an excellent design-minded developer.

Check out the video below to get a taste of what the course is like, and click through this short deck for an overview of the learning plan.

The full course materials — all the videos, quizzes, and forums — are available for free for all students by selecting “View Courseware”. Personalized ongoing feedback and guidance from Coaches is also available to anyone who chooses to enroll in Udacity’s guided program.

If that’s not enough, for even more about UX design from a developer's perspective, check out our YouTube UXD series, on the AndroidDevelopers channel: http://bit.ly/uxdplaylist.


Android Developers
at Udacity

Join the discussion on
+Android Developers


Categories: Programming

Grow with Google Play: Scaled Publishing and New App Insights

Thu, 07/31/2014 - 23:55

By Kobi Glick, Google Play team

If you're growing your business on Google Play, the Google Play Developer Console is one of the most important tools at your disposal. At Google I/O, we introduced a number of new changes that give you valuable insight into how your app is performing. Here's an overview of some of the improvements you can now take advantage of.

Publishing API for scaling your app operations

Today we're happy to announce that the Google Play Developer Publishing API is now available to all developers. The API will let you upload APKs to Beta testing, Staged rollout and Production, and integrate publishing operations with your release processes and toolchain. The Publishing API also makes it easier for you to manage your in-app products catalog, provide tablet-specific screenshots, and localize your store listing text and graphics. The Publishing API will help you focus on your core business, with less time managing your releases, even as your business grows to more apps and markets.

Actionable insights at the right time Email notifications for alerts

Recently, we added Alerts in the Developer Console to let you know when there are sudden changes in important stats like app installs, ratings, and crashes. You can now turn on email notifications for Alerts so that, even while you’re not in the Developer Console, you’ll be informed of relevant events before they can have a broader effect on your app. You can turn on email notifications for one or more of your apps under Email Preferences in the Developer Console settings.

New Optimization Tips

You’ll now see new Optimization Tips with instructions when we detect opportunities to improve your app. For example, we’ll let you know when updated versions of APIs you use are available — such as new Google Play in-app billing or Google Maps APIs. For games developers, we’ll also surface opportunities to use Google Play game services that can help improve users’ gaming experience and drive engagement. To see what tips we suggest for you, go to your app in the Developer Console and click on Optimization Tips.

Better data to inform your business decisions Enhanced revenue statistics

To help you better understand your commercial success, we’ve enhanced revenue statistics in the Finance section of the Developer Console. We now let you see the average revenue per paying user (ARPPU) and give you more ways to analyse buyer data, such as comparing returning buyers (i.e., those who also made purchases in the past) to new buyers.

Bulk export of reviews

You can already engage with your users by reading and replying to reviews in the Developer Console and we’ve now added bulk export of reviews so you can download and analyze your app’s reviews en masse. This is particularly useful if you receive a large volume of reviews and want to perform your own sentiment analysis.

Improved stats for beta releases and staged rollouts

Since last year’s launch, you’ve used beta testing to release alpha and beta versions of your app, and staged rollout to gradually launch your app to production. To help you make the most of this feature, we’re now improving the way alpha, beta and staged rollout specific stats are displayed. When viewing your app and crash statistics you can now filter the app version by alpha, beta, or staged rollout to better understand the impact of your testing.

Improved reporting of native crashes

If you develop in native code, we’ve improved the reporting and presentation specifically for native crashes, with better grouping of similar crashes and summarizing of relevant information.

Deep-linking to help drive engagement

Finally, we’ve also added website verification in the Developer Console, to enable deep-linking to your app from search results. Deep-linking helps remind users about the apps they already have. It is available through search for all apps that implement app indexing. For example, if a user with the Walmart Android app searches for “Chromecast where to buy”, they’ll go directly to the Chromecast page in the Walmart app. The new App Indexing API is now open to all Android developers, globally. Get started now.

We hope you find these features useful and take advantage of them so that you can continue to grow your user base and improve your users’ experience. If you're interested in some other great tools for distributing your apps, check out this blog post, or any of the sessions which have now been posted to the Google Developers Channel.
Join the discussion on
+Android Developers


Categories: Programming

Google I/O 2014 App Source Code Now Available

Wed, 07/30/2014 - 22:24

By Bruno Oliveira, Tech Lead of the I/O app project

The source code for the 2014 version of the Google I/O app is now available. Since its first release on Google Play a few weeks before the conference, the I/O app was downloaded by hundreds of thousands of people, including on-site attendees, I/O Extended event participants and users tuning in from home. If one of the goals of the app is to be useful to conference attendees, the other primary goal is to serve as a practical example of best practices for Android app design and development.

In addition to showing how to implement a wide variety of features that are useful for most Android apps, such as Fragments, Loaders, Services, Broadcast Receivers, alarms, notifications, SQLite databases, Content Providers, Action Bar and the Navigation Drawer, the I/O app source code also shows how to integrate with several Google products and services, from the Google Drive API to Google Cloud Messaging. It uses the material design approach, the Android L Preview APIs and full Android Wear integration with a packaged wearable app for sending session feedback.

To simplify the process of reusing and customizing the source code to build apps for other conferences, we rewrote the entire sync adapter to work with plain JSON files instead of requiring a server with a specific API. These files can be hosted on any web server of the developer's choice, and their format is fully documented.

Storing and syncing the user's data (that is, the personalized schedule) is crucial part of the app. The source code shows how user data can be stored in the Application Data folder of the user's own Google Drive account and kept in sync across multiple devices, and how to use Google Cloud Messaging to trigger syncs when necessary to ensure the data is always fresh.

The project includes the source code to the App Engine app that can be reused to send GCM messages to devices to trigger syncs, as well as a module (called Updater) that can be adapted to read conference data from other backends to produce the JSON files that are consumed by the I/O app.

We are excited to share this source code with the developer community today, and we hope it will serve as a learning tool, a source of reusable snippets and a useful example of Android app development in general. In the coming weeks we will post a few technical articles with more detailed information about the IOSched source code to help bring some insight into the app development process. We will continue to update the app in the coming months, and as always, your pull requests are very welcome!


Join the discussion on
+Android Developers


Categories: Programming

KNOX Contribution to Android: Accelerating Android in the Workplace

Mon, 07/21/2014 - 17:21

Srikanth Rajagopalan, PM Director and Workplace aficionado

Recently at Google I/O, we announced a comprehensive set of new features that will allow IT organizations to easily deploy and manage Android devices in enterprise environments. These features will be built into the upcoming Android L release.

Samsung, with its KNOX technology, has been a thought leader in the enterprise mobility space. In order to accelerate Android adoption in the enterprise, we have partnered with Samsung to bring key KNOX functionality into Android, for the benefit of the entire Android ecosystem. We thank Samsung for their contributions. These new capabilities will make it easy for IT organizations to allow employees to bring their own Android devices to work (BYOD) and use them on the corporate network or to simply issue new Android devices to their employees. IT administrators will be able to manage a wide range of Android devices from many manufacturers, using third-party Enterprise Mobility Management (EMM) solutions that are built on top of the new enterprise APIs launching with Android L release.

Google and Samsung together designed the new enterprise APIs around three major concepts:

  • Device and data security
  • Support for IT policies and restrictions
  • Mobile application management
Device and data security

At the core of the expanded enterprise capabilities being introduced in Android ‘L’ lies a set of technologies that are designed to keep personal and corporate data both separate and safe. We achieve the data separation by building on the existing multi-user support in Android: personal and corporate applications will run as two separate Android users. Data is kept safe by using block-level disk encryption as well as verified boot technology. For those of you familiar with KNOX, this is analogous to KNOX Workspace. EMMs will be able to take advantage of new Android SDK APIs to enable the creation of a managed profile, which is where all corporate applications and data will reside.

Support for IT restrictions and policies

EMMs can use new Android SDK APIs , which have evolved from KNOX APIs, to allow IT admins to enforce a wide set of policies, ranging from system settings and certificate provisioning to application-specific (e.g. Chrome) configurations and restrictions.

Mobile application management

EMMs will be able to use new backend APIs, adapted from KNOX APIs and built around strong security principles for on-device app deployment, to allow IT admins to curate the corporate application catalog and to remotely deploy applications to the managed profile on the employees’ devices.

We encourage developers interested in the new Enterprise APIs to download and test the Android L Developer Preview. For developers who have already built applications using Samsung KNOX APIs, Samsung will be providing a KNOX Compatibility Library that will let such applications run on all Android L devices.

You can read more about this collaboration on the Samsung KNOX blog. Stay tuned for additional details.


Join the discussion on
+Android Developers


Categories: Programming

Porting Your Android Wear Developer Preview Code to the Latest Support Library

Fri, 07/18/2014 - 01:18

Today’s post on #AndroidWear is from +Wayne Piekarski.

Now that the full Android Wear SDK is available, it’s time to port your existing wearable-enabled notification code from the Developer Preview. In the process, you’ll switch to using the latest Android support library, and there are some small API changes that will require you to update your code. This article will show you how to update my previous code samples that were released earlier for stacks and pages, which you can use to guide the conversion of your own code as well.

To get started with an existing project in Android Studio, you should update to the 0.8 or later release. You also need to make sure you’ve downloaded the Google Support Library version 20 or later from the SDK Manager. Since this is only a notification-based example, there’s no need to download the full Android Wear SDK, which is only needed if you want to create an APK to run on the wearable device.

Unix diff output is used to show the necessary changes in an easy to understand way. Do not copy the + or - symbols at the start of each line, and ignore the lines starting with @@ which are used to indicate the line number that changed. For the curious, I used the following command to generate the diff output from the last commit in my GIT repository (the -U1 shows one line of context to keep the output simple):

git show HEAD -U1

Gradle changes

To add the new support-v4 library, you need to edit your build.gradle file like so:

@@ -24,2 +24,3 @@ dependencies {
     compile 'com.android.support:appcompat-v7:19.+'
+    compile 'com.android.support:support-v4:20.0+'
 }

Make sure you remove the wearable-preview-support.jar that was provided with the Developer Preview from your libs directory and build.gradle file, since these features are now in the standard support library.

Package imports

Since the APIs and package names have changed, the import statements at the top of MainActivity.java need to be adjusted like this:

@@ -7,3 +7,2 @@ import android.view.MenuItem;
-import android.support.v4.app.NotificationCompat;
 import android.app.Notification;
@@ -13,4 +12,9 @@ import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
-import android.preview.support.v4.app.NotificationManagerCompat;
-import android.preview.support.wearable.notifications.WearableNotifications;
+import android.support.v4.app.NotificationCompat;
+import android.support.v4.app.NotificationManagerCompat;
+
+// Extra dependencies needed for the pages example
+import java.util.ArrayList;
+import java.util.List;
+import android.support.v4.app.NotificationCompat.BigTextStyle;
Stacking notifications

Since the preview SDK, we have simplified how notifications are implemented. The existing NotificationCompat.Builder() was extended to support groups directly, instead of a separate WearableNotifications class. The steps are a lot simpler, as can be seen with the following changes to showStackNotifications():

@@ -63,3 +67,3 @@ public class MainActivity extends ActionBarActivity {
         // Group notification that will be visible on the phone
-    NotificationCompat.Builder builderG = new NotificationCompat.Builder(this)
+    Notification summaryNotification = new NotificationCompat.Builder(this)
             .setContentTitle("2 Pet Notifications")
@@ -67,5 +71,5 @@ public class MainActivity extends ActionBarActivity {
             .setSmallIcon(R.drawable.ic_launcher)
-                .setLargeIcon(bitmapMila);
-    Notification summaryNotification = new WearableNotifications.Builder(builderG)
-            .setGroup(GROUP_KEY_MESSAGES, WearableNotifications.GROUP_ORDER_SUMMARY)
+                .setLargeIcon(bitmapMila)
+            .setGroup(GROUP_KEY_MESSAGES)
+            .setGroupSummary(true)
             .build();
@@ -76,3 +80,3 @@ public class MainActivity extends ActionBarActivity {
             PendingIntent.getActivity(this, notificationId+1, viewIntent1, 0);
-    NotificationCompat.Builder builder1 = new NotificationCompat.Builder(this)
+    Notification notification1 = new NotificationCompat.Builder(this)
             .addAction(R.drawable.ic_action_done, "Treat Fed", viewPendingIntent1)
@@ -81,4 +85,3 @@ public class MainActivity extends ActionBarActivity {
                     + "Can we have steak?")
-                .setSmallIcon(R.drawable.ic_launcher);
-    Notification notification1 = new WearableNotifications.Builder(builder1)
+            .setSmallIcon(R.drawable.ic_launcher)
             .setGroup(GROUP_KEY_MESSAGES)
@@ -89,3 +92,3 @@ public class MainActivity extends ActionBarActivity {
             PendingIntent.getActivity(this, notificationId+2, viewIntent2, 0);
-    NotificationCompat.Builder builder2 = new NotificationCompat.Builder(this)
+    Notification notification2 = new NotificationCompat.Builder(this)
             .addAction(R.drawable.ic_action_done, "Water Filled", viewPendingIntent2)
@@ -93,4 +96,3 @@ public class MainActivity extends ActionBarActivity {
             .setContentText("Can you refill our water bowl?")
-            .setSmallIcon(R.drawable.ic_launcher);
-        Notification notification2 = new WearableNotifications.Builder(builder2)
+            .setSmallIcon(R.drawable.ic_launcher)
             .setGroup(GROUP_KEY_MESSAGES)
Page notifications

Page notifications have also changed to use a WearableExtender() class instead of the WearableNotifications class, as can be seen here in showPageNotifications():

@@ -151,3 +153,3 @@ public class MainActivity extends ActionBarActivity {
             PendingIntent.getActivity(this, notificationId+1, viewIntent1, 0);
-    NotificationCompat.Builder builder1 = new NotificationCompat.Builder(this)
+    Notification notification1 = new NotificationCompat.Builder(this)
             .addAction(R.drawable.ic_action_done, "Returned", viewPendingIntent1)
@@ -155,5 +157,4 @@ public class MainActivity extends ActionBarActivity {
             .setContentText("You have " + numOverdue + " books due at the library")
-            .setSmallIcon(R.drawable.ic_launcher);
-    Notification notification1 = new WearableNotifications.Builder(builder1)
-            .addPages(extras)
+                .setSmallIcon(R.drawable.ic_launcher)
+            .extend(new NotificationCompat.WearableExtender().addPages(extras))
             .build();
Conclusion

If you want to download the final source code of showStackNotifications() and showPageNotifications(), you can download the MainActivity.java file. You can build this file easily by creating a new project in Android Studio, adding the support library, and then copying in this MainActivity.java.

As you can see, porting this previous code over to the latest Android Wear SDK is really easy! It should take you hardly any time at all to get your experimental applications ported over and ready for publishing on the Google Play!


Join the discussion on
+Android Developers


Categories: Programming

Learn to Think Like an Android Developer

Tue, 07/15/2014 - 19:57

By Reto Meier, Head of Scalable Developer Advocacy

Today I’m proud to announce the latest resource for learning to develop Android apps: Developing Android Apps: Android Fundamentals.

Android Fundamentals is an online training course featuring Google Developer Advocates Reto Meier, Dan Galpin, and Katherine Kuan, working with the team at Udacity that’s advanced and technical enough for experienced developers who are new to Android — maybe even new to mobile — but not new to programming.

The course offers step-by-step training in which you’ll build an Android app, and learn best practices of mobile development in general and Android development in particular.

The full course materials — all the videos, quizzes, and forums — are available for free for all students by selecting “View Courseware”. Personalized ongoing feedback and guidance from Coaches is also available to anyone who chooses to enroll in Udacity’s guided program.

This guided course, along with UX Design for Mobile Developers and Mobile Web Development, complement our existing material—including documentation, samples, and videos — to offer a solid grounding in developing great experiences for people using mobile devices. Check out the trailer below for an overview of what's in the course.

Mobile devices are the platform that will bring the next five billion people online. With Android expanding rapidly into emerging markets, and growing beyond phones and tablets into wearables, auto, and TV, learning the fundamentals behind Android development represents an opportunity to affect and improve the lives of billions of people.

We look forward to seeing what the next wave of Android developers build, and we’ll keep exploring new ways to help you become better developers.



Join the discussion on
+Android Developers


Categories: Programming