Author Archives: Reto Meier

Developing for Direct Boot

Posted by Wojtek Kaliciński, Developer Advocate

Starting with Android N, a device that has been powered on can boot into a new mode called Direct Boot before the user has a chance to unlock it for the first time. In this mode, the operating system is fully operational, but access to private app data is limited and only apps that have been updated to be Direct Boot aware can run.

Is Direct Boot right for my app?

Not every app should run in Direct Boot mode, so before you start coding check if your app fits these common use cases:

  • Apps that schedule alarms, such as alarm clocks.
  • Apps that provide important and timely notifications, like messaging apps.
  • Apps that provide services to other apps or the system, such as Accessibility Services.

Please note that this is not an exhaustive list and we look forward to seeing what other kinds of apps can benefit from Direct Boot.

Making your app Direct Boot aware

In order to let your app run before the user unlocks the device, you have to explicitly mark components as being Direct Boot aware in the manifest:

 <activity|provider|receiver|service ...  
     android:directBootAware=”true”>  

You can pick the subset of your app components that need to be Direct Boot aware, but if you are using a custom Application class, it is assumed to be Direct Boot aware if any component inside your app is marked as Direct Boot aware.

For apps that need to run as soon as the system starts in Direct Boot mode, there is a new Intent.ACTION_LOCKED_BOOT_COMPLETED broadcast. All apps will still receive Intent.ACTION_BOOT_COMPLETED after the user unlocks the device.

Using the device protected storage area

To support running apps before the user provides the credentials needed to unlock private app data, all Android N devices now provide two storage locations for data:

  • Credential protected storage, which is the default storage location for all apps, available only after the user has unlocked the device
  • Device protected storage, which is a new storage location that can be accessed at all times when the device is booted, including during Direct Boot

Components of your app that are marked as Direct Boot aware must rely on device protected storage for any data required for their operation during Direct Boot mode. They may still access credential protected storage after the user has unlocked the device.

To access device protected storage you need to create and use a secondary Context object for all file-related APIs:

 Context deviceProtectedContext = context.createDeviceProtectedStorageContext();  
 deviceProtectedContext.openFileInput( ... )  

When your app gets updated to a Direct Boot aware version, you might have previously saved Shared Preferences or databases that need to be migrated to device protected storage. You should use Context.moveSharedPreferencesFrom() and Context.moveDatabaseFrom() before accessing them to make sure the app continues to work properly even when data is backed up and restored from older versions or other devices.

Things to watch out for

You should think carefully about what you put in the device protected storage. This should be a minimum set of data that will let your app work during Direct Boot. For example, in a messaging app you could store an access token with a narrow scope that only has access to the number of new messages on your server. All sensitive, private information, like the full message history and a read/write access token, should still be saved in credential protected storage.

Another thing to remember is that during Direct Boot apps can only access other Direct Boot aware apps and components. If your app depends on external Services and Activities, make sure you gracefully handle the situation when they’re not available. Intent filters will by default match only components available in the current user state (locked / unlocked). There are two new flags for explicitly telling the Package Manager which components to enumerate: PackageManager.MATCH_DIRECT_BOOT_AWARE and PackageManager.MATCH_DIRECT_BOOT_UNAWARE.

What’s next?

Until devices with Android N that support Direct Boot out of the box are released, you can test your apps using Android N Developer Preview builds. On Nexus 5X and Nexus 6P, you can wipe all user data and enable full Direct Boot mode by using Settings > Developer options > Convert to file encryption. Alternatively, you can reboot into bootloader and issue the appropriate fastboot command:

 $ adb reboot-bootloader  
 $ fastboot --wipe-and-use-fbe  

Warning: Both methods will perform a factory reset and delete all user data on your device.

Alternatively, you can use an emulated Direct Boot mode. To enable it, set a lock pattern on the device, choose "No thanks" if prompted for a secure start-up screen when setting a lock pattern, and then use the following adb shell commands to enable and disable emulation:

 $ adb shell sm set-emulate-fbe true  
 $ adb shell sm set-emulate-fbe false  

Please note that using these commands will cause your device to reboot. You should only be using emulated Direct Boot mode on test devices, as it may cause data loss.

#BuildBetterApps

Follow the Android Development Patterns Collection for more!

Android Studio 2.1 supports Android N Developer Preview

Posted by Jamal Eason, Product Manager, Android

With the launch Android N Developer Preview, we wanted to give you an easy and comprehensive way to build, test and validate your apps on the latest release with Android Studio. Built on the speed and feature enhancements of Android Studio 2.0, the stable release of Android Studio 2.1 includes updates to the IDE wizards, build system and Android Emulator so that you can try out new features and APIs of the developer preview including the new Jack compiler and Java 8 language support. In addition to support for the N Developer Preview, Android Studio 2.1 also includes performance improvements to Instant Run which leads to faster edit and deploy build speeds. If you are developing and validating your app with the N Developer Preview or want faster Instant Run speeds, you should download or update on the stable release channel to Android Studio 2.1.

