Showing posts with label Android Developer. Show all posts
Showing posts with label Android Developer. Show all posts

Thursday, October 20, 2016

New video tips to help news publishers find success on Google Play

Posted by Tamzin Taylor - Strategic Partner Lead, Google Play





Today we have released a three-part video series ‘Tips for
your news app on Google Play’
, where you can find actionable tips
and learn best practices for developing, launching and monetising a high quality
news app. The video series accompanies the recently published href="https://play.google.com/store/books/details/Google_Inc_The_News_Publisher_Playbook_for_Android?id=O7T3CwAAQBAJ">News
Publisher Playbook
.

href="https://www.youtube.com/playlist?list=PLWz5rJ2EKKc_ElGrEtiEXc83m1SeYu3-Q">Watch
the video series
to learn:

  • 10 tips on how to design and develop your News app
  • 10 tips to help you launch your News app and start gaining readers
  • 10 tips to engage your readers and monetize your News app




You can also href="https://play.google.com/store/books/details/Google_Inc_The_News_Publisher_Playbook_for_Android?id=O7T3CwAAQBAJ&hl=en_GB">get
the News Publisher Playbook on the Play Store
to help you develop a
successful news mobile strategy on Android. It includes tips on mobile website
optimization, how to create a Google Play Newsstand edition, how to improve your
native app, and more.

Give us your feedback

Once you’ve checked out the video series, we’d love to hear your feedback so we
can continue to help you find success with and achieve your business objectives.
Leave a comment or a thumbs up, and href="https://www.youtube.com/channel/UCVHFbqXqoYvEWM1Ddxl0QDg?sub_confirmation=1">subscribe
to the Android Developers YouTube channel
!

Also, href="https://www.youtube.com/playlist?list=PLWz5rJ2EKKc_ElGrEtiEXc83m1SeYu3-Q">check
out our other videos in in the Tips for Success on Google Play series
,
including the recent video on href="https://www.youtube.com/watch?v=PfwHq8w9GBc&list=PLWz5rJ2EKKc_ElGrEtiEXc83m1SeYu3-Q&index=11">10
tips to build an app for billions of users
.

For more best practices to find success on Google Play, href="http://g.co/play/playbook-androiddevblogposts-evergreen">get the new
Playbook for Developers app
.








Tuesday, October 18, 2016

Announcing the Google Play Indie Games Festival in San Francisco, Sept. 24

Posted by Jamil Moledina, Google Play, Games Strategic Lead


If you’re an indie game developer, you know that games are a powerful medium of
expression of art, whimsy, and delight. Being on Google Play can help you reach
over a billion users and build a successful, global business. That’s why we
recently introduced programs, like the href="https://play.google.com/store/info/topic?id=topic_b000054_games_indie_corner_tp&e=-EnableAppDetailsPageRedesign">Indie
Corner
, to help more gamers discover your works of art.


To further celebrate and showcase the passion and innovation of indie game
developers, we’re hosting the Google Play Indie Games Festival at the href="https://www.google.com/maps/place/Terra+Gallery+%26+Event+Venue/@37.785531,-122.3929643,15z/data=!4m5!3m4!1s0x0:0xf5fb5bcb9c7795ab!8m2!3d37.785531!4d-122.3929643">Terra
Gallery
in San Francisco, on September 24.





This is a great opportunity for you to showcase your indie title to the public,
increase your network, and compete to win great prizes, such as Tango devices,
free tickets for Google I/O 2017, and Google ad campaign support. Admission will
be free and players will get the chance to play and vote on their favorites.


If you’re interested in showcasing your game, we’re href="https://docs.google.com/a/google.com/forms/d/e/1FAIpQLSduaM998L0WXm_4znsZjHX5-unZLBChNXHuCHbTlWuAcmMNmQ/viewform">accepting
submissions
now through August 14. We’ll then select high-quality games that
are both innovative and fun for the festival. Submissions are open to US and
Canadian developers with 15 or less full time staff. Only games published on or
after January 1, 2016 or those to be published by December 31, 2016 are
eligible. See href="https://docs.google.com/a/google.com/forms/d/e/1FAIpQLSduaM998L0WXm_4znsZjHX5-unZLBChNXHuCHbTlWuAcmMNmQ/viewform">complete
rules
.


