Aug 19

Announcing updates to Google’s Internet of Things platform: Android Things and Weave

Posted by Wayne Piekarski,
Developer Advocate for IoT

The Internet of Things (IoT) will bring computing to a whole new range of
devices. Today we’re announcing two important updates to our IoT developer
platform to make it faster and easier for you to create these smart, connected
products.

We’re releasing a Developer Preview of Android Things, a comprehensive way to
build IoT products with the power of Android, one of the world’s most supported
operating systems. Now any Android developer can quickly build a smart device
using Android APIs and Google services, while staying highly secure with updates
direct from Google. We incorporated the feedback from Project Brillo to include
familiar tools such as Android Studio, the Android Software Development Kit
(SDK), Google Play Services, and Google Cloud Platform. And in the coming
months, we will provide Developer Preview updates to bring you the
infrastructure for securely pushing regular OS patches, security fixes, and your
own updates, as well as built-in Weave connectivity and more.

There are several turnkey hardware solutions available for you to get started
building real products with Android Things today, including Intel Edison, NXP
Pico, and Raspberry Pi 3. You can easily scale to large production runs with
custom designs of these solutions, while continuing to use the same Board
Support Package (BSP) from Google.

We are also updating the Weave platform to make it easier for all types of
devices to connect to the cloud and interact with services like the Google
Assistant. Device makers like Philips Hue and Samsung SmartThings already use
Weave, and several others like Belkin WeMo, LiFX, Honeywell, Wink, TP-Link, and
First Alert are implementing it. Weave provides all the cloud infrastructure, so
that developers can focus on building their products without investing in cloud
services. Weave also includes a Device SDK for supported microcontrollers and a
management console. The Weave Device SDK currently supports schemas for light
bulbs, smart plugs and switches, and thermostats. In the coming months we will
be adding support for additional device types, custom schemas/traits, and a
mobile application API for Android and iOS. Finally, we’re also working towards
merging Weave and Nest Weave to enable all classes of devices to connect with
each other in a secure and reliable way. So whether you started with Google
Weave or Nest Weave, there is a path forward in the ecosystem.

This is just the
beginning of the IoT ecosystem we want to build with you. To get started, check
out Google’s IoT developer site,
or go directly to the Android
Things, Weave, and Google Cloud Platform sites for
documentation and code samples. You can also join Google’s IoT Developers Community on Google+ to
get the latest updates and share and discuss ideas with other developers.


Android Developers Blog

Aug 18

Alternative input methods for Android TV


Posted by Benjamin Baxter, Developer Advocate and Bacon Connoisseur

Hero image displaying phones and tvs communicating to each other

All TVs have the same problem with keyboard input: It is very cumbersome to hunt and peck for each letter using a D-pad with a remote. And if you make a mistake, trying to correct it compounds the problem.

APIs like Smart Lock and Autofill, can ease user’s frustrations, but for certain types of input, like login, you need to collect complex input that is difficult for users using the on-screen keyboard.

With the Nearby Connections API, you can use a second screen to gather input from the user with less friction.

How Nearby Connections works

From the documentation:

“Nearby Connections is an offline peer-to-peer socket model for communication based on advertising and discovering devices in proximity.

Usage of the API falls into two phases: pre-connection, and post-connection.

In the pre-connection phase, Advertisers advertise themselves, while Discoverers discover nearby Advertisers and send connection requests. A connection request from a Discoverer to an Advertiser initiates a symmetric authentication flow that results in both sides independently accepting (or rejecting) the connection request.

After a connection request is accepted by both sides, the connection is established and the devices enter the post-connection phase, during which both sides can exchange data.”

In most cases the TV is the advertiser and the phone is the discoverer. In the example below, the assumed second device is a phone. The API and patterns described in this article are not limited to a phone. For example, a tablet could also be the second screen device.

The TV is the Advertiser and the phone is the Discoverer.

Login Example

There are many times when keyboard input is required. Authenticating users and collecting billing information (like zip codes and name on card) are common cases. This example handles a login flow that uses a second screen to see how Nearby Connections can help reduce friction.

1. The user opens your app on her TV and needs to login. You can show a screen of options similar to the setup flow for a new TV.

Android TV setup with prompt to continue on the user's phone.

2. After the user chooses to login with their phone, the TV should start advertising and send the user to the associated login app on their phone, which should start discovering.

There are a variety of solutions to open the app on the phone. As an example, Android TV’s setup flow has the user open the corresponding app on their mobile device. Initiating the hand-off is a more a UX concern than a technology concern.

Animation showing setup hand off from TV to phone.

3. The phone app should display the advertising TV and prompt the user to initiate the connection. After the (encrypted — see Security Considerations below for more on this) connection is established the TV can stop advertising and the phone can stop discovering.

Advertising/Discovery using Nearby Connections for hours on end can affect a device’s battery. While this is not usually an issue for a plugged-in TV, it can be for mobile devices, so be conscious about stopping advertising and discovery once they’re no longer needed.”

4. Next, the phone can start collecting the user’s input. Once the user enters their login information, the phone should send it to the TV in a BYTES payload over the secure connection.

5. When the TV receives the message it should send an ACK (using a BYTES payload) back to the phone to confirm delivery.

6. When the phone receives the ACK, it can safely close the connection.

The following diagram summarizes the sequence of events:

Sequence diagram of order of events to setup a connect and send a message.

UX considerations

Nearby Connections needs location permissions to be able to discover nearby devices. Be transparent with your users. Tell them why they need to grant the location permission on their phone.

Since the TV is advertising, it does not need location permissions.

Start advertising: The TV code

After the user chooses to login on the phone, the TV should start advertising. This is a very simple process with the Nearby API.

override fun onGuidedActionClicked(action: GuidedAction?) {
    super.onGuidedActionClicked(action)
    if( action == loginAction ) {
        // Update the UI so the user knows to check their phone
        navigationFlowCallback.navigateToConnectionDialog()
        doStartAdvertising(requireContext()) { payload ->
            handlePayload(payload)
        }
    }
}