Android Studio 2.1 includes the following new features:

  • N Developer Preview Support: Android Studio 2.1 is the best IDE to test and validate your app with the N Developer Preview. Get the latest versions of the preview SDK, experiment with the new Java 8 support, and gain access to the only official Android Emulator able to run N Developer Preview Emulator System Images to help in your testing.
  • Instant Run: For those of you who enjoyed the fast edit, build and deploy cycle with Android Studio 2.0, Instant Run now can now update incremental changes to your app code significantly faster.

Deeper Dive into the New Features

N Developer Preview

On top of new features and APIs of the N Developer Preview, Android Studio 2.1 release includes support for the new Jack compiler and support for Java 8. With the Jack compiler, lambdas, method references, compile-time type annotations, intersection types and type inference are available on all versions of the Android platform. Default and static methods and repeatable annotations are available on Android N and higher. To use Java 8 language features when developing with the N Developer Preview, you need to use the Jack compiler. The New Project Wizard [File→ New→ Project] generates the correct configurations for projects targeting the N.

Getting started with development is as easy generating a new project or updating a few settings in your existing project. Once you are ready to test, you can create a fresh Android Virtual Device (AVD) and run your app on the N Developer Preview using the new Android Emulator.


N Developer Preview on the new Android Emulator

Instant Run & General Build Performance Improvements

Instant Run and general build speed are now faster with two new features: incremental Java compilation and in-process dex.

In previous versions of Android Studio, a single line of Java code change will cause all the Java sources in the module to be recompiled. Now in Android Studio 2.1, incremental Java compilation is enabled by default to reduce compilation time by compiling only what is needed.

We are also speeding up build times by using in-process dex, which converts class files to dex files within the Gradle daemon process. This avoids the costly processing operation of creating separate dex processes. To use this feature, you will need to increase the amount of memory available to the Gradle daemon to at least 2GB (1 GB is the default). This feature will help speed up both incremental and full builds.

We’d appreciate your feedback as we continue to improve Instant Run and general build performance. We are going to keep working on making build times even faster in coming releases. Click here to learn even more about the build changes.

What's Next

Update

If you are using a previous version of Android Studio, you can check for updates on the Stable channel from the navigation menu (Help → Check for Update [Windows/Linux] , Android Studio → Check for Updates [OS X]). If you need a new copy of Android Studio, you can download it here.

Test and Validate Apps with N Developer Preview

After you update to or download Android Studio 2.1 and you want to test and develop your apps with the N Developer Preview, create a fresh Android Virtual Device (AVD) for the new Android emulator, and check out these additional setup instructions.

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

Building TV Channels

Posted by Josh Gordon, Developer Advocate

Channel surfing is a popular way of watching TV. You pick up the remote, lean back, and flip through channels to see what’s on. On Android TV, app developers can create their own channel-like experiences using the TV Input Framework.

To the user, the channels you create look and feel just like regular TV channel. But behind the scenes, they stream video over the internet. For example, you can create a channel from a video playlist.

Watch this DevByte for an overview of how to build to a channel, and see the sample app and developer training for more info. The sample shows how to work with a variety of media formats, including HLS, MPEG-Dash, and HTTP Progressive.



If you already have an app that streams video, consider also making your content available as a channel. It’s a great opportunity to increase engagement. We’re excited to see what you develop, and look forward to seeing your content on the big screen!

Protecting against unintentional regressions to cleartext traffic in your Android apps

Posted by Alex Klyubin, Android Security team

When your app communicates with servers using cleartext network traffic, such as HTTP, the traffic risks being eavesdropped upon and tampered with by third parties. This may leak information about your users and open your app up to injection of unauthorized content or exploits. Ideally, your app should use secure traffic only, such as by using HTTPS instead of HTTP. Such traffic is protected against eavesdropping and tampering.

Many Android apps already use secure traffic only. However, some of them occasionally regress to cleartext traffic by accident. For example, an inadvertent change in one of the server components could make the server provide the app with HTTP URLs instead of HTTPS URLs. The app would then proceed to communicate in cleartext, without any user-visible symptoms. This situation may go unnoticed by the app’s developer and users.

Even if you believe your app is only using secure traffic, make sure to use the new mechanisms provided by Android Marshmallow (Android 6.0) to catch and prevent accidental regressions.

New protection mechanisms

