Tag Archives: Develop

How to set up Analytics on your AMP pages

Originally posted on Google Analytics blog

Posted by Arudea Mahartianto, Google AMP Specialist

In the digital world, whether you’re writing stories for your loyal readers, creating creative content that your fans love, helping the digital community, or providing items and services for your customer, understanding your audience is at the heart of it all. Key to unlocking that information is access to tools for measuring your audience and understanding their behavior. In addition to making your page load faster, Accelerated Mobile Pages (AMP) provides multiple analytics options without compromising on performance.

You can choose to use a solution like amp-pixel that behaves like a simple tracking pixel. It uses a single URL that allows variable substitutions, so it’s very customizable. See the amp-pixel documentation for more detail.

The amp-analytics component, on the other hand, is a powerful solution that recognizes many types of event triggers to help you collect specific metrics. Since amp-analytics is supported by multiple analytics providers, this means you can use amp-analytics to configure multiple endpoints and data sets. AMP then manages all of the instrumentation to come up with the data specified and shares it with these analytics solution providers.

To use amp-analytics, include the component library in your document's <head>:

<script async custom-element="amp-analytics"


src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>

And then include the component as follows (for these examples, make sure to specify your own account number instead of the placeholder):

<amp-analytics type="googleanalytics">


<script type="application/json">
{
"vars": {
"account": "UA-YYYY-Y"
},
"triggers": {
"defaultPageview": {
"on": "visible",
"request": "pageview",
"vars": {
"title": "Name of the Article"
}
}
}
}
</script>
</amp-analytics>

The JSON format is super flexible for describing several different types of events and it does not include any JavaScript code which could potentially lead to mistakes.

Expanding the above example, we can add another trigger, clickOnHeader:

<amp-analytics type="googleanalytics">
<script type="application/json">
{
"vars": {
"account": "UA-YYYY-Y"
},
"triggers": {
"defaultPageview": {
"on": "visible",
"request": "pageview",
"vars": {
"title": "Name of the Article"
}
},
"clickOnHeader": {
"on": "click",
"selector": "#header",
"request": "event",
"vars": {
"eventCategory": "examples",
"eventAction": "clicked-header"
}
}
}
}
</script>
</amp-analytics>

For a detailed description of data sets you can request, as well as the complete list of analytics providers supporting amp-analytics, check out the amp-analytics documentation. You can also see more implementation examples in the Amp By Example site.

If you want to conduct a user experience experiment on your AMP pages, such as an A/B test, you can use the amp-experimentelement. Any configurations done in this element will also be exposed to amp-analytics and amp-pixel, so you can easily do a statistical analysis of your experiment.

There are still plenty of ongoing developments for AMP analytics to help you gain insights as you AMPlify the user experience on your site. Visit the AMP Project roadmap to see a summary of what the team is cooking up. If you see some features missing, please file a request on GitHub.

Android Studio 2.2

By Jamal Eason, Product Manager, Android

Android Studio 2.2 is available to download today. Previewed at Google I/O 2016, Android Studio 2.2 is the latest release of our IDE used by millions of Android developers around the world.

Packed with enhancements, this release has three major themes: speed, smarts, and Android platform support. Develop faster with features such as the new Layout Editor, which makes creating an app user interface quick and intuitive. Develop smarter with our new APK analyzer, enhanced Layout Inspector, expanded code analysis, IntelliJ’s 2016.1.3 features and much more. Lastly, as the official IDE for Android app development, Android Studio 2.2 includes support for all the latest developer features in Android 7.0 Nougat, like code completion to help you add Android platform features like Multi-Window support, Quick Settings API, or the redesigned Notifications, and of course, the built-in Android Emulator to test them all out.

In this release, we evolved the Android Frameworks and the IDE together to create the Constraint Layout. This powerful new layout manager helps you design large and complex layouts in a flat and streamlined hierarchy. The ConstraintLayout integrates into your app like a standard Android support library, and was built in parallel with the new Layout Editor.

Android Studio 2.2 includes 20+ new features across every major phase of the development process: design, develop, build, & test. From designing UIs with the new ConstraintLayout, to developing C++ code with the Android NDK, to building with the latest Jack compliers, to creating Espresso test cases for your app, Android Studio 2.2 is the update you do not want to miss. Here’s more detail on some of the top highlights:

Design

  • Layout Editor: Creating Android app user interfaces is now easier with the new user interface designer. Quickly construct the structure of your app UI with the new blueprint mode and adjust the visual attributes of each widget with new properties panel. Learn more.

Layout Editor

  • Constraint Layout: This new layout is a flexible layout manager for your app that allows you to create dynamic user interfaces without nesting multiple layouts. It is backwards compatible all the way back to Android API level 9 (Gingerbread). ConstraintLayout works best with the new Layout Editor in Android Studio 2.2. Learn more.

ConstraintLayout

