Tuesday, June 28, 2016

Android Mobile Vision restores operation and adds Text API

Posted by Michael Sipe, Product Manager






As an important framework for finding objects in photos and video, Mobile Vision
operation for Android devices is restored in Google Play Services v9.2.



This new version of Google Play Services fixes a download issue in Google Play
Services v.9.0 that caused a service outage. See href="https://developers.google.com/vision/release-notes">release notes for
details.



We’re also pleased to announce the Text API, a new component for Android Mobile
Vision.



The Text API’s optical character recognition technology reads Latin character
text (e.g. English, Spanish, German, French, etc.) in photos and returns the
text as well as the organizational structure (paragraphs, lines, words). Mobile
apps can now:


  • Organize photos that contain text
  • Automate tedious data entry for credit cards, receipts, and business cards
  • Translate documents (along with the href="https://cloud.google.com/translate/">Cloud Translate API)
  • Keep track of real objects, such as reading the numbers on subway trains
  • Provide accessibility features


If you want to get started quickly, you can try our href="http://g.co/codelabs/mobile-vision-ocr">codelab which will get Android
developers reading text with their apps in under an hour.



Like the Mobile Vision Face and Barcode components, the Text API runs on-device
and is suitable for real-time applications. For more information, check out the
Mobile Vision Developer
site
.

Create Intelligent, Context-Aware Apps with the Google Awareness APIs


Posted by Bhavik Singh, Product Manager



Last month at Google I/O 2016 we announced the new Google Awareness APIs,
enabling your apps to intelligently react to user context using snapshots and
fences with minimal impact on system resources.



Today we’re proud to announce that the Google Awareness API is available to all
developers through Google Play services.






Using 7 different types of context—including location, weather, user activity,
and nearby beacons—your app can better understand your users’ current
situations, and use this information to provide optimized and customized
experiences.



The Awareness API offers two ways to take advantage of context signals within
your app:


  • The Snapshot API lets your app easily request information
    about the user's current context. For example, "give me the user's current
    location and the current weather conditions".
  • The Fence API lets your app react to changes in user’s
    context - and when it matches a certain set of conditions. For example, "tell me
    whenever the user is walking and their headphones are plugged in". Similar to
    the Geofencing API, once an awareness fence is registered, it can send callbacks
    to your app even when it's not running.


As a single, simplified surface, the Awareness APIs combine optimally processed
context signals in new ways that were not previously possible, providing more
accurate and insightful context cues, while also managing system resources to
save battery and minimize bandwidth.



We’ve worked closely with some of our partners, who have already found amazing
ways to integrate context awareness into their apps:






href="https://play.google.com/store/apps/details?id=com.trulia.android&hl=en">Trulia,
an online residential real estate site, uses our Fence API to suggest
open houses. When the weather is perfect and the user is walking around near a
house they are interested in, Trulia sends a notification reminding them to stop
by. This sort of tailored notification can help users engage with open houses at
the perfect time for them.




href="https://play.google.com/store/apps/details?id=fm.superplayer.jukebot&hl=en">SuperPlayer
Music, on the other hand, uses our Snapshot API and Fence API to suggest the
perfect music to match your mood. Whether you’re just finishing up a run and
beginning to stretch, setting off on a long car ride, or just getting to the
gym, their assistant can understand your context and suggest the right playlist
for you.



With our initial set of signals and our awesome partners, we’re just getting
started with the Awareness APIs. Join us on a journey to build tailored
experiences within your apps, by getting started with the href="https://developers.google.com/awareness/?utm_campaign=android_launch_awarenessapi_062716&utm_source=anddev&utm_medium=blog">Google Awareness API developer
documentation, and learn more by watching our Google I/O session





Thursday, June 23, 2016

Introducing the Android Basics Nanodegree

Posted by Shanea King-Roberson, Lead Program Manager Twitter: @shaneakr Instagram: @theshanea







Do you have an idea for an app but you don’t know where to start? There are over
1 billion Android devices worldwide, providing a way for you to deliver your
ideas to the right people at the right time. Google, in partnership with
Udacity, is making Android development accessible and understandable to
everyone, so that regardless of your background, you can learn to build apps
that improve the lives of people around you.