For apps which only use secure traffic, Android 6.0 Marshmallow (API Level 23) introduced two mechanisms to address regressions to cleartext traffic: (1) in production / installed base, block cleartext traffic, and (2) during development / QA, log or crash whenever non-TLS/SSL traffic is encountered. The following sections provide more information about these mechanisms.

Block cleartext traffic in production

To protect the installed base of your app against regressions to cleartext traffic, declare android:usesCleartextTraffic=”false” attribute on the application element in your app’s AndroidManifest.xml. This declares that the app is not supposed to use cleartext network traffic and makes the platform network stacks of Android Marshmallow block cleartext traffic in the app. For example, if your app accidentally attempts to sign in the user via a cleartext HTTP request, the request will be blocked and the user’s identity and password will not leak to the network.

You don’t have to set minSdkVersion or targetSdkVersion of your app to 23 (Android Marshmallow) to use android:usesCleartextTraffic. On older platforms, this attribute is simply ignored and thus has no effect.

Please note that WebView does not yet honor this feature.

And under certain circumstances cleartext traffic may still leave or enter the app. For example, Socket API ignores the cleartext policy because it does not know whether the data it transmits or receives can be classified as cleartext. Android platform HTTP stacks, on the other hand, honor the policy because they know whether traffic is cleartext.

Google AdMob is also built to honor this policy. When your app declares that it does not use cleartext traffic, only HTTPS-only ads should be served to the app.

Third-party network, ad, and analytics libraries are encouraged to add support for this policy. They can query the cleartext traffic policy via the NetworkSecurityPolicy class.

Detect cleartext traffic during development

To spot cleartext traffic during development or QA, StrictMode API lets you modify your app to detect non-TLS/SSL traffic and then either log violations to system log or crash the app (see StrictMode.VmPolicy.Builder.detectCleartextNetwork()). This is a useful tool for identifying which bits of the app are using non-TLS/SSL (and DLTS) traffic. Unlike the android:usesCleartextTraffic attribute, this feature is not meant to be enabled in app builds distributed to users.

Firstly, this feature is supposed to flag secure traffic that is not TLS/SSL. More importantly, TLS/SSL traffic via HTTP proxy also may be flagged. This is an issue because as a developer, you have no control over whether a particular user of your app may have configured their Android device to use an HTTP proxy. Finally, the implementation of the feature is not future-proof and thus may reject future TLS/SSL protocol versions. Thus, this feature is intended to be used only during the development and QA phase.

Declare finer-grained cleartext policy in Network Security Config

Android N offers finer-grained control over cleartext traffic policy. As opposed to android:usesCleartextTraffic attribute, which applies to all destinations with which an app communicates, Android N’s Network Security Config lets an app specify cleartext policy for specific destinations. For example, to facilitate a more gradual transition towards a policy that does not allow cleartext traffic, an app can at first block accidental cleartext only for communication with its most important backends and permit cleartext to be used for other destinations.

Next steps

It is a security best practice to only use secure network traffic for communication between your app and its servers. Android Marshmallow enables you to enforce this practice, so give it a try!

As always, we appreciate feedback and welcome suggestions for improving Android. Contact us at [email protected]. HTTPS, Android-Security

An Outsourcing Playbook for Android development

Posted by Rupert Whitehead, Developer Relations

We recently updated The Secrets to App Success on Google Play with tools and tips to help app and game developers grow successful businesses on Google Play. However, many great apps are created by agencies and freelancers on behalf of companies. Today, we’re releasing a new playbook to help companies of any size who are considering outsourcing their Android app development.

How do you choose an agency? What are the pitfalls you should avoid? What can you do to make your app successful? These are some of the questions tackled by the new Outsourcing Playbook that you can read on Google Play.


Let us know your feedback

Once you’ve checked out the guide, we’d love to hear your feedback so we can continue to improve our developer resources and support. Let us know what you think.

The Google Play Awards coming to Google I/O

Posted by Purnima Kochikar, Director, Apps and Games Business Development, Google Play

Google Play has seen tremendous growth over the past year, reaching more than 1 billion Android users across 190 countries. As a way to recognize our incredible developer community and highlight some of the best apps and games, we’re kicking off our first-ever Google Play Awards.

The program will showcase five nominees across 10 award categories and feature them in a dedicated collection on Google Play. Nominees were selected by a panel of experts on the Google Play team based on criteria emphasizing app quality, innovation, and having a launch or major update in the last 12 months. The winners of each category will be announced at Google I/O in May.

The full list of categories and nominees are below:

Standout Startup

Apps from new developers that offer a unique experience while achieving strong install growth. And the nominees are...

Dubsmash
Hopper
Musical.ly
Robinhood
Vrse

Standout Indie

Games from indie developers that focus on artistic design, high quality and innovative gameplay. And the nominees are...