When the user clicks a button, update the UI to tell them to look at their phone to continue. Be sure to offer a way to cancel the remote login and try manually with the cumbersome onscreen keyboard.

This example uses a GuidedStepFragment but the same UX pattern applies to whatever design you choose.

Advertising is straightforward. You need to supply a name, a service id (typically the package name), and a `ConnectionLifeCycleCallback`.

You also need to choose a strategy that both the TV and the phone use. Since it is possible that the users has multiple TVs (living room, bedroom, etc) the best strategy to use is P2P_CLUSTER.

Then start advertising. The onSuccessListener and onFailureListener tell you whether or not the device was able to start advertising, they do not indicate a device has been discovered.

fun doStartAdvertising(context: Context) {
    Nearby.getConnectionsClient(context).startAdvertising(
        context.getString(R.string.tv_name),
        context.packageName,
        connectionLifecycleCallback,
        AdvertisingOptions.Builder().setStrategy(Strategy.P2P_CLUSTER).build()
    )
    .addOnSuccessListener {
        Log.d(LoginStepFragment.TAG, "We are advertising!")
    }
    .addOnFailureListener {
        Log.d(LoginStepFragment.TAG, "We cannot start advertising.")
        Toast.makeText(
            context, "We cannot start advertising.", Toast.LENGTH_LONG)
                .show()
    }
}

The real magic happens in the `connectionLifecycleCallback` that is triggered when devices start to initiate a connection. The TV should accept the handshake from the phone (after performing the necessary authentication — see Security Considerations below for more) and supply a payload listener.

val connectionLifecycleCallback = object : ConnectionLifecycleCallback() {

    override fun onConnectionInitiated(
            endpointId: String,
            connectionInfo: ConnectionInfo
    ) {
        Log.d(TAG, "Connection initialized to endpoint: $  endpointId")
        // Make sure to authenticate using `connectionInfo.authenticationToken`
        // before accepting
        Nearby.getConnectionsClient(context)
            .acceptConnection(endpointId, payloadCallback)
    }

    override fun onConnectionResult(
        endpointId: String,
        connectionResolution: ConnectionResolution
    ) {
        Log.d(TAG, "Received result from connection: $  {connectionResolution.status.statusCode}")
        doStopAdvertising()
        when (connectionResolution.status.statusCode) {
            ConnectionsStatusCodes.STATUS_OK -> {
                Log.d(TAG, "Connected to endpoint: $  endpointId")
                otherDeviceEndpointId = endpointId
            }
            else -> {
                otherDeviceEndpointId = null
            }
        }
    }

    override fun onDisconnected(endpointId: String) {
        Log.d(TAG, "Disconnected from endpoint: $  endpointId")
        otherDeviceEndpointId = null
    }
}

The payloadCallback listens for the phone to send the login information needed. After receiving the login information, the connection is no longer needed. We go into more detail later in the Ending the Conversation section.

Discovering the big screen: The phone code

Nearby Connections does not require the user’s consent. However, the location permission must be granted in order for discovery with Nearby Connections to work its magic. (It uses BLE scanning under the covers.)

After opening the app on the phone, start by prompting the user for location permission if not already granted on devices running Marshmallow and higher.

Once the permission is granted, start discovering, confirm the connection, collect the credentials, and send a message to the TV app.

Discovering is as simple as advertising. You need a service id (typically the package name — this should be the same on the Discoverer and Advertiser for them to see each other), a name, and a `EndpointDiscoveryCallback`. Similar to the TV code, the flow is triggered by callbacks based on the connection status.

Nearby.getConnectionsClient(context).startDiscovery(
        context.packageName,
        mobileEndpointDiscoveryCallback,
        DiscoveryOptions.Builder().setStrategy(Strategy.P2P_CLUSTER).build()
        )
        .addOnSuccessListener {
            // We're discovering!
            Log.d(TAG, "We are discovering!")
        }
         .addOnFailureListener {
            // We were unable to start discovering.
            Log.d(TAG, "We cannot start discovering!")
        }

The Discoverer’s listeners are similar to the Advertiser’s success and failure listeners; they signal if the request to start discovery was successful or not.

Once you discover an advertiser, the `EndpointDiscoveryCallback` is triggered. You need to keep track of the other endpoint to know who to send the payload, e.g.: the user’s credentials, to later.

val mobileEndpointDiscoveryCallback = object : EndpointDiscoveryCallback() {
    override fun onEndpointFound(
        endpointId: String,
        discoveredEndpointInfo: DiscoveredEndpointInfo
    ) {
        // An endpoint was found!
        Log.d(TAG, "An endpoint was found, $  {discoveredEndpointInfo.endpointName}")
        Nearby.getConnectionsClient(context)
            .requestConnection(
                context.getString(R.string.phone_name),
                endpointId,
                connectionLifecycleCallback)
    }

    override fun onEndpointLost(endpointId: String) {
        // A previously discovered endpoint has gone away.
        Log.d(TAG, "An endpoint was lost, $  endpointId")
    }
}

One of the devices must initiate the connection. Since the Discoverer has a callback for endpoint discovery, it makes sense for the phone to request the connection to the TV.

The phone asks for a connection supplying a `connectionLifecycleCallback` which is symmetric to the callback in the TV code.

val connectionLifecycleCallback = object : ConnectionLifecycleCallback() {
    override fun onConnectionInitiated(
        endpointId: String,
        connectionInfo: ConnectionInfo
    ) {
        Log.d(TAG, "Connection initialized to endpoint: $  endpointId")
        // Make sure to authenticate using `connectionInfo.authenticationToken` before accepting
        Nearby.getConnectionsClient(context)
                .acceptConnection(endpointId, payloadCallback)
    }

    override fun onConnectionResult(
        endpointId: String,
        connectionResolution: ConnectionResolution
    ) {
        Log.d(TAG, "Connection result from endpoint: $  endpointId")
        when (connectionResolution.status.statusCode) {
            ConnectionsStatusCodes.STATUS_OK -> {
                Log.d(TAG, "Connected to endpoint: $  endpointId")
                otherDeviceEndpointId = endpointId
                waitingIndicator.visibility = View.GONE
                emailInput.editText?.isEnabled = true
                passwordInput.editText?.isEnabled = true

                Nearby.getConnectionsClient(this).stopDiscovery()
            }
            else -> {
                otherDeviceEndpointId = null
            }
        }
    }

    override fun onDisconnected(endpointId: String) {
        Log.d(TAG, "Disconnected from endpoint: $  endpointId")
        otherDeviceEndpointId = null
    }
}