Develop

  • Improved C++ Support: You can now use CMake or ndk-build to compile your C++ projects from Gradle. Migrating projects from CMake build systems to Android Studio is now seamless. You will also find C++ support in the new project wizard in Android Studio, plus a number of bug fixes to the C++ edit and debug experience. Learn more.

C++ Code Editing & CMake Support

  • Samples Browser: Referencing Android sample code is now even easier with Android Studio 2.2. Within the code editor window, find occurrences of your app code in Google Android sample code to help jump start your app development.

Sample Code Menu

Build

  • Instant Run Improvements: Introduced in Android Studio 2.0, Instant Run is our major, long-term investment to make Android development as fast and lightweight. Since launch, it has significantly improved the edit, build, run iteration cycles for many developers. In this release, we have made many stability and reliability improvements to Instant Run. If you have previously disabled Instant Run, we encourage you to re-enable it and let us know if you come across further issues. (Settings → Build, Execution, Deployment → Instant Run [Windows/Linux] , Preferences → Build, Execution, Deployment → Instant Run [OS X]). For details on the fixes that we have made, see the Android Studio 2.2 release notes.

Enable Instant Run

  • APK Analyzer: Easily inspect the contents of your APKs to understand the size contribution of each component. This feature can be helpful when debugging multi-dex issues. Plus, with the APK Analyzer you can compare two versions of an APK. Learn more.

APK Analyzer

  • Build cache (Experimental): We are continuing our investments to improve build speeds with the introduction of a new experimental build cache that will help reduce both full and incremental build times. Just add android.enableBuildCache=true to your gradle.properties file. Learn more.

Build Cache Setting

Test

  • Virtual Sensors in the Android Emulator: The Android Emulator now includes a new set of virtual sensors controls. With the new UI controls, you can now test Android Sensors such as Accelerometer, Ambient Temperature, Magnetometer and more. Learn more.

Android Emulator Virtual Sensors

  • Espresso Test Recorder (Beta): The Espresso Test Recorder lets you easily create UI tests by recording interactions with your app; it then outputs the UI test code for you. You record your interactions with a device and add assertions to verify UI elements in particular snapshots of your app. Espresso Test Recorder then takes the saved recording and automatically generates a corresponding UI test. You can run the test locally, on your continuous integration server, or using Firebase Test Lab for Android. Learn more.
Espresso Test Recorder
  • GPU Debugger (Beta): The GPU Debugger is now in Beta. You can now capture a stream of OpenGL ES commands on your Android device and then replay it from inside Android Studio for analysis. You can also fully inspect the GPU state of any given OpenGL ES command to better understand and debug your graphical output. Lean more.
GPU Debugger

To recap, Android Studio 2.2 includes these major features and more:

Design

Develop

Build

Test

Learn more about Android Studio 2.2 by reviewing the release notes and the preview blog post.

Getting Started

Download

If you are using a previous version of Android Studio, you can check for updates on the Stable channel from the navigation menu (Help → Check for Update [Windows/Linux] , Android Studio → Check for Updates [OS X]). You can also download Android Studio 2.2 from the official download page. To take advantage of all the new features and improvements in Android Studio, you should also update to the Android Gradle plugin version to 2.2.0 in your current app project.

Next Release

We would like to thank all of you in the Android Developer community for your work on this release. We are grateful for your contributions, your ongoing feedback which inspired the new features in this release, and your highly active use on canary and beta builds filing bugs. We all wanted to make Android Studio 2.2 our best release yet, with many stability and performance fixes in addition to the many new features. For our next release, look for even more; we want to work hard to address feedback and keep driving up quality and stability on existing features to make you productive.

We appreciate any feedback on things you like, issues or features you would like to see. Connect with us -- the Android Studio development team -- on our Google+ page or on Twitter.


What's New in Android Studio 2.2

Taking the final wrapper off of Android 7.0 Nougat

Posted by Dave Burke, VP of Engineering

Android Nougat

Android 7.0 Nougat

Today, Android 7.0 Nougat will begin rolling out to users, starting with Nexus devices. At the same time, we’re pushing the Android 7.0 source code to the Android Open Source Project (AOSP), extending public availability of this new version of Android to the broader ecosystem.

We’ve been working together with you over the past several months to get your feedback on this release, and also to make sure your apps are ready for the users who will run them on Nougat devices.

What’s inside Nougat

Android Nougat reflects input from thousands of fans and developers like you, all around the world. There are over 250 major features in Android Nougat, including VR Mode in Android. We’ve worked at all levels of the Android stack in Nougat — from how the operating system reads sensor data to how it sends pixels to the display — to make it especially built to provide high quality mobile VR experiences.

Plus, Nougat brings a number of new features to help make Android more powerful, more productive and more secure. It introduces a brand new JIT/AOT compiler to improve software performance, make app installs faster, and take up less storage. It also adds platform support for Vulkan, a low-overhead, cross-platform API for high-performance, 3D graphics. Multi-Window support lets users run two apps at the same time, and Direct Reply so users can reply directly to notifications without having to open the app. As always, Android is built with powerful layers of security and encryption to keep your private data private, so Nougat brings new features like File-based encryption, seamless updates, and Direct Boot.