Alphabear
Alto’s Adventure
Fast like a Fox
Neko Atsume: Kitty Collector
Prune

Best Families App

Apps or games with family friendly design that encourage creativity and exploration. And the nominees are...

Card Wars - Adventure Time
LEGO Jurassic World™
My Very Hungry Caterpillar
Thinkrolls 2
Toca Nature

Best Use of Material Design

First-class implementation of material design concepts that deliver an immersive and innovative user experience. And the nominees are...

Bring!
Robinhood
The Fabulous
Todoist
Vevo

Best Use of Google Play Game Services

High quality games with several strong GPGS feature implementations. And the nominees are...

Sea Battle 2
Table Tennis Touch
Tapventures
TowerMadness 2
Zombie Highway 2

Early Adopter

Early adopter of a nascent technology or platform, providing a delightful user experience. And the nominees are...

Glide
Mechanic Escape
Minecraft: Story Mode
World Around Me
Zumper

Go Global

Apps or games with great localization and culturalization, or subject matter appeal, across multiple regions. And the nominees are...

Dragon Ball Z Dokkan Battle
Freeletics Bodyweight
Memrise
Musixmatch
Pokémon Shuffle Mobile

Most Innovative

Apps or games offering a highly engaging novelty experience or unique benefit. And the nominees are...

Fast like a Fox
NYT VR
SmartNews
The Fabulous
This War of Mine

Best App

A true representation of beautiful design, intuitive UX and high user appeal, quality and rating. And the nominees are...

BuzzFeed News
Colorfy
Houzz
TuneIn Radio
Yummly

Best Game

Games with strong mechanics, informative tutorial, broad appeal and tasteful design. And the nominees are...

Alphabear
Clash of Kings
Clash Royale
MARVEL Future Fight
Star Wars™: Galaxy of Heroes

Join us live at the ceremony on May 19th at 7:00 pm PDT on stage 7 at Google I/O or via the live stream. You can also track the conversation on Twitter and G+ using the hashtags #io16.

Build beautifully for Android Wear’s Round Screen using API 23’s -round identifier

Posted by Hoi Lam, Android Wear Developer Advocate

Android Wear is about choice. From the beginning, users could choose the style they wanted, including watches with circular screens. With Android Wear API 23, we have enabled even better developer support so that you can code delightful experiences backed by beautiful code. The key component of this is the new round resource identifier which helps you separate resource files such as layouts, dimens between round and square devices. In this blog post, I will lay out the options that developers have and why you should consider dimens.xml! In addition, I will outline how best to deal with devices which have a chin.

Getting started? Consider BoxInsetLayout!

If all your content can fit into a single square screen, use the BoxInsetLayout. This class has been included in the Wearable Support Library from the start and helps you put all the content into the middle square area of the circular screen and is ignored by square screens. For details on how to use the BoxInsetLayout, refer to the Use a Shape-Aware Layout section in our developer guide.

Without BoxInsetLayout
With BoxInsetLayout

Goodbye WatchViewStub, Hello layout-round!

Developers have been able to specify different layouts for square and round watches using WatchViewStub from the beginning. With Android Wear API 23, this has become even easier. Developers can put different layouts into layout-round and layout folders. Previously with WatchViewStub, developers needed to wait until the layout was inflated before attaching view elements, this added significant complexity to the code. This is eliminated using the -round identifier:

 Pre Android Wear API 23 - WatchViewStub (4 files)

1. layout/activity_main.xml
 <?xml version="1.0" encoding="utf-8"?>  
 
<android.support.wearable.view.WatchViewStub    
     xmlns
:android="http://schemas.android.com/apk/res/android"  
     xmlns
:app="http://schemas.android.com/apk/res-auto"  
     xmlns
:tools="http://schemas.android.com/tools"  
     android
:id="@+id/watch_view_stub"  
     android
:layout_width="match_parent"  
     android
:layout_height="match_parent"  
     app
:rectLayout="@layout/rect_activity_main"  
     app
:roundLayout="@layout/round_activity_main"  
     tools
:context="com.android.example.watchviewstub.MainActivity"  
     tools
:deviceIds="wear"></android.support.wearable.view.WatchViewStub>

2. layout/rect_activity_main.xml - layout for square watches

3. layout/round_activity_main.xml - layout for round watches

4. MainAcitivity.java
  
 
protected void onCreate(Bundle savedInstanceState) {  
   
super.onCreate(savedInstanceState);  
   setContentView
(R.layout.activity_main);  
   
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);  
   stub
.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {  
     
@Override  
     
public void onLayoutInflated(WatchViewStub stub) {  
       mTextView
= (TextView) stub.findViewById(R.id.text);  
     
}  
   
});  
 
}  

 After Android Wear API 23 - layout-round (3 files)