We encourage virtual reality and augmented reality game submissions that use the
Google VR SDK and the href="https://store.google.com/product/tango_tablet_development_kit?srp=/product/project_tango_tablet_development_kit">Tango
Tablet Development Kit
.


At the end of August, we’ll announce the group of indies to be featured at the
festival.


You can learn more about the event href="https://events.withgoogle.com/google-play-indie-game-festival/">here.
We can’t wait to see what innovative and fun experiences you share with us!


Android Wear 2.0 Developer Preview 2

Android Wear 2.0 Developer Preview 2


Posted by Hoi Lam, Android Wear
Developer Advocate


At Google I/O 2016, we launched the Android
Wear 2.0 Developer Preview, which gives developers early access to the next
major release of Android Wear. Since I/O, feedback from the developer community
has helped us identify bugs and shape our product direction. Thank you!


Today, we are releasing the second developer preview with new functionalities
and bug fixes. Prior to the consumer release, we plan to release additional
updates, so please send us your
feedback early and often. Please keep in mind that this preview is a work in
progress, and is not yet intended for daily use.

What’s new?



 public class MainActivity extends Activity {  
   ...    
   @Override /* KeyEvent.Callback */  
   public boolean onKeyDown(int keyCode, KeyEvent event) {  
     switch (keyCode) {  
       case KeyEvent.KEYCODE_NAVIGATE_NEXT:  
         Log.d(TAG, "Next");  
         break;  
       case KeyEvent.KEYCODE_NAVIGATE_PREVIOUS:  
         Log.d(TAG, "Previous");  
         break;  
     }  
     // If you did not handle, then let it be handled by the next possible element as deemed by  
     // Activity.  
     return super.onKeyDown(keyCode, event);  
   }  
 }  


Get started and give us feedback!



The Android Wear 2.0 Developer Preview includes an updated SDK with tools and
system images for testing on the official Android emulator, the href="https://store.google.com/product/lg_watch_urbane_2nd_edition_lte">LG Watch
Urbane 2nd Edition LTE
, and the href="https://store.google.com/product/huawei_watch">Huawei Watch.


To get started, follow these steps:

  1. Take a video tour
    of the Android Wear 2.0 developer preview
  2. Update to Android Studio v2.1.1 or later
  3. Visit the Android Wear 2.0 Developer
    Preview site for downloads and documentation
  4. Get the emulator system images through the SDK Manager or href="https://developer.android.com/wear/preview/downloads.html?utm_campaign=android wear_launch_preview2_071216&utm_source=anddev&utm_medium=blog">download the
    device system images from the developer preview downloads page
  5. Test your app with your supported device or emulator
  6. Give us feedback


We will update this developer preview over the next few months based on your
feedback. The sooner we hear from you, the more we can include in the final
release, so don't be shy!

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 href="https://developer.android.com/preview/index.html?utm_campaign=android_launch_developerpreview5_071816&utm_source=anddev&utm_medium=blog">Android 7.0 Nougat
to devices later this summer, today we’re releasing Developer Preview
5
, the last milestone of this preview series. href="http://android-developers.blogspot.com/2016/06/android-n-apis-are-now-final.html">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 href="https://developer.android.com/preview/behavior-changes.html?utm_campaign=android_launch_developerpreview5_071816&utm_source=anddev&utm_medium=blog">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 href="https://developer.android.com/preview/api-overview.html?utm_campaign=android_launch_developerpreview5_071816&utm_source=anddev&utm_medium=blog">new developer
features in Android N
such as href="https://developer.android.com/preview/api-overview.html?utm_campaign=android_launch_developerpreview5_071816&utm_source=anddev&utm_medium=blog#multi-window_support">Multi-window
support
, Direct Reply and other href="https://developer.android.com/preview/api-overview.html?utm_campaign=android_launch_developerpreview5_071816&utm_source=anddev&utm_medium=blog#notification_enhancements">notifications
enhancements
, href="https://developer.android.com/preview/api-overview.html?utm_campaign=android_launch_developerpreview5_071816&utm_source=anddev&utm_medium=blog#direct_boot">Direct
boot
, href="https://developer.android.com/preview/api-overview.html?utm_campaign=android_launch_developerpreview5_071816&utm_source=anddev&utm_medium=blog#emoji">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 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 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 href="https://android.com/beta">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 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 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 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. Android
Nougat is almost here!