You can find all of the Nougat developer resources here, including details on behavior changes and new features you can use in your apps. An overview of what's new for developers is available here, and you can explore all of the new user features in Nougat here.

Multi-window mode in Android Nougat

Multi-window mode in Android Nougat

The next wave of users

Starting today and rolling out over the next several weeks, the Nexus 6, Nexus 5X, Nexus 6P, Nexus 9, Nexus Player, Pixel C, and General Mobile 4G (Android One) will get an over-the-air software update to Android 7.0 Nougat. Devices enrolled in the Android Beta Program will also receive this final version.

And there are many tasty devices coming from our partners running Android Nougat, including the upcoming LG V20, which will be the first new smartphone that ships with Android Nougat, right out of the box.

With all of these new devices beginning to run Nougat, now is the time to publish your app updates to Google Play. We recommend compiling against, and ideally targeting, API 24. If you’re still testing some last minute changes, a great strategy to do this is using Google Play’s beta testing feature to get early feedback from a small group of users — including those using Android 7.0 Nougat — and then doing a staged rollout as you release the updated app to all users.

What’s next for Nougat?

We’re moving Nougat into a new regular maintenance schedule over the coming quarters. In fact, we’ve already started work on the first Nougat maintenance release, that will bring continued refinements and polish, and we’re planning to bring that to you this fall as a developer preview. Stay tuned!

We’ll be closing open bugs logged against Developer Preview builds soon, but please keep the feedback coming! If you still see an issue that you filed in the preview tracker, just file a new issue against Android 7.0 in the AOSP issue tracker.

Thanks for being part of the preview, which we shared earlier this year with an eye towards giving everyone the opportunity to make the next release of Android stronger. Your continued feedback has been extremely beneficial in shaping this final release, not just for users, but for the entire Android ecosystem.

Strictly Enforced Verified Boot with Error Correction

Posted by Sami Tolvanen, Software Engineer

Overview

Android uses multiple layers of protection to keep users safe. One of these layers is verified boot, which improves security by using cryptographic integrity checking to detect changes to the operating system. Android has alerted about system integrity since Marshmallow, but starting with devices first shipping with Android 7.0, we require verified boot to be strictly enforcing. This means that a device with a corrupt boot image or verified partition will not boot or will boot in a limited capacity with user consent. Such strict checking, though, means that non-malicious data corruption, which previously would be less visible, could now start affecting process functionality more.

By default, Android verifies large partitions using the dm-verity kernel driver, which divides the partition into 4 KiB blocks and verifies each block when read, against a signed hash tree. A detected single byte corruption will therefore result in an entire block becoming inaccessible when dm-verity is in enforcing mode, leading to the kernel returning EIO errors to userspace on verified partition data access.

This post describes our work in improving dm-verity robustness by introducing forward error correction (FEC), and explains how this allowed us to make the operating system more resistant to data corruption. These improvements are available to any device running Android 7.0 and this post reflects the default implementation in AOSP that we ship on our Nexus devices.

Error-correcting codes

Using forward error correction, we can detect and correct errors in source data by shipping redundant encoding data generated using an error-correcting code. The exact number of errors that can be corrected depends on the code used and the amount of space allocated for the encoding data.

Reed-Solomon is one of the most commonly used error-correcting code families, and is readily available in the Linux kernel, which makes it an obvious candidate for dm-verity. These codes can correct up to ⌊t/2⌋ unknown errors and up to t known errors, also called erasures, when t encoding symbols are added.

A typical RS(255, 223) code that generates 32 bytes of encoding data for every 223 bytes of source data can correct up to 16 unknown errors in each 255 byte block. However, using this code results in ~15% space overhead, which is unacceptable for mobile devices with limited storage. We can decrease the space overhead by sacrificing error correction capabilities. An RS(255, 253) code can correct only one unknown error, but also has an overhead of only 0.8%.

An additional complication is that block-based storage corruption often occurs for an entire block and sometimes spans multiple consecutive blocks. Because Reed-Solomon is only able to recover from a limited number of corrupted bytes within relatively short encoded blocks, a naive implementation is not going to be very effective without a huge space overhead.

Recovering from consecutive corrupted blocks

In the changes we made to dm-verity for Android 7.0, we used a technique called interleaving to allow us to recover not only from a loss of an entire 4 KiB source block, but several consecutive blocks, while significantly reducing the space overhead required to achieve usable error correction capabilities compared to the naive implementation.

Efficient interleaving means mapping each byte in a block to a separate Reed-Solomon code, with each code covering N bytes across the corresponding N source blocks. A trivial interleaving where each code covers a consecutive sequence of N blocks already makes it possible for us to recover from the corruption of up to (255 - N) / 2 blocks, which for RS(255, 223) would mean 64 KiB, for example.

An even better solution is to maximize the distance between the bytes covered by the same code by spreading each code over the entire partition, thereby increasing the maximum number of consecutive corrupted blocks an RS(255, N) code can handle on a partition consisting of T blocks to ⌈T/N⌉ × (255 - N) / 2.