Once the connection is established, stop discovery to avoid keeping this battery-intensive operation running longer than needed. The example stops discovery after the connection is established, but it is possible for a user to leave the activity before that happens. Be sure to stop the discovery/advertising in onStop() on both the TV and phone.


override fun onStop() {
    super.onStop()
    Nearby.getConnectionsClient(this).stopDiscovery()
}


Just like a TV app, when you accept the connection you supply a payload callback. The callback listens for messages from the TV app such as the ACK described above to clean up the connection.

After the devices are connected, the user can use the keyboard and send their authentication information to the TV by calling `sendPayload()`.

fun sendCreditials() {

    val email = emailInput.editText?.text.toString()
    val password = passwordInput.editText?.text.toString()

    val creds = "$  email:$  password"
    val payload = Payload.fromBytes(creds.toByteArray())
    Log.d(TAG, "sending payload: $  creds")
    if (otherDeviceEndpointId != null) {
        Nearby.getConnectionsClient(this)
                .sendPayload(otherDeviceEndpointId, payload)
    }
}

Ending the conversation

After the phone sends the payload to the TV (and the login is successful), there is no reason for the devices to remain connected. The TV can initiate the disconnection with a simple shutdown protocol.

The TV should send an ACK to the phone after it receives the credential payload.

val payloadCallback = object : PayloadCallback() {
    override fun onPayloadReceived(endpointId: String, payload: Payload) {
        if (payload.type == Payload.Type.BYTES) {
            payload.asBytes()?.let {
                val body = String(it)
                Log.d(TAG, "A payload was received: $  body")
                // Validate that this payload contains the login credentials, and process them.

                val ack = Payload.fromBytes(ACK_PAYLOAD.toByteArray())
                Nearby.getConnectionsClient(context).sendPayload(endpointId, ack)
            }
        }
    }

    override fun onPayloadTransferUpdate(
        endpointId: String,
        update: PayloadTransferUpdate
    ) {    }
}

The phone should have a `PayloadCallback` that initiates a disconnection in response to the ACK. This is also a good time to reset the UI to show an authenticated state.

private val payloadCallback = object : PayloadCallback() {
    override fun onPayloadReceived(endpointId: String, payload: Payload) {
        if (payload.type == Payload.Type.BYTES) {
            payload.asBytes()?.let {
                val body = String(it)
                Log.d(TAG, "A payload was received: $  body")

                if (body == ACK_PAYLOAD) {
                    waitingIndicator.visibility = View.VISIBLE
                    waitingIndicator.text = getString(R.string.login_successful)
                    emailInput.editText?.isEnabled = false
                    passwordInput.editText?.isEnabled = false
                    loginButton.isEnabled = false

                    Nearby.getConnectionsClient(this@MainActivity)
                        .disconnectFromEndpoint(endpointId)
                }
            }
        }
    }

    override fun onPayloadTransferUpdate(
        endpointId: String,
        update: PayloadTransferUpdate
    ) {    }
}

Security considerations

For security (especially since we’re sending over sensitive information like login credentials), it’s strongly recommended that you authenticate the connection by showing a code and having the user confirm that the two devices being connected are the intended ones — without this, the connection established by Nearby Connection is encrypted but not authenticated, and that’s susceptible to Man-In-The-Middle attacks. The documentation goes into greater detail on how to authenticate a connection.

Let the user accept the connection by displaying a confirmation code on both devices.

Does your app offer a second screen experience?

There are many times when a user needs to supply input to a TV app. The Nearby API provides a way to offload the hardships of an onscreen-dpad-driven keyboard to an easy and familiar phone keyboard.

What use cases do you have where a second screen would simplify your user’s life? Leave a comment or send me (@benjamintravels) or Varun (@varunkapoor, Team Lead for Nearby Connections) a tweet to continue the discussion.


Android Developers Blog

Aug 18

Android Wear 2.0 for China – Developer Preview

Posted by Hoi Lam, Developer Advocate

Today at Google
Developer Day China, we are happy to announce a developer preview
of Android Wear 2.0 for developers creating apps for China. Android Wear 2.0 is
the biggest update since our partners launched their first devices in China last
year.

We’re making a Developer Preview available today and plan to release additional
updates in the coming months. Please send us your feedback by filing bugs or posting in our Android Wear
Developers community.

Developing for the Chinese Market

With Android Wear 2.0, apps can access the internet directly on Android Wear
devices. As a result, for the majority of apps, having a companion phone
application is no longer necessary. This means that most developers creating
apps for Android Wear 2.0 may no longer need to import the Google Play services
library.

There are two situations where developers will need to import Google Play
services for China:

  • Apps that require direct interaction with the paired mobile
    device
    – some experiences require Android Wear to connect directly to a
    paired phone. In this case, the Data
    Layer API introduced in Android Wear 1.0 will continue to function.

  • New FusedLocationProvider
    for China
    – we have added location detection to the SDK for Chinese
    developers. With the user’s permission, your app can receive location updates
    via the FusedLocationProvider.

You can find more details about how to import the China compatible version of
Google Play services library here.

Product testing for Android Wear 2.0 for China

The Android Wear 2.0 Developer Preview includes an updated SDK with tools, and
system images for testing using the Huawei Watch.

To get started, follow these steps:

  • Update to Android Studio v2.1.1 or later
  • Visit the Android Wear 2.0
    Developer Preview site for downloads and documentation

  • Download
    the device system images

  • Test your app with your supported device

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!