1. layout-notround/activity_main.xml - layout for square watches

2. layout-round/activity_main.xml - layout for round watches

3. MainAcitivity.java
 protected void onCreate(Bundle savedInstanceState) {  
     
super.onCreate(savedInstanceState);  
     setContentView
(R.layout.activity_main);  
     mTextView
= (TextView) findViewById(R.id.text);    
 
}  

That said, since WatchViewStub is part of the Android Wear Support Library, if your current code uses it, it is not a breaking change and you can refactor your code at your convenience. In addition to the -round identifier, developers also use the -notround idenifier to separate resources. So why would you want to use it in place of the default layout? It’s a matter of style. If you have a mixture of layouts, you might consider organising layouts in this way:

  • layout/ - Layouts which works for both circular and square watches
  • layout-round/ and layout-notround/ - Screen shape specific layouts

An even better way to develop for round - values-round/dimens.xml

Maintaining multiple layout files is potentially painful. Each time you add a screen element, you need to go to all the layout files and add this. With mobile devices, you will usually only do this to specify different layouts for phones and tablets and rarely for different phone resolutions. For watches, unless your screen layout is significantly different between round and square (which is rare based on the applications I have seen thus far), you should consider using different dimens.xml instead.

As I experimented with the -round identifier, I found that the easiest way to build for round and square watches is actually by specifying values/dimens.xml and values-round/dimens.xml. By specifying different padding settings, I am able to create the following layout with the same layout.xml file and two dimens files - one for square and one for round. The values used suits this layout, you should experiment with different values to see what works best:

values-round/dimens.xml values/dimens.xml
 <dimen name="header_start_padding">36dp</dimen>  
 
<dimen name="header_end_padding">22dp</dimen>  
 
<dimen name="list_start_padding">36dp</dimen>  
 
<dimen name="list_end_padding">22dp</dimen>  
 <dimen name="header_start_padding">16dp</dimen>  
 
<dimen name="header_end_padding">16dp</dimen>  
 
<dimen name="list_start_padding">10dp</dimen>  
 
<dimen name="list_end_padding">10dp</dimen>  

Before API 23, to do the same would have involved a significant amount of boilerplate code manually specifying the different dimensions for all elements on the screen. With the -round identifier, this is now easy to do in API 23 and is my favourite way to build round / square layouts.

Don’t forget the chin!

Some watches have an inset (also know as a “chin”) in an otherwise circular screen. So how should you can you build a beautiful layout while keeping your code elegant? Consider this design:

activity_main.xml

 <FrameLayout  
   
...>  
   
<android.support.wearable.view.CircledImageView  
     android
:id="@+id/androidbtn"  
     android
:src="@drawable/ic_android"  
     
.../>  
   
<ImageButton  
     android
:id="@+id/lovebtn"  
     android
:src="@drawable/ic_favourite"  
     android
:paddingTop="5dp"  
     android
:paddingBottom="5dp"  
     android
:layout_gravity="bottom"  
     
.../>  
 
</FrameLayout>  

If we are to do nothing, the heart shape button will disappear into the chin. Luckily, there’s an easy way to fix this with fitsSystemWindows:

 <ImageButton  
     
android:id="@+id/lovebtn"  
     
android:src="@drawable/ic_favourite"  
     
android:paddingTop="5dp"  
     
android:paddingBottom="5dp"  
   
android:fitsSystemWindows="true"  
     ...
/>  

For the eagle-eyed (middle image of the screen shown below under “fitsSystemWindows=”true””), you might noticed that the top and bottom padding that we have put in is lost. This is one of the main side effect of using fitsSystemWindows. This is because fitsSystemWindows works by overriding the padding to make it fits the system window. So how do we fix this? We can replace padding with InsetDrawables:

inset_favourite.xml

 <inset  
   
xmlns:android="http://schemas.android.com/apk/res/android"  
   
android:drawable="@drawable/ic_favourite"
   
android:insetTop="5dp"  
   
android:insetBottom="5dp"
/>  

activity_main.xml

 <ImageButton  
     
android:id="@+id/lovebtn"  
     
android:src="@drawable/inset_favourite"  
     
android:paddingTop="5dp"  
     
android:paddingBottom="5dp"  
     
android:fitsSystemWindows="true"  
     ...
/>  

Although the padding setting in the layout will be ignored, the code is tidier if we remove this redundant code.

Do nothing
fitsSystemWindows=”true”
fitsSystemWindows=”true”
and use InsetDrawable

If you require more control than what is possible declaratively using xml, you can also programmatically adjust your layout. To obtain the size of the chin you should attach a View.OnApplyWindowInsetsListener to the outermost view of your layout. Also don’t forget to call v.onApplyWindowInsets(insets). Otherwise, the new listener will consume the inset and inner elements which react to insets may not react.