Interleaving with distance D and block size B.

An additional benefit of interleaving, when combined with the integrity verification already performed by dm-verity, is that we can tell exactly where the errors are in each code. Because each byte of the code covers a different source block—and we can verify the integrity of each block using the existing dm-verity metadata—we know which of the bytes contain errors. Being able to pinpoint erasure locations allows us to effectively double our error correction performance to at most ⌈T/N⌉ × (255 - N) consecutive blocks.

For a ~2 GiB partition with 524256 4 KiB blocks and RS(255, 253), the maximum distance between the bytes of a single code is 2073 blocks. Because each code can recover from two erasures, using this method of interleaving allows us to recover from up to 4146 consecutive corrupted blocks (~16 MiB). Of course, if the encoding data itself gets corrupted or we lose more than two of the blocks covered by any single code, we cannot recover anymore.

While making error correction feasible for block-based storage, interleaving does have the side effect of making decoding slower, because instead of reading a single block, we need to read multiple blocks spread across the partition to recover from an error. Fortunately, this is not a huge issue when combined with dm-verity and solid-state storage as we only need to resort to decoding if a block is actually corrupted, which still is rather rare, and random access reads are relatively fast even if we have to correct errors.

Conclusion

Strictly enforced verified boot improves security, but can also reduce reliability by increasing the impact of disk corruption that may occur on devices due to software bugs or hardware issues.

The new error correction feature we developed for dm-verity makes it possible for devices to recover from the loss of up to 16-24 MiB of consecutive blocks anywhere on a typical 2-3 GiB system partition with only 0.8% space overhead and no performance impact unless corruption is detected. This improves the security and reliability of devices running Android 7.0.

Final Developer Preview before Android 7.0 Nougat begins rolling out

Posted by Dave Burke, VP of Engineering

As we close in on the public rollout of Android 7.0 Nougat to devices later this summer, today we’re releasing Developer Preview 5, the last milestone of this preview series. Last month’s Developer Preview included the final APIs for Nougat; this preview gives developers the near-final system updates for all of the supported preview devices, helping you get your app ready for consumers.

Here’s a quick rundown of what’s included in the final Developer Preview of Nougat:

  • System images for Nexus and other preview devices
  • An emulator that you can use for doing the final testing of your apps to make sure they’re ready
  • The final N APIs (API level 24) and latest system behaviors and UI
  • The latest bug fixes and optimizations across the system and in preinstalled apps

Working with this latest Developer Preview, you should make sure your app handles all of the system behavior changes in Android N, like Doze on the Go, background optimizations, screen zoom, permissions changes, and more. Plus, you can take advantage of new developer features in Android N such as Multi-window support, Direct Reply and other notifications enhancements, Direct boot, new emojis and more.

Publish your apps to alpha, beta or production channels in Google Play

After testing your apps with Developer Preview 5 you should publish the updates to Google Play soon. We recommend compiling against, and optionally targeting, API 24 and then publishing to your alpha, beta, or production channels in the Google Play Developer Console. A great strategy to do this is using Google Play’s beta testing feature to get early feedback from a small group of users -- including Developer Preview users — and then doing a staged rollout as you release the updated app to all users.

How to get Developer Preview 5

If you are already enrolled in the Android Beta program, your devices will get the Developer Preview 5 update right away, no action is needed on your part. If you aren’t yet enrolled in Android Beta, the easiest way to get started is by visiting android.com/beta and opt-in your eligible Android phone or tablet -- you’ll soon receive this preview update over-the-air. As always, you can also download and flash this update manually. The Nougat Developer Preview is available for Nexus 6, Nexus 5X, Nexus 6P, Nexus 9, and Pixel C devices, as well as General Mobile 4G [Android One] devices.

Thanks so much for all of your feedback so far. Please continue to share feedback or requests either in the N Developer Preview issue tracker, N Preview Developer community, or Android Beta community as we work towards the consumer release later this summer. Android Nougat is almost here!

Also, the Android engineering team will host a Reddit AMA on r/androidev to answer all your technical questions about the platform tomorrow, July 19 from 12-2 PM (Pacific Time). We look forward to addressing your questions!

Android N APIs are now final, get your apps ready for Android N!

Posted by Dave Burke, VP of Engineering

As we put the finishing touches on the next release of Android, which will begin to roll out to consumers later this summer, we’re releasing the 4th Developer Preview of Android N, including the Android N final SDK. And thanks to your continued feedback over the last three releases, all of the APIs are now final as well. If you’ve already enrolled your device in the Android Beta Program, (available at android.com/beta) you will receive an update to this Developer Preview shortly.

Get your apps ready for Android N