Android Wear 2.0 中国版 – 开发者预览版

编辑: 林海泉, Android Wear 开发平台负责人

今天在上海举办的Google
开发者大会上,我们正式宣布了一款专门针对中国市场的Android Wear 2.0 开发者预览版。Android Wear
2.0系统,将是自我们的合作伙伴首次发布手表产品以来最重大的更新。

开发者预览版已于今日正式上线。与此同时,我们也计划在未来的几个月内持续进行更新。请您将您遇到的问题在此提交反馈,或者在我们的Android
Wear开发者论坛发表意见。

为中国市场开发应用

在Android Wear 2.0系统中,应用可以由Android
Wear手表直接连接至互联网。因此,对于大多数应用来说,手机端的伴侣应用也就变得不再必要。这也意味着,多数为Android Wear
2.0开发应用的开发者将不再需要引用Google Play services客户端库。

目前,在两个情况下开发者仍然需要引入Google Play Services客户端库来为中国市场开发应用:

  • 需要与手机直接进行通信的应用 – 有一些用例需要Android
    Wear手表与已配对手机直接连接。在这种情况下,Android Wear 1.0中引入的Data
    Layer API仍然可以继续使用。

  • 使用 FusedLocationProvider
    - 我们在最新的中国版SDK中加入了定位的支持。在用户的许可下,您的应用可以通过FusedLocationProvider来接收定位更新。

您可以在这里找到关于如何引入与中国版兼容的Google
Play service的更多信息。

Android Wear 2.0 中国版产品测试

Android Wear 2.0 开发者预览版包括最新的SDK套件,手表测试系统镜像(基于华为手表)。

情按照以下步骤进行测试:

  • 更新到Android Studio至v2.1.1以上版本
  • 访问 Android Wear
    2.0 开发者预览版,那里的文件下载与文档下载部分

  • 下载手表系统镜像
  • 在手表上测试您的应用

开发反馈

我们会根据您的反馈在未来的几个月中更新开发者预览版。您给我们的反馈越早,我们将会在最终的发布版本中包含更多针对您的反馈的解决方案。敬请期待!


Android Developers Blog

Aug 17

Android Wear 2.0 Developer Preview 4: Authentication, In-App Billing, and more

Posted by Hoi Lam, Developer
Advocate

A key part of Android Wear 2.0 is letting
watch apps work as standalone apps, so users can respond to messages, track
their fitness, and use their favorite apps, even when their phone isn’t around.
Developer Preview 4 includes a number of new APIs that will help you build more
powerful standalone apps.

Seamless authentication

To make authentication a seamless experience for both Android phone and iPhone
users, we have created new APIs for OAuth
and added support for one-click Google Sign-in. With the OAuth API for
Android Wear, users can tap a button on the watch that opens an authentication
screen on the phone. Your watch app can then authenticate with your server side
APIs directly. With Google Sign-In, it’s even easier. All the user needs to do
is select which account they want to authenticate with and they are done.

In-app billing

In addition to paid apps, we have added in-app
billing support, to give you another way to monetize your Android Wear app
or watch face. Users can authorize purchases quickly and easily on the watch
through a 4-digit Google Account PIN. Whether it’s new levels in a game or new
styles on a watch face, if you can build it, users can buy it.

Cross-device promotion

What if your watch app doesn’t work standalone? Or what if it offers a better
user experience when both the watch and phone apps are installed? We’ve been
listening carefully to your feedback, and we’ve added two
new APIs (PlayStoreAvailability and RemoteIntent)
to help you navigate users to the Play Store on a paired device so they can
more easily install your app. Developers can also open custom URLs on the phone
from the watch via the new RemoteIntent API; no phone app or data
layer is required.

// Check Play Store is available
int playStoreAvailabilityOnPhone =
    PlayStoreAvailability.getPlayStoreAvailabilityOnPhone(getApplicationContext());

if (playStoreAvailabilityOnPhone == PlayStoreAvailability.PLAY_STORE_ON_PHONE_AVAILABLE) {
    // To launch a web URL, setData to Uri.parse("https://g.co/wearpreview")
    Intent intent =
        new Intent(Intent.ACTION_VIEW)
            .addCategory(Intent.CATEGORY_BROWSABLE)
            .setData(Uri.parse("market://details?id=com.google.android.wearable.app"));
    // mResultReceiver is optional; it can be null.
    RemoteIntent.startRemoteActivity(this, intent, mResultReceiver);
}

Swipe-to-dismiss is back

Many of you have given us the feedback that the swipe-to-dismiss gesture from
Android Wear 1.0 is an intuitive time-saver. We agree, and have reverted back to
the previous behavior with this developer preview release. To support
swipe-to-dismiss in this release, we’ve made the following platform and API
changes:

  • Activities now automatically support swipe-to-dismiss.
    Swiping an activity from left to right will result in it being dismissed and the
    app will navigate down the back stack.

  • New Fragment and View support. Developers can wrap the
    containing views of a Fragment or Views in general in the new
    SwipeDismissFrameLayout to implement custom actions such as going
    down the back stack when the user swipes rather than exiting the activity.

  • Hardware button now maps to “power” instead of “back” which
    means it can no longer be intercepted by apps.

Additional details are available under the behavior
changes section of the Android Wear Preview site.

Compatibility with Android Wear 1.0 apps

Android Wear apps packaged using the legacy embedded app mechanism can now be
delivered to Android Wear 2.0 watches. When a user installs a phone app that
also contains an embedded Android Wear app, the user will be prompted to install
the embedded app via a notification. If they choose not to install the embedded
app at that moment, they can find it in the Play Store on Android Wear under a
special section called “Apps you’ve used”.

Despite support for the existing mechanism, there are significant benefits for
apps that transition to the multi-APK
delivery mechanism. Multi-APK allows the app to be searchable in the Play
Store on Android Wear, to be eligible for merchandising on the homepage, and to
be remotely installed from the web to the watch. As a result, we strongly
recommend that developers move to multi-APK.