How to obtain the screen chin size programmatically

MainActivity.java

 private int mChinSize;  
 
protected void onCreate(Bundle savedInstanceState) {  
     
super.onCreate(savedInstanceState);  
     setContentView
(R.layout.activity_main);  
     
// find the outermost element  
     
final View container = findViewById(R.id.outer_container);  
     
// attach a View.OnApplyWindowInsetsListener  
     
container.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {  
         
@Override  
         
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {  
             mChinSize
= insets.getSystemWindowInsetBottom();  
           
 // The following line is important for inner elements which react to insets  
             v.onApplyWindowInsets(insets);

             
return insets;  
     
}  
   
});  
 
}  

Last but not least, remember to test your code! Since last year, we have included several device images for Android Wear devices with a chin to make testing easier and faster:

Square peg in a round hole no more!

Android Wear has always been about empowering users to wear what they want. A major part in enabling this is the round screen. With API 23 and the -round resource identifier, it is easier than ever to build for both round and square watches - delightful experiences backed by beautiful code!

Additional Resources

Why would I want to fitsSystemWindows? by Ian Lake - Best practice for using this powerful tool including its limitations. ScreenInfo Utility by Wayne Piekarski - Get useful information for your display including DPI, chin size, etc.

Deprecation of BIND_LISTENER with Android Wear APIs

Posted by Wayne Piekarski, Developer Advocate, Android Wear

If you’re an Android Wear developer, we wanted to let you know of a change you might need to make to your app to improve the performance of your user’s devices. If your app is using BIND_LISTENER intent filters in your manifest, it is important that you are aware that this API has been deprecated on all Android versions. The new replacement API introduced in Google Play Services 8.2 is more efficient for Android devices, so developers are encouraged to migrate to this as soon as possible to ensure the best user experience. It is important that all Android Wear developers are aware of this change and update their apps as soon as possible.

Limitations of BIND_LISTENER API

When Android Wear introduced the WearableListenerService, it allowed you to listen to changes via the BIND_LISTENER intent filter in the AndroidManifest.xml. These changes included data item changes, message arrivals, capability changes, and peer connects/disconnects.

The WearableListenerService starts whenever any of these events occur, even if the app is only interested in one type. When a phone has a large number of apps using WearableListenerService and BIND_LISTENER, a watch appearing or disappearing can cause many services to start up. This applies memory pressure to the device, causing other activities and services to be shut down, and generates unnecessary work.

Fine-grained intent filter API

In Google Play Services 8.2, we introduced a new fine-grained intent filter mechanism that allows developers to specify exactly what events they are interested in. For example, if you have multiple listener services, use a path prefix to filter only those data items and messages meant for the service, with syntax like this:


 <service android:name=".FirstExampleService">  
   <intent-filter>  
       <action android:name="com.google.android.gms.wearable.DATA_CHANGED" />  
       <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />  
       <data android:scheme="wear" android:host="*" android:pathPrefix="/FirstExample" />  
   </intent-filter>  
 </service>  

There are intent filters for DATA_CHANGED, MESSAGE_RECEIVED, CHANNEL_EVENT, and CAPABILITY_CHANGED. You can specify multiple elements, and if any of them match, it will call your service and filter out anything else. If you do not include a element, all events will be filtered out and your service will never be called, so make sure to include at least one. You should be aware that registering in an AndroidManifest.xml for CAPABILITY_CHANGED will cause your service to be called any time a device advertising this capability appears or disappears, so you should use this only if there is a compelling reason.

Live listeners

If you only need these events when an Activity or Service is running, then there is no need to register a listener in AndroidManifest.xml at all. Instead, you can use addListener() live listeners, which will only be active when the Activity or Service is running, and will not impact the device otherwise. This is particularly useful if you want to do live status updates for capabilities being available in an Activity, but with no further background impact. In general, you should try to use addListener(), and only use AndroidManifest.xml when you need to receive events all the time.

Best practices

In general, you should only use a listener in AndroidManifest.xml for events that must launch your service. For example, if your watch app needs to send an interactive message or data to the phone.

You should try to limit the number of wake-ups of your service by using filters. If most of the events do not need to launch your app, then use a path and a filter that only matches the event you need. This is critical to limit the number of launches of your service.

If you have other cases where you do not need to launch a service, such as listening for status updates in an Activity, then register a live listener only for the duration it is needed.

Documentation

There is more information available about Data Layer events and the use of WearableListenerService, and tags in the manifest. Android Studio has a guide with a summary of how to convert to the new API. The Android Wear samples also show best practices in the use of WearableListenerService, such as DataLayer and XYZTouristAttractions. The changes needed are very small, and can be seen in this git diff from one of the samples here.