Enroll in the new Android Basics
Nanodegree
. This series of courses and services teaches you how to build
simple Android apps--even if you have little or no programming experience. Take
a look at some of the apps built by our students:



The app "ROP Tutorial" built by student Arpy Vanyan raises awareness of a
potentially blinding eye disorder called Retinopathy of Prematurity that can
affect newborn babies.











And user Charles Tommo created an app called “Dr Malaria” that teaches people
ways to prevent malaria.











With courses designed by Google, you can
learn skills that are applicable to building apps that solve real world
problems. You can learn at your own pace to use href="http://developer.android.com/tools/studio/index.html">Android Studio
(Google’s official tool for Android app development) to design app user
interfaces and implement user interactions using the Java programming language.



The courses walk you through
step-by-step on how to build an order form for a coffee shop, an app to track
pets in a shelter, an app that teaches vocabulary words from the Native American
Miwok tribe, and an app on recent earthquakes in the world. At the end of the
course, you will have an entire portfolio of apps to share with your friends and
family.



Upon completing the Android Basics Nanodegree, you also have the opportunity to
continue your learning with the Career-track Android Nanodegree (for
intermediate developers). The first 50 participants to finish the Android Basics
Nanodegree have a chance to win a scholarship for the Career-track Android
Nanodegree. Please visit href="http://udacity.com/legal/scholarship">udacity.com/legal/scholarship
for additional details and eligibility requirements. You now have a complete
learning path to help you become a technology entrepreneur or most importantly,
build very cool Android apps, for yourself, your communities, and even the
world.



All of the individual courses that make
up this Nanodegree are available online for no charge at href="http://udacity.com/google">udacity.com/google. In addition, Udacity
provides paid services, including access to coaches, guidance on your project,
help staying on track, career counseling, and a certificate upon completion for
a fee.



You will be exposed to introductory computer science concepts in the Java
programming language, as you learn the following skills.


  • Build app user interfaces
  • Implement user interactions
  • Store information in a database
  • Pull data from the internet into your app
  • Identify and fix unexpected behavior in the app
  • Localize your app to support other languages


To enroll in the Android Basics Nanodegree program, href="http://udacity.com/nd803">click here.



See you in class!


Tuesday, June 21, 2016

Grow your business on Google Play with help from the new Playbook for Developers app

Posted by Dom Elliott, the Google Play team








Today, the href="http://g.co/play/playbook-androiddevelopers-blog-launch">Playbook for
Developers
mobile app is now
generally available for Android devices. The app helps you stay up-to-date with
the features and best practices to grow your business on Google Play. Thanks to
all our beta testers over the last six weeks whose feedback helped us tweak and
refine the app in preparation for launch.


Here’s how you read and watch content in the Playbook for Developers app:


  • Choose topics relating to your business interests to personalize My
    Playbook
    with curated articles and videos from Google and experts
    across the web.
  • Explore the in-depth guide to Google’s developer
    products, with articles grouped by what you’re trying to do: develop, launch,
    engage, grow, and earn.
  • Take actions on items – complete, share, save, or dismiss them – and read
    your Saved articles later, including offline if they’re
    written in the app. A data connection will be needed to read articles and videos
    from across the web.






The app supports Android 5.0 and above. If you're on an older device, check out our ebook, The Secrets to App Success on Google Play. We will be adding and updating content
in the app to help you stay up-to-date and grow your business. href="http://g.co/play/playbook-androiddevelopers-blog-launch">Get the Playbook
for Developers app today and then href="mailto:playbookfeedback@google.com">give us your feedback. The app is
also available in the following languages: href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=id&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=id">Bahasa
Indonesia, href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=de&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=de">Deutsch,
href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=es-419&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=es-419">español
(Latinoamérica), href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=fr&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=fr">le
français, href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=pt-BR&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=pr-BR">português
do Brasil, href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=vi&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=vi">tiếng
Việt, href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=ru&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=ru">русский
язы́к, href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=ko&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=ko">한국어,
href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=zh-CN&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=zh-CN">中文
(简体), href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=zh-TW&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=zh-TW">中文
(繁體), and href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&hl=ja&&utm_source=androiddevelopers&utm_medium=blog&utm_campaign=ja">日本語.