More additions in Developer Preview 4

  • Action
    and Navigation Drawers: An enhancement to peeking behavior
    allows the user to take action without scrolling all the way to the top or
    bottom of a list. Developers can further fine-tune drawer peeking behavior
    through new APIs, such as setShouldPeekOnScrollDown for the action
    drawer.

  • WearableRecyclerView:
    The curved layout is now opt-in, and with this, the WearableRecyclerView is now
    a drop-in replacement for RecyclerView.

  • Burn-in
    protection icon for complications: Complication data providers can now
    provide icons for use on screens susceptible to burn-in. These burn-in-safe
    icons are normally the outline of the icon in interactive mode. Previously,
    watch faces may have chosen not to display the icon at all in ambient mode to
    prevent screen burn-in.

Feedback welcome!

Thanks for all your terrific feedback on Android Wear 2.0. Check out g.co/wearpreview for the latest builds and
documentation, keep the feedback coming by filing bugs or posting in our Android Wear
Developers community, and stay tuned for Android Wear Developer Preview 5!


Android Developers Blog

Aug 17

Streaming support spec for hearing aids on Android


Posted by Seang Chau, Vice President, Engineering

According to the World Health Organization1, around 466 million people worldwide have disabling hearing loss. This number is expected to increase to 900 million people by the year 2050. Google is working with GN Hearing to create a new open specification for hearing aid streaming support on future versions of Android. Users with hearing loss will be able to connect, pair, and monitor their hearing aids so they can hear their phones loudly and clearly.

Hearing aid users expect a high quality, low latency experience with minimal impact on phone and hearing aid battery life. We’ve published a new hearing aid spec for Android smartphones: Audio Streaming for Hearing Aids (ASHA) on Bluetooth Low Energy Connection-Oriented Channels. ASHA is designed to have a minimal impact on battery life with low-latency while maintaining a high quality audio experience for users who rely on hearing aids. We look forward to continually evolving the spec to even better meet the needs of our users.

The spec details the pairing and connectivity, network topology, system architecture, and system requirements for implementing hearing aids using low energy connection-oriented channels. Any hearing aid manufacturer can now build native hearing aid support for Android.

The protocol specification is available here.


Android Developers Blog

Aug 16

Android Wear 2.0 Developer Preview 4: Authentication, In-App Billing, and more

Posted by Hoi Lam, Developer
Advocate

A key part of Android Wear 2.0 is letting
watch apps work as standalone apps, so users can respond to messages, track
their fitness, and use their favorite apps, even when their phone isn’t around.
Developer Preview 4 includes a number of new APIs that will help you build more
powerful standalone apps.

Seamless authentication

To make authentication a seamless experience for both Android phone and iPhone
users, we have created new APIs for OAuth
and added support for one-click Google Sign-in. With the OAuth API for
Android Wear, users can tap a button on the watch that opens an authentication
screen on the phone. Your watch app can then authenticate with your server side
APIs directly. With Google Sign-In, it’s even easier. All the user needs to do
is select which account they want to authenticate with and they are done.

In-app billing

In addition to paid apps, we have added in-app
billing support, to give you another way to monetize your Android Wear app
or watch face. Users can authorize purchases quickly and easily on the watch
through a 4-digit Google Account PIN. Whether it’s new levels in a game or new
styles on a watch face, if you can build it, users can buy it.

Cross-device promotion

What if your watch app doesn’t work standalone? Or what if it offers a better
user experience when both the watch and phone apps are installed? We’ve been
listening carefully to your feedback, and we’ve added two
new APIs (PlayStoreAvailability and RemoteIntent)
to help you navigate users to the Play Store on a paired device so they can
more easily install your app. Developers can also open custom URLs on the phone
from the watch via the new RemoteIntent API; no phone app or data
layer is required.

// Check Play Store is available
int playStoreAvailabilityOnPhone =
    PlayStoreAvailability.getPlayStoreAvailabilityOnPhone(getApplicationContext());

if (playStoreAvailabilityOnPhone == PlayStoreAvailability.PLAY_STORE_ON_PHONE_AVAILABLE) {
    // To launch a web URL, setData to Uri.parse("https://g.co/wearpreview")
    Intent intent =
        new Intent(Intent.ACTION_VIEW)
            .addCategory(Intent.CATEGORY_BROWSABLE)
            .setData(Uri.parse("market://details?id=com.google.android.wearable.app"));
    // mResultReceiver is optional; it can be null.
    RemoteIntent.startRemoteActivity(this, intent, mResultReceiver);
}

Swipe-to-dismiss is back

Many of you have given us the feedback that the swipe-to-dismiss gesture from
Android Wear 1.0 is an intuitive time-saver. We agree, and have reverted back to
the previous behavior with this developer preview release. To support
swipe-to-dismiss in this release, we’ve made the following platform and API
changes:

  • Activities now automatically support swipe-to-dismiss.
    Swiping an activity from left to right will result in it being dismissed and the
    app will navigate down the back stack.

  • New Fragment and View support. Developers can wrap the
    containing views of a Fragment or Views in general in the new
    SwipeDismissFrameLayout to implement custom actions such as going
    down the back stack when the user swipes rather than exiting the activity.

  • Hardware button now maps to “power” instead of “back” which
    means it can no longer be intercepted by apps.

Additional details are available under the behavior
changes section of the Android Wear Preview site.

Compatibility with Android Wear 1.0 apps

Android Wear apps packaged using the legacy embedded app mechanism can now be
delivered to Android Wear 2.0 watches. When a user installs a phone app that
also contains an embedded Android Wear app, the user will be prompted to install
the embedded app via a notification. If they choose not to install the embedded
app at that moment, they can find it in the Play Store on Android Wear under a
special section called “Apps you’ve used”.

Despite support for the existing mechanism, there are significant benefits for
apps that transition to the multi-APK
delivery mechanism. Multi-APK allows the app to be searchable in the Play
Store on Android Wear, to be eligible for merchandising on the homepage, and to
be remotely installed from the web to the watch. As a result, we strongly
recommend that developers move to multi-APK.