Removal of BIND_LISTENER

With the release of Android Studio 2.1, lint rules have been added that flag the use of BIND_LISTENER as a fatal error, and developers will need to make a small change to the AndroidManifest.xml to declare accurate intent filters. If you are still using BIND_LISTENER, you will receive the following error:

 AndroidManifest.xml:11: Error: The com.google.android.gms.wearable.BIND_LISTENER action is deprecated. [WearableBindListener]  
          <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />  
              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  

This will only impact developers who are recompiling their apps with Android Studio 2.1 and will not affect existing apps on user’s devices.

For developers who are using Google Play Services earlier than 8.2, the lint rules will not generate an error, but you should update to a newer version and implement more accurate intent filters as soon as possible.

In order to give users the best experience, we plan to disable BIND_LISTENER in the near future. It is therefore important that developers take action now, to avoid any future disruption experienced by users of their apps.

Optimize, Develop, and Debug with Vulkan Developer Tools

Posted by Shannon Woods, Technical Program Manager

Today we're pleased to bring you a preview of Android development tools for Vulkan™. Vulkan is a new 3D rendering API which we’ve helped to develop as a member of Khronos, geared at providing explicit, low-overhead GPU (Graphics Processor Unit) control to developers. Vulkan’s reduction of CPU overhead allows some synthetic benchmarks to see as much as 10 times the draw call throughput on a single core as compared to OpenGL ES. Combined with a threading-friendly API design which allows multiple cores to be used in parallel with high efficiency, this offers a significant boost in performance for draw-call heavy applications.

Vulkan support is available now via the Android N Preview on devices which support it, including Nexus 5X and Nexus 6P. (Of course, you will still be able to use OpenGL ES as well!)

To help developers start coding quickly, we’ve put together a set of samples and guides that illustrate how to use Vulkan effectively.

You can see Vulkan in action running on an Android device with Robert Hodgin’s Fish Tornado demo, ported by Google’s Art, Copy, and Code team:


Optimization: The Vulkan API

There are many similarities between OpenGL ES and Vulkan, but Vulkan offers new features for developers who need to make every millisecond count.


  • Application control of memory allocation. Vulkan provides mechanisms for fine-grained control of how and when memory is allocated on the GPU. This allows developers to use their own allocation and recycling policies to fit their application, ultimately reducing execution and memory overhead and allowing applications to control when expensive allocations occur.
  • Asynchronous command generation. In OpenGL ES, draw calls are issued to the GPU as soon as the application calls them. In Vulkan, the application instead submits draw calls to command buffers, which allows the work of forming and recording the draw call to be separated from the act of issuing it to the GPU. By spreading command generation across several threads, applications can more effectively make use of multiple CPU cores. These command buffers can also be reused, reducing the overhead involved in command creation and issuance.
  • No hidden work. One OpenGL ES pitfall is that some commands may trigger work at points which are not explicitly spelled out in the API specification or made obvious to the developer. Vulkan makes performance more predictable and consistent by specifying which commands will explicitly trigger work and which will not.
  • Multithreaded design, from the ground up. All OpenGL ES applications must issue commands for a context only from a single thread in order to render predictably and correctly. By contrast, Vulkan doesn’t have this requirement, allowing applications to do work like command buffer generation in parallel— but at the same time, it doesn’t make implicit guarantees about the safety of modifying and reading data from multiple threads at the same time. The power and responsibility of managing thread synchronization is in the hands of the application.
  • Mobile-friendly features. Vulkan includes features particularly helpful for achieving high performance on tiling GPUs, used by many mobile devices. Applications can provide information about the interaction between separate rendering passes, allowing tiling GPUs to make effective use of limited memory bandwidth, and avoid performing off-chip reads.
  • Offline shader compilation. Vulkan mandates support for SPIR-V, an intermediate language for shaders. This allows developers to compile shaders ahead of time, and ship SPIR-V binaries with their applications. These binaries are simpler to parse than high-level languages like GLSL, which means less variance in how drivers perform this parsing. SPIR-V also opens the door for third parties to provide compilers for specialized or cross-platform shading languages.
  • Optional validation. OpenGL ES validates every command you call, checking that arguments are within expected ranges, and objects are in the correct state to be operated upon. Vulkan doesn’t perform any of this validation itself. Instead, developers can use optional debug tools to ensure their calls are correct, incurring no run-time overhead in the final product.

Debugging: Validation Layers


As noted above, Vulkan’s lack of implicit validation requires developers to make use of tools outside the API in order to validate their code. Vulkan’s layer mechanism allows validation code and other developer tools to inspect every API call during development, without incurring any overhead in the shipping version. Our guides show you how to build the validation layers for use with the Android NDK, giving you the tools necessary to build bug-free Vulkan code from start to finish.