The final SDK for Android N is now available for download through the SDK Manager in Android Studio. It gives you everything you need to develop and test against the official APIs in the Android N platform. Once you’ve installed the final SDK, you can update your project’s compileSdkVersion to API 24 to develop with the Android N APIs and build and test on the new platform, for new features such as Multi-window support, direct-reply notifications, and others. We also recommend updating your app’s targetSdkVersion to API 24 to opt-in and test your app with Android N specific behavior changes. For details on how to setup your app with the final SDK, see Set up the Preview. For details on API level 24 check out the API diffs and the updated API reference, now hosted online.

Along with the Android N final SDK, we’ve also updated the Android Support Library to 24.0.0. This allows you to use multi-window and picture-in-picture callbacks, new notification features, methods for supporting Direct Boot, and new MediaBrowser APIs in a backward compatible manner.

Publish your apps to alpha, beta or production channels in Google Play

Now that you have a final set of APIs, you can publish updates compiling with, and optionally targeting, API 24 to Google Play. You can now publish app updates that use API 24 to your alpha, beta, or even production channels in the Google Play Developer Console. In this way, you can test your app’s backward-compatibility and push updates to users whose devices are running Developer Preview 4.

To make sure that your updated app runs well on Android N, as well as older versions, a common strategy is to use Google Play’s beta testing feature to get early feedback from a small group of users -- including developer preview users — and then do a staged rollout as you release the updated app to all users.

How to Get Developer Preview 4

Developer Preview 4 includes updated system images for all supported Preview devices as well as for the Android emulator. If you are already enrolled in the Android Beta program, your devices will get the Developer Preview 4 update right away, no action is needed on your part. If you aren’t yet enrolled in Android Beta, the easiest way to get started is by visiting android.com/beta and opt-in your eligible Android phone or tablet -- you’ll soon receive this (and later) preview updates over-the-air. As always, you can also download and flash this update manually. The N Developer Preview is available for Nexus 6, Nexus 5X, Nexus 6P, Nexus 9, and Pixel C devices, as well as General Mobile 4G [Android One] devices and the Sony Xperia Z3.

Thanks so much for all of your feedback so far. Please continue to share feedback or requests either in the N Developer Preview issue tracker, N Preview Developer community, or Android Beta community as we work towards the consumer release later this summer. We’re looking forward to seeing your apps on Android N!

Notifications in Android N

Posted by Ian Lake, Developer Advocate

Android notifications are often a make-or-break interaction between your Android app and users. To provide a better user experience, notifications on Android N have received a visual refresh, improved support for custom views, and expanded functionality in the forms of Direct Reply, a new MessagingStyle, and bundled notifications.

Same notification, new look

The first and most obvious change is that the default look and feel of notifications has significantly changed. Many of the fields that were spread around the notifications have been collapsed into a new header row with your app’s icon and name anchoring the notification. This change ensured that the title, text, and large icon are given the most amount of space possible and, as a result, notifications are generally slightly larger now and easier to read.


Given the single header row, it is more important than ever that the information there is useful. When you target Android N, by default the time will be hidden - if you have a time critical notification such as a messaging app, you can re-enable it with setShowWhen(true). In addition, the subtext will take precedence over any content info you set: only if you target a previous version of Android will both appear. In all cases, ensure that the subtext is relevant and useful - don’t add an account email address as your subtext if the user only has one account, for example.

Notification actions have also received a redesign and are now in a visually separate bar below the notification.


You’ll note that the icons are not present in the new notifications; instead more room is provided for the labels themselves in the constrained space of the notification shade. However, the notification action icons are still required and continue to be used on older versions of Android and on devices such as Android Wear.

If you’ve been building your notification with NotificationCompat.Builder and the standard styles available to you there, you’ll get the new look and feel by default with no code changes required.

Better Support for Custom Views

If you’re instead building your notification from custom RemoteViews, adapting to any new style has been challenging. With the new header, expanding behavior, actions, and large icon positioning as separate elements from the main text+title of the notification, we’ve introduced a new DecoratedCustomViewStyle and DecoratedMediaCustomViewStyle to provide all of these elements, allowing you to focus only on the content portion with the new setCustomContentView() method.


This also ensures that future look and feel changes should be significantly easier to adapt to as these styles will be updated alongside the platform with no code changes needed on the app side.

Direct Reply

While notification actions have already been able to launch an Activity or do background work with a Service or BroadcastReceiver, Direct Reply allows you to build an action that directly receives text input inline with the notification actions.


Direct Reply uses the same RemoteInput API - originally introduced for Android Wear - to mark an Action as being able to directly receive input from the user.

The RemoteInput itself contains information like the key which will be used to later retrieve the input and the hint text which is displayed before the user starts typing.

// Where should direct replies be put in the intent bundle (can be any string)
private static final String KEY_TEXT_REPLY = "key_text_reply";

// Create the RemoteInput specifying this key
String replyLabel = getString(R.string.reply_label);
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)
        .setLabel(replyLabel)
        .build();


Once you’ve constructed the RemoteInput, it can be attached to your Action via the aptly named addRemoteInput() method. You might consider also calling setAllowGeneratedReplies(true) to enable Android Wear 2.0 to generate Smart Reply choices when available and make it easier for users to quickly respond.