Also, the Android engineering team will host a Reddit AMA on r/androiddev 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!

Wednesday, August 17, 2016

Protecting Android with more Linux kernel defenses

Protecting Android with more Linux kernel defenses



Posted by Jeff Vander Stoep, Android Security team



Android relies heavily on the Linux kernel for enforcement of its security
model. To better protect the kernel, we’ve enabled a number of mechanisms within
Android. At a high level these protections are grouped into two
categories—memory protections and attack surface reduction.

Memory protections



One of the major security features provided by the kernel is memory protection
for userspace processes in the form of address space separation. Unlike
userspace processes, the kernel’s various tasks live within one address space
and a vulnerability anywhere in the kernel can potentially impact unrelated
portions of the system’s memory. Kernel memory protections are designed to
maintain the integrity of the kernel in spite of vulnerabilities.

Mark memory as read-only/no-execute



This feature segments kernel memory into logical sections and sets restrictive
page access permissions on each section. Code is marked as read only + execute.
Data sections are marked as no-execute and further segmented into read-only and
read-write sections. This feature is enabled with config option
CONFIG_DEBUG_RODATA. It was put together by Kees Cook and is based on a subset
of Grsecurity’s KERNEXEC feature by Brad
Spengler and Qualcomm’s CONFIG_STRICT_MEMORY_RWX feature by Larry Bassel and
Laura Abbott. CONFIG_DEBUG_RODATA landed in the upstream kernel for arm/arm64
and has been backported to Android’s 3.18+ arm/href="https://android-review.googlesource.com/#/c/174947/">arm64 common
kernel.

Restrict kernel access to userspace



This feature improves protection of the kernel by preventing it from directly
accessing userspace memory. This can make a number of attacks more difficult
because attackers have significantly less control over kernel memory
that is executable, particularly with CONFIG_DEBUG_RODATA enabled. Similar
features were already in existence, the earliest being Grsecurity’s UDEREF. This
feature is enabled with config option CONFIG_CPU_SW_DOMAIN_PAN and was
implemented by Russell King for ARMv7 and backported to href="https://android-review.googlesource.com/#/q/topic:sw_PAN">Android’s
4.1
kernel by Kees Cook.

Improve protection against stack buffer overflows



Much like its predecessor, stack-protector, stack-protector-strong protects
against stack
buffer overflows
, but additionally provides coverage for href="https://outflux.net/blog/archives/2014/01/27/fstack-protector-strong/">more
array types
, as the original only protected character arrays.
Stack-protector-strong was implemented by Han Shen and href="https://gcc.gnu.org/ml/gcc-patches/2012-06/msg00974.html">added to the gcc
4.9 compiler
.


Attack surface reduction



Attack surface reduction attempts to expose fewer entry points to the kernel
without breaking legitimate functionality. Reducing attack surface can include
removing code, removing access to entry points, or selectively exposing
features.

Remove default access to debug features



The kernel’s perf system provides infrastructure for performance measurement and
can be used for analyzing both the kernel and userspace applications. Perf is a
valuable tool for developers, but adds unnecessary attack surface for the vast
majority of Android users. In Android Nougat, access to perf will be blocked by
default. Developers may still access perf by enabling developer settings and
using adb to set a property: “adb shell setprop security.perf_harden 0”.