This is the second app we’ve released for Google Play developers. Get the href="http://g.co/play/consoleapp">Google Play Developer Console app to
review your app's performance statistics and financial data, get notified about
your app's status and publishing changes, and read and reply to user reviews on
the go.


Friday, June 17, 2016

One Year of Android Security Rewards

One Year of Android Security Rewards





A year ago, we added Android Security Rewards to the long standing Google Vulnerability Rewards Program. We offered up to $38,000 per report that we used to fix vulnerabilities and protect Android users.



Since then, we have received over 250 qualifying vulnerability reports from researchers that have helped make Android and mobile security stronger. More than a third of them were reported in Media Server which has been hardened in Android N to make it more resistant to vulnerabilities.



While the program is focused on Nexus devices and has a primary goal of improving Android security, more than a quarter of the issues were reported in code that is developed and used outside of the Android Open Source Project. Fixing these kernel and device driver bugs helps improve security of the broader mobile industry (and even some non-mobile platforms).



By the Numbers



Here’s a quick rundown of the Android VRP’s first year:




  • We paid over $550,000 to 82 individuals. That’s an average of $2,200 per reward and $6,700 per researcher.

  • We paid our top researcher, @heisecode, $75,750 for 26 vulnerability reports.

  • We paid 15 researchers $10,000 or more.

  • There were no payouts for the top reward for a complete remote exploit chain leading to TrustZone or Verified Boot compromise.



Thank you to those who submitted high quality vulnerability reports to us last year.




Improvements to Android VRP





We’re constantly working to improve the program and today we’re making a few changes to all vulnerability reports filed after June 1, 2016.





We’re paying more!



  • We will now pay 33% more for a high-quality vulnerability report with proof of concept. For example, the reward for a Critical vulnerability report with a proof of concept increased from $3000 to $4000.

  • A high quality vulnerability report with a proof of concept, a CTS Test, or a patch will receive an additional 50% more.

  • We’re raising our rewards for a remote or proximal kernel exploit from $20,000 to $30,000.

  • A remote exploit chain or exploits leading to TrustZone or Verified Boot compromise increase from $30,000 to $50,000.



All of the changes, as well as the additional terms of the program, are explained in more detail in our Program Rules. If you’re interested in helping us find security vulnerabilities, take a look at Bug Hunter University and learn how to submit high quality vulnerability reports. Remember, the better the report, the more you’ll get paid. We also recently updated our severity ratings, so make sure to check those out, too.





Thank you to everyone who helped us make Android safer. Together, we made a huge investment in security research that has made Android stronger. We’re just getting started and are looking forward to doing even more in the future.

Thursday, June 16, 2016

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 href="https://developer.android.com/preview/index.html?utm_campaign=android_launch_npreview_061516&utm_source=anddev&utm_medium=blog">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 href="https://android.com/beta">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 href="https://developer.android.com/preview/api-overview.html?utm_campaign=android_launch_npreview_061516&utm_source=anddev&utm_medium=blog">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 href="https://developer.android.com/preview/behavior-changes.html?utm_campaign=android_launch_npreview_061516&utm_source=anddev&utm_medium=blog">behavior
changes. For details on how to setup your app with the final SDK, see href="https://developer.android.com/preview/setup-sdk.html?utm_campaign=android_launch_npreview_061516&utm_source=anddev&utm_medium=blog">Set up the
Preview. For details on API level 24 check out the href="https://developer.android.com/sdk/api_diff/24/changes.html?utm_campaign=android_launch_npreview_061516&utm_source=anddev&utm_medium=blog">API diffs
and the updated href="https://developer.android.com/reference/packages.html?utm_campaign=android_launch_npreview_061516&utm_source=anddev&utm_medium=blog">API reference,
now hosted online.