// Add to your action, enabling Direct Reply for it
NotificationCompat.Action action =
    new NotificationCompat.Action.Builder(R.drawable.reply, replyLabel, pendingIntent)
        .addRemoteInput(remoteInput)
        .setAllowGeneratedReplies(true)
        .build();


Keep in mind that the pendingIntent being passed into your Action should be an Activity on Marshmallow and lower devices that don’t support Direct Reply (as you’ll want to dismiss the lock screen, start an Activity, and focus the input field to have the user type their reply) and should be a Service (if you need to do work on a separate thread) or BroadcastReceiver (which runs on the UI thread) on Android N devices so as the process the text input in the background even from the lock screen. (There is a separate user control to enable/disable Direct Reply from a locked device in the system settings.)

Extracting the text input in your Service/BroadcastReceiver is then possible with the help of the RemoteInput.getResultsFromIntent() method:

private CharSequence getMessageText(Intent intent) {
    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
    if (remoteInput != null) {
        return remoteInput.getCharSequence(KEY_TEXT_REPLY);
    }
    return null;
 }


After you’ve processed the text, you must update the notification. This is the trigger which hides the Direct Reply UI and should be used as a technique to confirm to the user that their reply was received and processed correctly.

For most templates, this should involve using the new setRemoteInputHistory() method which appends the reply to the bottom of the notification. Additional replies should be appended to the history until the main content is updated (such as the other person replying).


However, if you’re building a messaging app and expect back and forth conversations, you should use MessagingStyle and append the additional message to it.

MessagingStyle

We’ve optimized the experience for displaying an ongoing conversation and using Direct Reply with the new MessagingStyle.


This style provides built-in formatting for multiple messages added via the addMessage() method. Each message supports passing in the text itself, a timestamp, and the sender of the message (making it easy to support group conversations).

builder.setStyle(new NotificationCompat.MessagingStyle("Me")
    .setConversationTitle("Team lunch")
    .addMessage("Hi", timestampMillis1, null) // Pass in null for user.
    .addMessage("What's up?", timestampMillis2, "Coworker")
    .addMessage("Not much", timestampMillis3, null)
    .addMessage("How about lunch?", timestampMillis4, "Coworker"));


You’ll note that this style has first-class support for specifically denoting messages from the user and filling in their name (in this case with “Me”) and setting an optional conversation title. While this can be done manually with a BigTextStyle, by using this style Android Wear 2.0 users will get immediate inline responses without kicking them out of the expanded notification view, making for a seamless experience without needing to build a full Wear app.

Bundled Notifications

Once you’ve built a great notification by using the new visual designs, Direct Reply, MessagingStyle, and all of our previous best practices, it is important to think about the overall notification experience, particularly if you post multiple notifications (say, one per ongoing conversation or per new email thread).


Bundled notifications offer the best of both worlds: a single summary notification for when users are looking at other notifications or want to act on all notifications simultaneously and the ability to expand the group to act on individual notifications (including using actions and Direct Reply).

If you’ve built stacking notifications for Android Wear, the API used here is exactly the same. Simply add setGroup() to each individual notification to bundle those notifications together. You’re not limited to one group, so bundle notifications appropriately. For an email app, you might consider one bundle per account for instance.

It is important to also create a summary notification. This summary notification, denoted by setGroupSummary(true), is the only notification that appears on Marshmallow and lower devices and should (you guessed it) summarize all of the individual notifications. This is an opportune time to use the InboxStyle, although using it is not a requirement. On Android N and higher devices, some information (such as the subtext, content intent, and delete intent) is extracted from the summary notification to produce the collapsed notification for the bundled notifications so you should continue to generate a summary notification on all API levels.

To improve the overall user experience on Android N devices, posting 4 or more notifications without a group will cause those notifications to be automatically bundled.

N is for Notifications

Notifications on Android have been a constant area of progressive enhancement. From the single tap targets of the Gingerbread era to expandable notifications, actions, MediaStyle, and now features such as Direct Reply and bundled notifications, notifications play an important part of the overall user experience on Android.

With many new tools to use (and NotificationCompat to help with backward compatibility), I’m excited to see how you use them to #BuildBetterApps

Follow the Android Development Patterns Collection for more!

Bring Your Android App to Chromebooks

Posted by Dylan Reid and Elijah Taylor, Software Engineers, Chrome OS

Users love Chromebooks for their speed, security and simplicity. According to IDC1, in Q1 of this year Chromebook shipments overtook Macs in the U.S. That means, thanks to your support, in the U.S. Chrome OS is now the second most popular PC operating system.  As we continue to increase our focus on mobility, we want to make sure your apps are easily available on this new form factor, reaching the many Chrome devices while maintaining a great experience.

Today we announced that we’re adding Android apps to Chromebooks, which means users will be able to install the apps they know and love. Later this year you can expand your app’s reach to a new hardware platform and wider audience while maximizing the Google Play ecosystem. With expanded app availability, new use cases and improved workflows can be achieved for all Chromebook users, whether for personal use, for work or for education.  As a developer we encourage you to test your app as described here.