The patchset for blocking access to perf may be broken down into kernel and
userspace sections. The href="https://android-review.googlesource.com/#/c/234573/">kernel patch is
by Ben Hutchings and is
derived from Grsecurity’s CONFIG_GRKERNSEC_PERF_HARDEN by Brad Spengler. The
userspace changes were href="https://android-review.googlesource.com/#/q/topic:perf_harden">contributed
by Daniel Micay
. Thanks to href="https://conference.hitb.org/hitbsecconf2016ams/sessions/perf-from-profiling-to-kernel-exploiting/">Wish
Wu
and others for responsibly disclosing security vulnerabilities in perf.

Restrict app access to ioctl commands



Much of Android security model is described and enforced by SELinux. The ioctl()
syscall represented a major gap in the granularity of enforcement via SELinux.
Ioctl command
whitelisting with SELinux
was added as a means to provide per-command
control over the ioctl syscall by SELinux.


Most of the kernel vulnerabilities reported on Android occur in drivers and are
reached using the ioctl syscall, for example href="https://source.android.com/security/bulletin/2016-03-01.html#elevation_of_privilege_vulnerability_in_mediatek_wi-fi_kernel_driver">CVE-2016-0820.
Some ioctl commands are needed by third-party applications, however most are not
and access can be restricted without breaking legitimate functionality. In
Android Nougat, only a small whitelist of socket ioctl commands are available to
applications. For select devices, applications’ access to GPU ioctls has been
similarly restricted.

Require seccomp-bpf



Seccomp provides an additional sandboxing mechanism allowing a process to
restrict the syscalls and syscall arguments available using a configurable
filter. Restricting the availability of syscalls can dramatically cut down on
the exposed attack surface of the kernel. Since seccomp was first introduced on
Nexus devices in Lollipop, its availability across the Android ecosystem has
steadily improved. With Android Nougat, seccomp support is a requirement for all
devices. On Android Nougat we are using seccomp on the mediaextractor and
mediacodec processes as part of the href="http://android-developers.blogspot.com/2016/05/hardening-media-stack.html">media
hardening effort
.

Ongoing efforts



There are other projects underway aimed at protecting the kernel:


Due to these efforts and others, we expect the security of the kernel to
continue improving. As always, we appreciate feedback on our work and welcome
suggestions for how we can improve Android. Contact us at href="mailto:security@android.com">security@android.com.

Tuesday, August 16, 2016

Announcing Android add-ons for Docs and Sheets




We know many of you consider your mobile device as your primary tool to consume business information, but what if you could use it to get more work done, from anywhere?

We’re excited to introduce Android add-ons for Docs and Sheets, a new way for you to do just that—whether it’s readying a contract you have for e-signature from your phone, or pulling in CRM data on your tablet for some quick analysis while waiting for your morning coffee, Android add-ons can help you accomplish more.


Get more done with your favorite third-party apps, no matter where you are


We’ve worked with eight integration partners who have created seamless integrations for Docs and Sheets. Here’s a preview of just a few of them:




  • DocuSign - Trigger or complete a signing process from Docs or Sheets, and save the executed document to Drive. Read more here.





DocuSign lets you easily create signature envelopes right from Google Docs



  • ProsperWorks - Import your CRM data to create and update advanced dashboards, reports and graphs on Sheets, right from your device. Read more here.

  • AppSheet - Create powerful mobile apps directly from your data in Sheets instantly — no coding required. Read more here.

  • Scanbot - Scan your business documents using built-in OCR, and insert their contents into Docs as editable text. Read more here.





You can find these add-ons and many more, including PandaDoc, ZohoCRM, Teacher Aide, EasyBib and Classroom in our Google Play collection as well as directly from the add-on menus in Docs or Sheets.







Try them out today, and see how much more you can do.





Calling all developers: try our developer preview today!