Along with the Android N final SDK, we’ve also updated the href="https://developer.android.com/topic/libraries/support-library/revisions.html?utm_campaign=android_launch_npreview_061516&utm_source=anddev&utm_medium=blog">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 href="https://developer.android.com/distribute/engage/beta.html?utm_campaign=android_launch_npreview_061516&utm_source=anddev&utm_medium=blog">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 href="https://developer.android.com/preview/download.html?utm_campaign=android_launch_npreview_061516&utm_source=anddev&utm_medium=blog#flash">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 href="https://code.google.com/p/android/issues/list?can=2&q=label%3ADevPreview-N">N
Developer Preview issue tracker, href="https://plus.google.com/communities/103655397235276743411">N
Preview Developer community, or href="https://plus.google.com/communities/106765800802768335079">Android Beta
community as we work towards the consumer release later this summer. We’re
looking forward to seeing your apps on Android N!















Wednesday, June 15, 2016

Android Developer Story: Sendy uses Google Play features to build for the next billion users

Android Developer Story: Sendy uses Google Play features to build for the next billion users

Posted by Lily Sheringham, Google Play team



href="https://play.google.com/store/apps/details?id=com.sendy.co.ke.sendyy&hl=en&e=-EnableAppDetailsPageRedesign">Sendy
is a door to door on-demand couriering platform founded in Nairobi, Kenya. It
connects customers and logistics providers, providing two unique apps, one for
the driver and one for the customer. Watch CEO & Co-founder, Meshack Alloys, and
Android Developer, Jason Rogena, explain how they use Developer Console
features, such as alpha and beta testing, as well as other tips and best
practices, to build for the next billion users.






href="https://play.google.com/store/books/details/Google_Inc_The_Building_for_Billions_Playbook_for?id=cJEjDAAAQBAJ&e=-EnableAppDetailsPageRedesign">Learn
more about building for billions and get more tips to grow your games
business by href="https://play.google.com/apps/testing/com.google.android.apps.secrets">opting-in
to the Playbook app beta and href="https://play.google.com/store/apps/details?id=com.google.android.apps.secrets&e=-EnableAppDetailsPageRedesign">download
the Playbook app in the Google Play Store.

Friday, June 10, 2016

Security "Crypto" provider deprecated in Android N

Posted by Sergio Giro, software engineer



random_droid


If your Android app derives keys using the SHA1PRNG algorithm from the Crypto
provider, you must start using a real key derivation function and possibly re-encrypt your data.



The Java Cryptography Architecture allows developers to create an instance of a class like a cipher, or a pseudo-random number generator, using calls like:



SomeClass.getInstance("SomeAlgorithm", "SomeProvider");


Or simply:



SomeClass.getInstance("SomeAlgorithm");


For instance,



Cipher.getInstance(“AES/CBC/PKCS5PADDING”);


SecureRandom.getInstance(“SHA1PRNG”);


On Android, we don’t recommend specifying the provider. In general, any call to
the Java Cryptography Extension (JCE) APIs specifying a provider should only be
done if the provider is included in the application or if the application is
able to deal with a possible ProviderNotFoundException.



Unfortunately, many apps depend on the now removed “Crypto” provider for an
anti-pattern of key derivation.



This provider only provided an implementation of the algorithm “SHA1PRNG” for
instances of SecureRandom. The problem is that the SHA1PRNG algorithm is not
cryptographically strong. For readers interested in the details, On
statistical distance based testing of pseudo random sequences and experiments
with PHP and Debian OpenSSL
,Section 8.1, by Yongge Want and Tony Nicol,
states that the “random” sequence, considered in binary form, is biased towards
returning 0s, and that the bias worsens depending on the seed.



As a result, in Android N we are deprecating the
implementation of the SHA1PRNG algorithm and the Crypto provider altogether
.
We’d previously covered the issues with using SecureRandom for key derivation a
few years ago in href=http://android-developers.blogspot.com/2013/02/using-cryptography-to-store-credentials.html>Using
Cryptography to Store Credentials Safely. However, given its continued use,
we will revisit it here.



A common but incorrect usage of this provider was to derive keys for encryption
by using a password as a seed. The implementation of SHA1PRNG had a bug that
made it deterministic if setSeed() was called before obtaining output. This bug
was used to derive a key by supplying a password as a seed, and then using the
"random" output bytes for the key (where “random” in this sentence means
“predictable and cryptographically weak”). Such a key could then be used to
encrypt and decrypt data.