Developers can start to optimize their app for the Chromebook form factor in advance of launch later in 2016. Here are some of the benefits:
  • Android Apps can be shown in 3 different window sizes to allow the best experience
  • Users can multi-task with multiple Android apps in moveable windows along with a full desktop browser, all within the familiar Chrome OS interface.
  • Keyboard, mouse, and touch input will seamlessly work together
  • Users will get Android notifications on their Chromebooks
  • Android apps benefit from the Wifi or Bluetooth connectivity setup by the user or the administrator
  • File sharing is seamless between Chrome and Android apps through the Files app
  • Performance of demanding apps such as games or design apps is excellent
In addition to being a great personal device, one of the reasons Chromebooks are popular in schools and businesses is that you can centrally manage and configure them with 200+ policies. Administrators can manage Android apps on Chromebooks using the same Admin Console. In addition to whitelisting or push installing specific apps to users, admins can selectively enable them for parts of their organization while disabling in others.

Please come to our Google I/O session on May 19th at 4 pm. You will hear directly  from our friendly engineers on how to optimize your Android app for Chromebooks. We are making the feature available in early June on Asus Chromebook Flip, Chromebook Pixel (2015) and Acer Chromebook R11 specifically for developers to have sufficient time to test their apps. For the actual launch and thereafter we will keep adding support for the following list of devices. Please see detailed instructions on how to get started with testing your apps.

1 - IDC’s Worldwide Quarterly PC Tracker, May 2016

Enhancing Android Pay APIs

Posted by Pali Bhat, Senior Director, Product Management

Today, we’re enhancing our APIs, making it easier than ever for the developer community to integrate with Android Pay. With just a few lines of code, you can enable quick and seamless checkout to help increase purchase conversions and ongoing engagement.

Improve conversions within apps

We’ve been working with popular apps such as Airbnb, Yelp Eat24, Kickstarter, TicketMaster, Uber and many others to bring the ease of speedy checkouts to apps. We also want to make the same great in-app experience available to all developers, big or small. So we’re taking a few steps:

  • Earlier today, we announced Android Instant Apps, which gives users the ability to pay using Android Pay with a single tap, without the friction of getting a user to install the app to complete their transaction. 

Example of Android Pay in Android Instant Apps

  • We’re opening the Android Pay API to all developers selling physical goods and services in markets where Android Pay is available—just sign up at developers.google.com/android-pay/
  • We’ve teamed up with payment processors globally so developers can integrate Android Pay with their Android apps in just a few hours.

Enhance mobile web payments

Many users continue to make purchases on mobile sites. But buying something from a website on your phone can be clumsy and cumbersome, which results in much lower conversion rates on mobile sites than on desktop sites.

To make painful web checkout forms a thing of the past, we will be launching PaymentRequest, a brand new web API that we are developing together with Chrome and standardizing across browsers through W3C. Android Pay will be part of this API to allow users to pay on mobile websites as they do in-store and in-app.

Example of Android Pay in PaymentRequest
Drive deeper engagement

Thanks for all the great feedback on our Save to Android Pay API since launch. You spoke and we’ve listened: We think you’ll be thrilled with the latest improvements to the Save to Android Pay API. The following enhancements help developers build stronger loyalty and engagement with new and existing customers:

  • Enable users to add offers, loyalty cards and gift cards in the Android Pay app with the tap of a button. Simply add a deep link to an email, SMS message, push notification or within an app and you’re all set.
  • Enroll new customers into a loyalty program in a variety of ways with the new simplified sign-up feature. Customers can sign-up either in store via a NFC tap or through a sign-up page linked from an Android Pay transaction notification.

Example sign-up feature for Walgreens Balance Reward®  
via Save to Android Pay from transaction notification
We believe that mobile payments can make for a better, more secure shopping experience - so we're in this together for the long haul. We’re building a robust Android Pay ecosystem, one that’s open and scalable, to enable developers to drive mobile payments - and their businesses - forward. We're very excited for the road ahead and we hope you are too.

To learn more about Android Pay and share your feedback, visit our developer pages.

What’s new in Android: the N-Release, Virtual Reality, Android Studio 2.2 and more

Posted by Dave Burke, VP of Engineering

In the past year, Android users around the globe have installed apps–built by developers like you–over 65 billion times on Google Play. To help developers continue to build amazing experiences on top of Android, today at Google I/O, we announced a number of new things we’re doing with the platform, including the next Developer Preview of Android N, an extension of Android into virtual reality, an update to Android Studio, and much more!

Android N Developer Preview is available to try on a range of devices
Android N: Performance, Productivity and Security
With Android N, we want to achieve a new level of product excellence for Android, so we’ve carried out some pretty deep surgery to the platform, rewriting and redesigning some fundamental aspects of how the system works. For Android N, we are focused on three key themes: performance, productivity and security. The first Developer Preview introduced a brand new JIT compiler to improve software performance, make app installs faster, and take up less storage. The second N Developer Preview included Vulkan, a new 3D rendering API to help game developers deliver high performance graphics on mobile devices. Both previews also brought useful productivity improvements to Android, including Multi-Window support and Direct Reply.