More additions in Developer Preview 4

  • Action
    and Navigation Drawers: An enhancement to peeking behavior
    allows the user to take action without scrolling all the way to the top or
    bottom of a list. Developers can further fine-tune drawer peeking behavior
    through new APIs, such as setShouldPeekOnScrollDown for the action
    drawer.

  • WearableRecyclerView:
    The curved layout is now opt-in, and with this, the WearableRecyclerView is now
    a drop-in replacement for RecyclerView.

  • Burn-in
    protection icon for complications: Complication data providers can now
    provide icons for use on screens susceptible to burn-in. These burn-in-safe
    icons are normally the outline of the icon in interactive mode. Previously,
    watch faces may have chosen not to display the icon at all in ambient mode to
    prevent screen burn-in.

Feedback welcome!

Thanks for all your terrific feedback on Android Wear 2.0. Check out g.co/wearpreview for the latest builds and
documentation, keep the feedback coming by filing bugs or posting in our Android Wear
Developers community, and stay tuned for Android Wear Developer Preview 5!


Android Developers Blog

Aug 16

Develop a sweet spot for Marshmallow: Official Android 6.0 SDK & Final M Preview

By Jamal Eason, Product Manager, Android

Android 6.0 Marshmallow

Whether you like them straight out of the bag, roasted to a golden brown exterior with a molten center, or in fluff form, who doesn’t like marshmallows? We definitely like them! Since the launch of the M Developer Preview at Google I/O in May, we’ve enjoyed all of your participation and feedback. Today with the final Developer Preview update, we’re introducing the official Android 6.0 SDK and opening Google Play for publishing your apps that target the new API level 23 in Android Marshmallow.

Get your apps ready for Android Marshmallow

The final Android 6.0 SDK is now available to download via the SDK Manager in Android Studio. With the Android 6.0 SDK you have access to the final Android APIs and the latest build tools so that you can target API 23. Once you have downloaded the Android 6.0 SDK into Android Studio, update your app project compileSdkVersion to 23 and you are ready to test your app with the new platform. You can also update your app to targetSdkVersion to 23 test out API 23 specific features like auto-backup and app permissions.

Along with the Android 6.0 SDK, we also updated the Android Support Library to v23. The new Android Support library makes it easier to integrate many of the new platform APIs, such as permissions and fingerprint support, in a backwards-compatible manner. This release contains a number of new support libraries including: customtabs, percent, recommendation, preference-v7, preference-v14, and preference-leanback-v17.

Check your App Permissions

Along with the new platform features like fingerprint support and Doze power saving mode, Android Marshmallow features a new permissions model that streamlines the app install and update process. To give users this flexibility and to make sure your app behaves as expected when an Android Marshmallow user disables a specific permission, it’s important that you update your app to target API 23, and test the app thoroughly with Android Marshmallow users.

How to Get the Update

The Android emulator system images and developer preview system images have been updated for supported Nexus devices (Nexus 5, Nexus 6, Nexus 9 & Nexus Player) to help with your testing. You can download the device system images from the developer preview site. Also, similar to the previous developer update, supported Nexus devices will receive an Over-the-Air (OTA) update over the next couple days.

Although the Android 6.0 SDK is final, the devices system images are still developer preview versions. The preview images are near final but they are not intended for consumer use. Remember that when Android 6.0 Marshmallow launches to the public later this fall, you’ll need to manually re-flash your device to a factory image to continue to receive consumer OTA updates for your Nexus device.

What is New

Compared to the previous developer preview update, you will find this final API update fairly incremental. You can check out all the API differences here, but a few of the changes since the last developer update include:

  • Android Platform Change:

    • Final Permissions User Interface — we updated the permissions user interface and enhanced some of the permissions behavior.
  • API Change:

    • Updates to the Fingerprint API — which enables better error reporting, better fingerprint enrollment experience, plus enumeration support for greater reliability.

Upload your Android Marshmallow apps to Google Play

Google Play is now ready to accept your API 23 apps via the Google Play Developer Console on all release channels (Alpha, Beta & Production). At the consumer launch this fall, the Google Play store will also be updated so that the app install and update process supports the new permissions model for apps using API 23.

To make sure that your updated app runs well on Android Marshmallow and older versions, we recommend that you use Google Play’s newly improved beta testing feature to get early feedback, then do a staged rollout as you release the new version to all users.


Android Developers Blog

Aug 14

Google releases source for Google I/O 2018 for Android


Posted by Shailen Tuli, DPE

Today we’re releasing the source code for the official Google I/O 2018 for Android app.

The 2018 version constitutes a comprehensive rewrite of the app. For many years, the app has used a ContentProvider + SyncAdapter architecture. This year, we rewrote the app using Architecture Components and brought the code in sync with the Android team’s current recommendations for building modern apps.

Architecture

We followed the recommendations laid out in the Guide to App Architecture for writing modular, testable and maintainable code when deciding on the architecture for the app. We kept logic away from Activities and Fragments and moved it to ViewModels. We observed data using LiveData and used the Data Binding Library to bind UI components in layouts to the app’s data sources.

The overall architecture of the app can be summarized in this diagram:

We used a Repository layer for handling data operations. IOSched’s data comes from a few different sources — user data is stored in Cloud Firestore (either remotely or in a local cache for offline use), user preferences and settings are stored in SharedPreferences, conference data is stored remotely and is fetched and stored in memory for the app to use — and the repository modules are responsible for handling all data operations and abstracting the data sources from the rest of the app. If we ever wanted to swap out the Firestore backend for a different data source in the future, our architecture allows us to do so in a clean way.

We implemented a lightweight domain layer, which sits between the data layer and the presentation layer, and handles discrete pieces of business logic off the UI thread. Examples.

We used Dagger2 for dependency injection and we heavily relied on dagger-android to abstract away boilerplate code.

We used Espresso for basic instrumentation tests and JUnit and Mockito for unit testing.