In the following, we explain how to derive keys correctly, and how to decrypt
data that has been encrypted using an insecure key. There’s also a
full example
, including a helper class to use the deprecated SHA1PRNG
functionality, with the sole purpose of decrypting data that would be otherwise
unavailable.



Keys can be derived in the following way:




  • If you're reading an AES key from disk, just store the actual key and don't go through this weird dance. You can get a SecretKey for AES usage from the bytes by doing:


    SecretKey key = new SecretKeySpec(keyBytes, "AES");


  • If you're using a password to derive a key, follow href="http://nelenkov.blogspot.com/2012/04/using-password-based-encryption-on.html">Nikolay Elenkov's excellent tutorial with the caveat that a good rule of thumb is the salt size should be the same size as the key output. It looks like this:



   /* User types in their password: */  
String password = "password";

/* Store these things on disk used to derive key later: */
int iterationCount = 1000;
int saltLength = 32; // bytes; should be the same size
as the output (256 / 8 = 32)
int keyLength = 256; // 256-bits for AES-256, 128-bits for AES-128, etc
byte[] salt; // Should be of saltLength

/* When first creating the key, obtain a salt with this: */
SecureRandom random = new SecureRandom();
byte[] salt = new byte[saltLength];
random.nextBytes(salt);

/* Use this to derive the key from the password: */
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt,
iterationCount, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");



That's it. You should not need anything else.



To make transitioning data easier, we covered the case of developers that have
data encrypted with an insecure key, which is derived from a password every
time. You can use the helper class InsecureSHA1PRNGKeyDerivator in
the example app
to derive the key.



 private static SecretKey deriveKeyInsecurely(String password, int
keySizeInBytes) {
byte[] passwordBytes = password.getBytes(StandardCharsets.US_ASCII);
return new SecretKeySpec(
InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(
passwordBytes, keySizeInBytes),
"AES");
}


You can then re-encrypt your data with a securely derived key as explained
above, and live a happy life ever after.



Note 1: as a temporary measure to keep apps working, we decided to still create
the instance for apps targeting SDK version 23, the SDK version for Marshmallow,
or less. Please don't rely on the presence of the Crypto provider in the Android
SDK, our plan is to delete it completely in the future.



Note 2: Because many parts of the system assume the existence of a SHA1PRNG
algorithm, when an instance of SHA1PRNG is requested and the provider is not
specified we return an instance of OpenSSLRandom, which is a strong source of
random numbers derived from OpenSSL.




Thursday, June 9, 2016

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 now supersedes the role of content info and number: number is never shown on Android N devices and only if you target a previous version of Android and don’t include a subtext will content info 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 href="https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog">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 href="https://developer.android.com/reference/android/support/v4/app/RemoteInput.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog">RemoteInput API - originally introduced for Android Wear - to mark an href="https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Action.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog">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 href="https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Action.Builder.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog#addRemoteInput(android.support.v4.app.RemoteInput)">addRemoteInput() method. You might consider also calling setAllowGeneratedReplies(true) to enable href="https://developer.android.com/wear/preview/index.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog">Android Wear 2.0 to generate href="https://developer.android.com/wear/preview/api-overview.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog#smart-replies">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 href="https://developer.android.com/reference/android/support/v4/app/RemoteInput.html#getResultsFromIntent(android.content.Intent)">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 href="https://www.youtube.com/watch?v=-iog_fmm6mE">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 href="https://developer.android.com/training/wearables/notifications/stacks.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog">stacking notifications for Android Wear, the API used here is exactly the same. Simply add href="https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog#setGroup(java.lang.String)">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 href="https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog#setGroupSummary(boolean)">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 href="https://developer.android.com/reference/android/support/v4/app/NotificationCompat.InboxStyle.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog">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 href="https://developer.android.com/reference/android/support/v4/app/NotificationCompat.html?utm_campaign=android_series_notificationsandroidnblog_060816&utm_source=anddev&utm_medium=blog">NotificationCompat to help with backward compatibility), I’m excited to see how you use them to #BuildBetterApps

Follow the href="https://plus.google.com/collection/sLR0p?utm_campaign=android_series_design_multiwindow_blog_051116&utm_source=anddev&utm_medium=blog">Android Development Patterns Collection for more!