As you can see from above, Android add-ons offer a great opportunity to build
innovative integrations and reach Docs and Sheets users around the world.
They’re basically Android apps that connect with href="http://developers.google.com/apps-script?utm_campaign=android_discussion_googledocs_072816&utm_source=anddev&utm_medium=blog">Google Apps Script projects
on the server-side, allowing them to access and manipulate data from Google Docs
or Sheets using standard Apps Script techniques. Check out href="https://developers.google.com/apps-script/add-ons/mobile?utm_campaign=android_discussion_googledocs_072816&utm_source=anddev&utm_medium=blog">our
documentation
which includes href="https://developers.google.com/apps-script/add-ons/mobile/mobile-style?utm_campaign=android_discussion_googledocs_072816&utm_source=anddev&utm_medium=blog">UI
guidelines
as well as href="https://developers.google.com/apps-script/add-ons/mobile/?utm_campaign=android_discussion_googledocs_072816&utm_source=anddev&utm_medium=blog#see_what_you_can_make">sample
code
to get you started. We’ve also made it easy for you to publish your
apps with the Apps Script editor.


Android add-ons are available today as a developer preview. We look forward to
seeing what you build!

Expand Your Global Reach on Google Play With New Language and Country Analytics



With users in 190 countries around the world, Google Play offers you a truly
global audience for your apps and games. Localization is one of the most
powerful ways to connect with people in different places, which is why we
launched translation support for in-app purchase and Universal App Campaigns
earlier this year. With over 30 language translation options available via the
Developer Console, we updated our app translation service to help you select the
most relevant languages, making it quick and easy to get started.


With the launch of new language and country analytics, you gain access to app
install analysis on Google Play, including:

  • Information on the top languages and countries where apps have been
    installed, broken down to the level of your app’s category
  • The percentage of installs that come from users of those languages
  • Further information to help inform your go-to-market plans for these
    countries





To make ordering translations easier, we show language bundles that you can add
to your order in a single click.


To get started, select Manage translations -> Purchase
translations
from the Store Listing page in the href="https://play.google.com/apps/publish/">Google Play Developer Console.

New features for reviews and experiments in Google Play Developer Console app



With over one million apps published through the Google Play Developer Console,
we know how important it is to publish with confidence, acquire users, learn
about them, and manage your business. Whether reacting to a critical performance
issue or responding to a negative review, checking on your apps when and where
you need to is invaluable.


The href="https://play.google.com/store/apps/details?id=com.google.android.apps.playconsole&hl=en">Google
Play Developer Console app
, launched in May, has already helped thousands of
developers stay informed of crucial business updates on the go.


We’re excited to tell you about new features, available today:


Receive notifications about new reviews





Use filters to find the reviews you want





Review and apply store listing experiment results





Increase the percent of a staged rollout or halt a bad staged
rollout






Download the href="https://play.google.com/store/apps/details?id=com.google.android.apps.playconsole">Developer
Console app on Google Play
and stay on top of your apps and games, wherever
you are! Also, get the Playbook for Developers app to stay up-to-date with more features and best practices that will help you grow a successful business on Google Play.

Wednesday, July 20, 2016

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 href="https://g.co/ABH">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.


href="https://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction">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 href="https://en.wikipedia.org/wiki/Erasure_code">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 href="https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=a739ff3f543afbb4a041c16cd0182c8e8d366e70">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.

Friday, July 1, 2016

Building for Billions

Posted by Sam Dutton, Ankur Kotwal, Developer Advocates; Liz Yepsen, Program Manager






‘TOP-UP WARNING.’ ‘NO CONNECTION.’ ‘INSUFFICIENT BANDWIDTH TO PLAY THIS
RESOURCE.’



These are common warnings for many smartphone users around the world.



To build products that work for billions of users, developers must address key
challenges: limited or intermittent connectivity, device compatibility, varying
screen sizes, high data costs, short-lived batteries. We first presented href="https://developers.google.com/billions/?utm_campaign=android_discussion_billions_063016&utm_source=anddev&utm_medium=blog">developers.google.com/billions
and related Android and Web resources at Google I/O last month, and today you
can watch the video presentations about href="https://www.youtube.com/watch?v=vaEV8bNi1Dw">Android or the href="https://www.youtube.com/watch?v=E6hGubMkNfM">Web.