Firebase

The use of Firebase technologies has grown in the app as the Firebase platform has matured. The 2018 version uses the following Firebase components:

  • Cloud Firestore is our source for all user data (events starred or reserved by a user). Firestore gave us automatic sync and also seamlessly managed offline functionality for us.
  • Firebase Cloud Functions allowed us to run backend code. The reservations feature heavily depended on Functions checking a user’s status (only attendees were allowed to make reservations), checking space availability and persisting reservation status in Firestore.
  • Firebase Cloud Messaging let us inform the app about changes to conference data on our server. Conference data is mostly static, but it does change from time to time, especially after the keynote. The app has traditionally used a ping-and-fetch model when working with conference data, and we retained that usage this year.
  • Remote Config helped us manage in-app constants. In previous years, we had found ourselves unable to inform users when data not directly related to the conference schedule — WiFi information, conference shuttle schedule, etc. — changed unexpectedly. Remote Config helped us update such values in a lightweight manner.

Kotlin

We made an early decision to rewrite the app from scratch to bring it in line with modern Android architecture. Using Kotlin for the rewrite was an easy choice: we loved Kotlin’s expressive, concise, and powerful syntax; we found that Kotlin’s support for safety features including nullability and immutability made our code more resilient; and we leveraged the enhanced functionality provided by Android Ktx extensions.

Material Design

At I/O 2018, the Material Design team announced Material Theming, giving apps much greater ability to customize Material Design to bring more of their product’s brand. As we launched the app before Material Theming, we couldn’t use all of the new components but we managed to sneak a couple in like the new Bottom App Bar with inset Floating Action Button and we were able to incorporate a lot of the conference’s branding elements.

Future plans

The rewrite of the app brings the code in sync with Android’s opinionated recommendations about building apps, and it resulted in a cleaner, more maintainable codebase. We’ll continue working on the app, incorporating JetPack components as they become available and finding opportunities to showcase platform features that are good fits for the app. Developers can follow changes to the code on GitHub.


Android Developers Blog

Aug 09

Watch sessions from the Playtime 2016 events to learn how to succeed on Android & Google Play

Posted by Patricia Correa, Head of Developer Marketing, Google Play

We’re wrapping up our annual global Playtime series of events with a last stop in Tokyo, Japan. This year Google Play hosted events in 10 cities: London, Paris, Berlin, Hong Kong, Singapore, Gurgaon, San Francisco, Sao Paulo, Seoul and Tokyo. We met with app and game developers from around the world to discuss how to build successful businesses on Google Play, share experiences, give feedback, collaborate, and get inspired.

You can now watch some of the best Playtime sessions on our Android Developers YouTube Channel, as listed below. The playlist opens with a video that celebrates collaboration.


Keynote

What’s next for Google Play

Learn how we’re helping users discover apps in the right context, creating new
ways to engage with users beyond the install, and powering innovative
experiences on emerging platforms like virtual reality, wearables, and auto.

Develop and launch apps & games

Android
development in 2016

Android development is more powerful and efficient than ever before. Android
Studio brings you speed, smarts, and support for Android Nougat. The broad range
of cross-platform tools on Firecase can improve your app on Android and beyond.
Material Design and Vulkan continue to improve the user experience and increase
engagement.

Daydream
& Tango

Daydream View is a VR headset and controller by Google that lets people explore
new worlds, or play games that put them at the center of action. Learn how we’re
helping users discover apps in the right context and powering new experiences
with Daydream and Tango.

Fireside
chat – Wayfair & Pokémon GO on augmented reality

Augmented reality engages and delights people everywhere. In this fireside chat,
online furniture seller Wayfair and Niantic’s Pokémon
GO share their experiences with AR and discuss how other developers can make
the most of the platform.

Building
for billions, featuring best practices from Maliyo Games

Learn how to create apps and games for emerging markets, which are expected to
drive 80% of global smartphone growth by 2020, by recognizing the key challenges
and designing the right app experiences to overcome them.

At minute 16:41, hear tips from Hugo Obi, co-founder of Nigerian games developer
Maliyo.

Launch
smart on Google Play

Set your app up for success using experimentation and iteration. Learn best
practices for soft launching and adapting your app for different markets and
device types.

Apps

Sustainable
growth solves most problems for apps, featuring best practices from
SoundCloud &
Peak

Planning and executing a great growth strategy involves a complex set of choices
and mastery of many tools. In this session we discuss topics including key
business objectives, tools, and techniques to help you solve the growth puzzle
with our partner, SoundCloud.

Also, check out some growth
best practices from Peak.

Creating
sustainable user growth for startups, by Greylock

User growth isn’t just about growing the number of users you have. The key to
sustainability is creating and delivering core product value. In this session,
VC Greylock discusses how to identify your core action to focus on and shows you
how to use these insights to optimize your app for long term growth.

App
engagement is the new black, featuring best practices from Lifesum

As the app marketplace becomes more competitive, developer success depends on
retaining users in apps they love. Find out which Google tools and features can
help you analyze your users’ behaviors, improve engagement and retention in your
app and hear insights from others developers including Lifesum.

Predicting
lifetime value in the apps world

Deepdive into lifetime value models and predictive analytics in the apps ecosystem.
Tactics to get the most out of identified segments and how to upgrade their
behaviors to minimize churn.

Subscriptions
update

Learn about Google’s efforts to enable users, around the world, to seamlessly
and safely pay for content. This session provides updates on Google Play billing
and recent enhancements to our subscriptions platform.

Games

One
game fits all, featuring best practices from Space Ape Games

Customize your game’s experience for different users by targeting them with lifetime value
models and predictive analytics. Hear how these concepts are applied by
Space Ape Games to improve retention and monetization of their titles.

Promoting
your game and growing your user base, featuring best practices from Seriously

Learn how to use Google’s latest tools, like Firebase, for benchmarking,
acquiring users and measuring your activities. Also, hear game
developer Seriously share their latest insights and strategies on YouTube
influencer campaigns.