Develop: Shader toolchain


The Shaderc collection of tools provides developers with build-time and run-time tools for compiling GLSL into SPIR-V. Shaders can be compiled at build time using glslc, a command-line compiler, for easy integration into existing build systems. Or, for shaders which are generated or edited during execution, developers can use the Shaderc library to compile GLSL shaders to SPIR-V via a C interface. Both tools are built on top of Khronos’s reference compiler.

Additional Resources


The Vulkan ecosystem is a broad one, and the resources to get you started don’t end here. There is a wealth of material to explore, including:

Android N Developer Preview 2, out today!

Posted by Dave Burke, VP of Engineering

Last month, we released the first Developer Preview of Android N, to give you a sneak peek at our next platform. The feedback you’ve shared to-date has helped us catch bugs and improve features. Today, the second release in our series of Developer Previews is ready for you to continue testing against your apps.

This latest preview of Android N fixes a few bugs you helped us identify, such as not being able to connect to hidden Wi-Fi networks (AOSP 203116), Multiwindow pauses (AOSP 203424), and Direct Reply closing an open activity (AOSP 204411), to name just a few. We’re still on the hunt for more; please continue to share feedback, either in the N Developer Preview issue tracker or in the N preview community.

What’s new:

Last month’s Developer Preview introduced a host of new features, like Multi-window, bundled notifications and more. This preview builds on those and includes a few new ones:

  • Vulkan: Vulkan is a new 3D rendering API which we’ve helped to develop as a member of Khronos, geared at providing explicit, low-overhead GPU (Graphics Processor Unit) control to developers and offers a significant boost in performance for draw-call heavy applications. Vulkan’s reduction of CPU overhead allows some synthetic benchmarks to see as much as 10 times the draw-call throughput on a single core as compared to OpenGL ES. Combined with a threading-friendly API design which allows multiple cores to be used in parallel with high efficiency, this offers a significant boost in performance for draw-call heavy applications. With Android N, we’ve made Vulkan a part of the platform; you can try it out on supported devices running Developer Preview 2. Read more here. Vulkan Developer Tools blog here.

  • Launcher shortcuts: Now, apps can define shortcuts which users can expose in the launcher to help them perform actions quicker. These shortcuts contain an Intent into specific points within your app (like sending a message to your best friend, navigating home in a mapping app, or playing the next episode of a TV show in a media app).

    An application can publish shortcuts with ShortcutManager.setDynamicShortcuts(List) and ShortcutManager.addDynamicShortcut(ShortcutInfo), and launchers can be expected to show 3-5 shortcuts for a given app.


  • Emoji Unicode 9 support: We are introducing a new emoji design for people emoji that moves away from our generic look in favor of a more human-looking design. If you’re a keyboard or messaging app developer, you should start incorporating these emoji into your apps. The update also introduces support for skin tone variations and Unicode 9 glyphs, like the bacon, selfie and face palm. You can dynamically check for the new emoji characters using Paint.hasGlyph().

New human emoji

New activity emoji

  • API changes: This update includes API changes as we continue to refine features such as multi-window support (you can now specify a separate minimum height and minimum width for an activity), notifications, and others. For details, take a look at the diff reports available in the downloadable API reference package.

  • Bug fixes: We’ve resolved a number of issues throughout the system, including these fixes for issues that you’ve reported through the public issue tracker. Please continue to let us know what you find and follow along with the known issues here.

How to get the update:

The easiest way to get this and later preview updates is by enrolling your devices in the Android Beta Program. Just visit g.co/androidbeta and opt-in your eligible Android phone or tablet -- you’ll soon receive this (and later) preview updates over-the-air. If you’ve already enrolled your device, you’ll receive the update shortly, no action is needed on your part. You can also download and flash this update manually. Developer Preview 2 is intended for developers and not as a daily driver; this build is not yet optimized for performance and battery life.

The N Developer Preview is currently available for Nexus 6, Nexus 5X, Nexus 6P, Nexus 9, and Pixel C devices, as well as General Mobile 4G [Android One] devices. For Nexus Player, the update to Developer Preview 2 will follow the other devices by several days.

To build and test apps with Developer Preview 2, you need to use Android Studio 2.1 -- the same version that was required for Developer Preview 1. You’ll need to check for SDK components updates (including build tools and emulator system images) for Developer Preview 2 -- see here for details.

Thanks so much for all of your feedback so far. Please continue to share feedback, either in the N Developer Preview issue tracker or in the N preview community. The sooner we’re able to get your feedback, the more of of it we will be able to incorporate in the next release of Android.