These best practices can help developers reach billions by delivering
exceptional performance across a range of connections, data plans, and devices.
g.co/dev/billions will
help you:



Seamlessly transition between slow, intermediate, and offline
environments



Your users move from place to place, from speedy wireless to patchy or expensive
data. Manage these transitions by storing data, queueing requests, optimizing
image handling, and performing core functions entirely offline.



Provide the right content for the right context



Keep context in mind - how and where do your users consume your content?
Selecting text and media that works well across different viewport sizes,
keeping text short (for scrolling on the go), providing a simple UI that doesn’t
distract from content, and removing redundant content can all increase
perception of your app’s quality while giving real performance gains
like reduced data transfer. Once these practices are in place, localization
options can grow audience reach and increase engagement.



Optimize for mobile hardware



Ensure your app or Web content is served and runs well for your widest possible
addressable market, covering all actively used OS versions, while still
following best practices, by testing on virtual or actual devices in target
markets. Native Android apps should set minimum and target SDKs. Also, remember
low cost phones have smaller amounts of RAM; apps should therefore adjust usage
accordingly and minimize background running. For in-depth information on
minimizing APK size, check out this href="https://medium.com/@wkalicinski/smallerapk-part-8-native-libraries-open-from-apk-fc22713861ff">series
of Medium posts. On the Web, optimize JavaScript CPU usage, avoid raster
image rendering, and minimize resource requests. Find out more href="https://developers.google.com/web/fundamentals/performance/?utm_campaign=android_discussion_billions_063016&utm_source=anddev&utm_medium=blog">here.



Reduce battery consumption



Low cost phones usually have shorter battery life. Users are sensitive to
battery consumption levels and excessive consumption can lead to a high
uninstall rate or avoidance of your site. Benchmark your battery usage against
sessions on other pages or apps, or using tools such as Battery Historian, and
avoid long-running processes which drain batteries.



Conserve data usage



Whatever you’re building, conserve data usage in three simple steps: understand
loading requirements, reduce the amount of data required for interaction, and
streamline navigation so users get what they want quickly. Conserving data on
behalf of your users (and with native apps, offering configurable network usage)
helps retain data-sensitive users -- especially those on prepaid plans or
contracts with limited data -- as even “unlimited” plans can become expensive
when roaming or if unexpected fees are applied.



Have another insight, or a success launching in low-connectivity conditions or
on low-cost devices? Let us know on our href="https://plus.sandbox.google.com/+GoogleDevelopers/posts/WffV23WSrc8">G+
post.

Tuesday, June 28, 2016

Android changes for NDK developers

Android changes for NDK developers

Posted by Dmitry Malykhanov, Developer Advocate




Related to other improvements to the Android platform, the dynamic linker in
Android M and N has stricter requirements for writing clean, cross-platform
compatible native code in order to load. It is necessary that an application’s
native code follows the rules and recommendations in order to ensure a smooth
transition to recent Android releases.



Below we outline in detail each individual change related to native code
loading, the consequences and steps you can take to avoid issues.



Required tools: there is an <arch>-linux-android-readelf binary (e.g.
arm-linux-androideabi-readelf or i686-linux-android-readelf) for each
architecture in the NDK (under toolchains/), but you can use readelf for any
architecture, as we will be doing basic inspection only. On Linux you need to
have the “binutils” package installed for readelf, and “pax-utils” for scanelf.


Private API (Enforced since API 24)



Native libraries must use only href="http://developer.android.com/ndk/guides/stable_apis.html?utm_campaign=android_discussion_ndkchanges_062716&utm_source=anddev&utm_medium=blog">public API,
and must not link against non-NDK platform libraries. Starting with API 24 this
rule is enforced and applications are no longer able to load non-NDK platform
libraries. The rule is enforced by the dynamic linker, so non-public libraries
are not accessible regardless of the way code tries to load them:
System.loadLibrary(...), DT_NEEDED entries, and direct calls to dlopen(...) will
fail in exactly the same way.