Creating
long-term retention, loyalty and value with engaging LiveOps events, featuring
best practices from Kabam &
Creative Mobile

Learn how successful developers keep their games fresh and engaging with Live
Operations. In this talk, the LiveOps expert on Marvel: Contest of Champions
discusses tips about the art and science of running an engaging LiveOps event.

Also check out the tips and best
practices to run successful LiveOps from games developer Creative Mobile.

Panel
- Play fair: Maintaining a level playing field in your game, featuring Space Ape
Games and Kongregate

Ensuring that your game is fair is critical to success. Find out how game
developers are achieving this and some ways Google Play can help.

Families

Why
you need to build for families

Family-based households with children have higher tablet and smartphone
ownership rates than the general population. These families are more likely to
make purchases on their mobile devices and play games. Learn about how parents
choose what to download and buy, and how you can prepare for maximum conversion.

Two
keys to growth: user acquisition & app engagement, by Cartoon Network

Hear how Cartoon Network leverages their network to cross-promote new titles,
acquire new users and keep them engaged through immersive experiences.

Go
global: Getting ready for the emerging markets revolution, by
Papumba

Papumba has a clear vision to grow a global business. Hear how they work with
experts to adapt their games to local markets and leverage Google Play’s
developer tools to find success around the world.

Optimizing
for a post install world

You’ve spent time and resources getting users to download your apps, but what
happens after the install? Learn how to minimize churn and keep families engaged
with your content long term.

Monetization
best practices on freemium, by 01 Digital

Learn how 01 Digital uses In-App-Purchases (IAP) to effectively monetize their
apps while maintaining a safe environment for families.

Building
a subscription business that appeals to parents, by PlayKids

PlayKids has been at the forefront of the subscription business model since
their inception. See how they best serve their subscribers by refreshing their
content, expanding their offerings and investing in new verticals.




How useful did you find this blogpost?


Android Developers Blog

Aug 08

Android Pie SDK is now more Kotlin-friendly


Posted by James Lau, Product Manager (@jmslau)

When using the Java programming language, one of the most common pitfalls is trying to access a member of a null reference, causing a NullPointerException to be thrown. Kotlin offers protection against this by baking nullable and non-nullable types into the type system. This helps eliminate NullPointerExceptions from your code and improve your app’s overall quality. When Kotlin code is calling into APIs written in the Java programming language, it relies on nullability annotations in those APIs to determine the nullability of each parameter and the return type. Unannotated parameters and return types are treated as platform types, which weakens the null-safety guarantee of Kotlin.

As part of yesterday’s Android 9 announcement, we have also released a new Android SDK that contains nullability annotations for some of the most frequently used APIs. This will preserve the null-safety guarantee when your Kotlin code is calling into any annotated APIs in the SDK. Even if you are using the Java programming language, you can still benefit from these annotations by using Android Studio to catch nullability contract violations.

Not a breaking change

Normally, nullability contract violations in Kotlin result in compilation errors. But to ensure the newly annotated APIs are compatible with your existing code, we are using an internal mechanism provided by the Kotlin compiler team to mark the APIs as recently annotated. Recently annotated APIs will result only in warnings instead of errors from the Kotlin compiler. You will need to use Kotlin 1.2.60 or later.

Our plan is to have newly added nullability annotations produce warnings only, and increase the severity level to errors starting in the following year’s Android SDK. The goal is to provide you with sufficient time to update your code.

How to use the “Kotlin-friendly” SDK

To get started, go to Tools > SDK Manager in Android Studio. Select Android SDK on the left menu, and make sure the SDK Platforms tab is open.

Use SDK Manager in Android Studio to install SDK for API Level 28 Revision 6

Check Android 8.+ (P) and click OK. This will install the Android SDK Platform 28 revision 6 if it is not already installed. After that, set your project’s compile SDK version to API 28 to start using the new Android Pie SDK with nullability annotations.

Use the Project Structure Dialog to change your project’s Compile Sdk Version to API 28

You may also need to update your Kotlin plugin in Android Studio if it’s not already up-to-date. Make sure your Kotlin plugin version is 1.2.60 or later by going to Tools > Kotlin > Configure Kotlin Plugin Updates.

Once it’s set up, your builds will start showing warnings if you have any code that violates nullability contracts in the Android SDK. An example of such a warning is shown below.

Sample warning from the Kotlin compiler when code violates a
recently added nullability contract in the Android SDK.

You will also start seeing warnings in Android Studio’s code editor if you call an Android API with the incorrect nullability. An example is shown below.

Android Studio warning about passing a null reference to a parameter
annotated as a recently non-null type in the android.graphics.Path API.

Leveraging nullability annotations from the Java programming language

You can benefit from the new nullability annotations even if your code is in the Java programming language. By default, Android Studio will highlight any nullability contract violations with a warning, like the one below:

Android Studio showing a warning about nullability contract violation
in code written in the Java programming language

To ensure that you have this inspection enabled, you can go to the IDE’s settings page and search for “Constant conditions & exceptions” inspection and make sure that item is checked.

Use the Inspections page under Settings to ensure the Constant conditions & exceptions code inspection is enabled.

If you are using the Java programming language, nullability contract violations will not produce any compiler warning or error. Only the in-IDE code inspections are available to flag these issues.

You can also run code inspections across your entire project and see the aggregated results. Click on Analyze > Inspect Code… to start.

What’s Next

The Android SDK API surface is very large, and we have only annotated a small percentage of the APIs so far – there is still lots of work remaining. Over the next several Android SDK releases, we will continue to add nullability annotations to the existing Android APIs, as well as making sure new APIs are annotated.

With the “Kotlin-friendly” Android SDK, the nullability annotations in AndroidX (part of the Jetpack family), and Android KTX, we are continuing to improve the Android APIs for developers using Kotlin. If you have not yet tried Kotlin, we encourage you to try it. Not only can Kotlin make your code more concise, it can also improve the stability of your apps.

Happy Kotlin-ing!


Android Developers Blog