Multi-Window mode on Android N
Android N also adds some important new features to help keep users safer and more secure. Inspired by how Chromebooks apply updates, we’re introducing seamless updates, so that new Android devices built on N can install system updates in the background. This means that the next time a user powers up their device, new devices can automatically and seamlessly switch into the new updated system image.

Today’s release of Android N Developer Preview 3 is our first beta-quality candidate, available to test on your primary phone or tablet. You can opt in to the Android Beta Program at android.com/beta and run Android N on your Nexus 6, 9, 5X, 6P, Nexus Player, Pixel C, and Android One (General Mobile 4G). By inviting more people to try this beta release, developers can expect to see an uptick in usage of your apps on N; if you’ve got an Android app, you should be testing how it works on N, and be watching for feedback from users.

VR Mode in Android  
Android was built for today’s multi-screen world; in fact, Android powers your phone, your tablet, the watch on your wrist, it even works in your car and in your living room, all the while helping you move seamlessly between each device. As we look to what’s next, we believe your phone can be a really powerful new way to see the world and experience new content virtually, in a more immersive way; but, until this point, high quality mobile VR wasn’t possible across the Android ecosystem. That’s why we’ve worked at all levels of the Android stack in N–from how the operating system reads sensor data to how it sends pixels to the display–to make it especially built to provide high quality mobile VR experiences, with VR Mode in Android. There are a number of performance enhancements designed for developers, including single buffer rendering and access to an exclusive CPU core for VR apps. Within your apps, you can take advantage of smooth head-tracking and stereo notifications that work for VR. Most importantly, Android N provides for very low latency graphics; in fact, motion-to-photon latency on Nexus 6P running Developer Preview 3 is <20 ms, the speed necessary to establish immersion for the user to feel like they are actually in another place. We’ll be covering all of the new VR updates tomorrow at 9AM PT in the VR at Google session, livestreamed from Google I/O.

Android Instant Apps: real apps, without the installation 
We want to make it easier for users to discover and use your apps. So what if your app was just a tap away? What if users didn't have to install it at all? Today, we're introducing Android Instant Apps as part of our effort to evolve the way we think about apps. Whether someone discovers your app from search, social media, messaging or other deep links, they’ll be able to experience a fast and powerful native Android app without needing to stop and install your app first or reauthenticate. Best of all, Android Instant Apps is compatible with all Android devices running Jellybean or higher (4.1+) with Google Play services. Android Instant Apps functionality is an upgrade to your existing Android app, not a new, separate app; you can sign-up to request early access to the documentation.

Android Wear 2.0: UI changes and standalone apps  
This morning at Google I/O, we also announced the most significant Android Wear update since its launch two years ago: Android Wear 2.0. Based on what we’ve learned from users and developers, we're evolving the platform to improve key watch experiences: watch faces, messaging, and fitness. We’re also making a number of UI changes and updating our design guidelines to make your apps more consistent, intuitive, and beautiful.  With Android Wear 2.0, apps can be standalone and have direct network access to the cloud via a Bluetooth, Wi-Fi, or cellular connection.  Since your app won’t have to rely on the Data Layer APIs, it can continue to offer full functionality even if the paired phone is far away or turned off. You can read about all of the new features available in today’s preview here.


Android Studio 2.2 Preview: a new layout designer, constraint layout, and much more
Android Studio is the quickest way to get up and running with Android N and all our new platform features. Today at Google I/O, we previewed Android Studio 2.2 - another big update to the IDE designed to help you code faster with smart new tooling features built in. One of the headline features is our rewritten layout designer with the new constraint layout. In addition to helping you get out of XML to do your layouts visually, the new tools help you easily design for Android’s many great devices. Once you’re happy with a layout, we do all the hard work to automatically calculate constraints for you, so your UIs will resize automatically on different screen sizes . Here’s an overview of more of what’s new in 2.2 Preview (we’ll be diving into more detail this update at 10AM PT tomorrow in “What’s new in Android Development Tools”, livestreamed from Google I/O):

  • Speed: New layout designer and constraint layout, Espresso test recording and even faster builds
  • Smarts: APK analyzer, Layout inspector, expanded Android code analysis and IntelliJ 2016.1
  • Platform Support: Enhanced Jack compiler / Java 8 support, Expanded C++ support with CMake and NDK-Build, Firebase support and enhanced accessibility

New Layout Editor and Constraint Layout in Android Studio 2.2 Preview

This is just a small taste of some of the new updates for Android, announced today at Google I/O. There are more than 50 Android-related sessions over the next three days; if you’re not able to join us in person, many of them will be livestreamed, and all of them will be posted to YouTube after we’re done. We can’t wait to see what you build!