Users should have a consistent app experience across updates, and developers
shouldn’t have to make emergency app updates to handle platform changes. For
that reason, we recommend against using private C/C++ symbols. Private symbols
aren’t tested as part of the Compatibility Test Suite (CTS) that all Android
devices must pass. They may not exist, or they may behave differently. This
makes apps that use them more likely to fail on specific devices, or on future
releases --- as many developers found when Android 6.0 Marshmallow switched from
OpenSSL to BoringSSL.



In order to reduce the user impact of this transition, we’ve identified a set of
libraries that see significant use from Google Play’s most-installed apps, and
that are feasible for us to support in the short term (including
libandroid_runtime.so, libcutils.so, libcrypto.so, and libssl.so). In order to
give you more time to transition, we will temporarily support these libraries;
so if you see a warning that means your code will not work in a future release
-- please fix it now!



$ readelf --dynamic libBroken.so | grep NEEDED
0x00000001 (NEEDED) Shared library: [libnativehelper.so]
0x00000001 (NEEDED) Shared library: [libutils.so]
0x00000001 (NEEDED) Shared library: [libstagefright_foundation.so]
0x00000001 (NEEDED) Shared library: [libmedia_jni.so]
0x00000001 (NEEDED) Shared library: [liblog.so]
0x00000001 (NEEDED) Shared library: [libdl.so]
0x00000001 (NEEDED) Shared library: [libz.so]
0x00000001 (NEEDED) Shared library: [libstdc++.so]
0x00000001 (NEEDED) Shared library: [libm.so]
0x00000001 (NEEDED) Shared library: [libc.so]


Potential problems: starting from API 24 the dynamic linker will not load
private libraries, preventing the application from loading.



Resolution: rewrite your native code to rely only on public API. As a short term
workaround, platform libraries without complex dependencies (libcutils.so) can
be copied to the project. As a long term solution the relevant code must be
copied to the project tree. SSL/Media/JNI internal/binder APIs should not be
accessed from the native code. When necessary, native code should call
appropriate public Java API methods.



A complete list of public libraries is available within the NDK, under
platforms/android-API/usr/lib.


Note: SSL/crypto is a special case, applications must NOT use platform libcrypto
and libssl libraries directly, even on older platforms. All applications should
use href="http://developer.android.com/training/articles/security-gms-provider.html?utm_campaign=android_discussion_ndkchanges_062716&utm_source=anddev&utm_medium=blog">GMS
Security Provider to ensure they are protected from known vulnerabilities.


Missing Section Headers (Enforced since API 24)



Each ELF file has additional information contained in the section headers. These
headers must be present now, because the dynamic linker uses them for sanity
checking. Some developers try to strip them in an attempt to obfuscate the
binary and prevent reverse engineering. (This doesn’t really help because it is
possible to reconstruct the stripped information using widely-available tools.)



$ readelf --header libBroken.so | grep 'section headers'
Start of section headers: 0 (bytes into file)
Size of section headers: 0 (bytes)
Number of section headers: 0
$


Resolution: remove the extra steps from your build that strip section headers.


Text Relocations (Enforced since API 23)



Starting with API 23, shared objects must not contain text relocations. That is,
the code must be loaded as is and must not be modified. Such an approach reduces
load time and improves security.



The usual reason for text relocations is non-position independent hand-written
assembler. This is not common. Use the href="https://wiki.gentoo.org/wiki/Hardened/Textrels_Guide#Finding_broken_object_code">scanelf
tool as described in href="http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html?utm_campaign=android_discussion_ndkchanges_062716&utm_source=anddev&utm_medium=blog#behavior-runtime">our
documentation for further diagnostics:



$ scanelf -qT libTextRel.so
libTextRel.so: (memory/data?) [0x15E0E2] in (optimized out: previous simd_broken_op1) [0x15E0E0]
libTextRel.so: (memory/data?) [0x15E3B2] in (optimized out: previous simd_broken_op2) [0x15E3B0]
[skipped the rest]


If you have no scanelf tool available, it is possible to do a basic check with
readelf instead, look for either a TEXTREL entry or the TEXTREL flag. Either
alone is sufficient. (The value corresponding to the TEXTREL entry is irrelevant
and typically 0 --- simply the presence of the TEXTREL entry declares that the
.so contains text relocations). This example has both indicators present:



$ readelf --dynamic libTextRel.so | grep TEXTREL
0x00000016 (TEXTREL) 0x0
0x0000001e (FLAGS) SYMBOLIC TEXTREL BIND_NOW
$


Note: it is technically possible to have a shared object with the TEXTREL
entry/flag but without any actual text relocations. This doesn’t happen with the
NDK, but if you’re generating ELF files yourself make sure you’re not generating
ELF files that claim to have text relocations, because the Android dynamic
linker trusts the entry/flag.



Potential problems: Relocations enforce code pages being writable, and
wastefully increase the number of dirty pages in memory. The dynamic linker has
issued warnings about text relocations since Android K (API 19), but on API 23
and above it refuses to load code with text relocations.



Resolution: rewrite assembler to be position independent to ensure no text
relocations are necessary. Check the href="https://wiki.gentoo.org/wiki/Hardened/Textrels_Guide">Gentoo
documentation for cookbook recipes.


Invalid DT_NEEDED Entries (Enforced since API 23)



While library dependencies (DT_NEEDED entries in the ELF headers) can be
absolute paths, that doesn’t make sense on Android because you have no control
over where your library will be installed by the system. A DT_NEEDED entry
should be the same as the needed library’s SONAME, leaving the business of
finding the library at runtime to the dynamic linker.



Before API 23, Android’s dynamic linker ignored the full path, and used only the
basename (the part after the last ‘/’) when looking up the required libraries.
Since API 23 the runtime linker will honor the DT_NEEDED exactly and so it won’t
be able to load the library if it is not present in that exact location on the
device.



Even worse, some build systems have bugs that cause them to insert DT_NEEDED
entries that point to a file on the build host, something that
cannot be found on the device.



$ readelf --dynamic libSample.so | grep NEEDED
0x00000001 (NEEDED) Shared library: [libm.so]
0x00000001 (NEEDED) Shared library: [libc.so]
0x00000001 (NEEDED) Shared library: [libdl.so]
0x00000001 (NEEDED) Shared library:
[C:\Users\build\Android\ci\jni\libBroken.so]
$


Potential problems: before API 23 the DT_NEEDED entry’s basename was used, but
starting from API 23 the Android runtime will try to load the library using the path
specified, and that path won’t exist on the device. There are broken third-party
toolchains/build systems that use a path on a build host instead of the SONAME.



Resolution: make sure all required libraries are referenced by SONAME only. It
is better to let the runtime linker to find and load those libraries as the
location may change from device to device.


Missing SONAME (Used since API 23)



Each ELF shared object (“native library”) must have a SONAME (Shared Object
Name) attribute. The NDK toolchain adds this attribute by default, so its
absence indicates either a misconfigured alternative toolchain or a
misconfiguration in your build system. A missing SONAME may lead to runtime
issues such as the wrong library being loaded: the filename is used instead when
this attribute is missing.



$ readelf --dynamic libWithSoName.so | grep SONAME
0x0000000e (SONAME) Library soname: [libWithSoName.so]
$


Potential problems: namespace conflicts may lead to the wrong library being
loaded at runtime, which leads to crashes when required symbols are not found,
or you try to use an ABI-incompatible library that isn’t the library you were
expecting.



Resolution: the current NDK generates the correct SONAME by default. Ensure
you’re using the current NDK and that you haven’t configured your build system
to generate incorrect SONAME entries (using the -soname linker
option).



Please remember, clean, cross-platform code built with a current NDK should have
no issues on Android N. We encourage you to revise your native code build so
that it produces correct binaries.

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!


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.

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!