28 Apr 2016

feedAndroid Developers Blog

Enhancing App Security on Google Play

Posted by Eric Davis, Android Security Team

We're constantly investing in new tools and services to help developers build secure Android applications. This includes the application sandbox and Security APIs in the platform, Security APIs in Google Play Services, and even open source testing tools. Last year, Google Play also helped developers enhance the security of their applications by looking directly at the code they've written and offering suggestions for improvements.

The Google Play App Security Improvement Program is the first of its kind. It has two core components: We provide developers with security tips to help them build more secure apps, and we help developers identify potential security enhancements when uploaded to Google Play. This week, to help educate developers, Kristian Monsen, one of our engineers, gave a presentation about security best practices at the Samsung Developer Conference. And in 2015, we worked with developers to improve the security of over 100,000 apps through the program.

How it works

Before any app is accepted into Google Play, it is scanned for safety and security, including potential security issues. We also continuously re-scan the over one million apps in Google Play for additional threats.

If your app is flagged for a potential security issue, you will be notified immediately to help you quickly address the issue and help keep your users safe. We'll deliver alerts to you using both email and the Google Play Developer Console, with links to a support page with details about how to improve the app.


Typically, these notifications will include a timeline for delivering the improvement to users as quickly as possible. Applications may be required to make security improvements before any other app updates can be be published.

You can confirm that you've fully addressed the issue by uploading the new version of your app to the Google Play Developer Console. Be sure to increment the version number of the fixed app. After a few hours, check the Developer Console for the security alert; if it's no longer there, you're all set!

The success of this program rests on our partnership with you-the developers of apps on Google Play-and the security community. We're all responsible for providing safe, secure apps to our users. For feedback or questions, please reach out to us through the Google Play Developer Help Center. To report potential security issues in apps, please reach out to us at security+asi@android.com.

28 Apr 2016 9:08pm GMT

feedAndroid News, Rumours, and Updates

HP’s premium Chromebook 13 is a breath of fresh (and affordable) air

Whereas the Pixel from Google is premium and pricey, HP's new Chromebook 13 is premium and affordable. The Chromebook 13 has an all-metal design measuring 12.9mm thin, boasts a 13.3-inch Quad HD+ display, and packs an Intel Core M processor. All of these impressive features and much more are available in a Chrome OS-powered device that costs […]


Come comment on this article: HP's premium Chromebook 13 is a breath of fresh (and affordable) air

Visit TalkAndroid

28 Apr 2016 5:05pm GMT

Triby is the first third-party Alexa-enabled speaker

For those of you who don't know, Amazon has built-up a technology called Alexa Voice Service (AVS). This is what provides the functionality of an Amazon Echo speaker. Amazon recently opened AVS to third-parties, letting them to create their own Alex-equipped speakers. Triby is the first one, and it's now available on Amazon. Triby is an Alexa-enabled […]


Come comment on this article: Triby is the first third-party Alexa-enabled speaker

Visit TalkAndroid

28 Apr 2016 4:34pm GMT

Talk Android Podcast: Episode 4

Listen to the fourth episode of the Talk Android Podcast. In Episode 4 (4/28/16), we cover the following topics: Nexus 9 vanishes from the Google Store HTC's Nexus devices this year are going by M1 and S1, likely Marlin and Sailfish Fenis down! Third-party Twitter app hits 100,000 token limit Google introduces new MODE bands for Android Wear […]


Come comment on this article: Talk Android Podcast: Episode 4

Visit TalkAndroid

28 Apr 2016 4:00pm GMT

Galaxy S7 and S7 Edge sales raise operating profits for Samsung in the first quarter

Samsung has reported positive results for the first quarter of 2016. The company says the Galaxy S7 and S7 Edge lead the way in the increase it had during the impressive period. In the first quarter, Samsung managed to increase their total operating profits to $5.84 billion, which is 12% higher than the same period from […]


Come comment on this article: Galaxy S7 and S7 Edge sales raise operating profits for Samsung in the first quarter

Visit TalkAndroid

28 Apr 2016 3:25pm GMT

The second generation Philips Hue app comes with a modern UI and and added functionality

If you have the Philips Hue lighting system installed in your house, you've probably been left a little dissatisfied with its clunkiness, possibly to the point of having to rely on one of the many serviceable third-party apps. It seems that Philips may have taken notice because it's just published a new app to the […]


Come comment on this article: The second generation Philips Hue app comes with a modern UI and and added functionality

Visit TalkAndroid

28 Apr 2016 1:53pm GMT

LG G5 update finally brings the App Drawer back

LG has begun rolling out a new update to the G5 that brings the "Home and App Drawer" setup back to the smartphone. Leading up to the announcement of the LG G5, there were many rumors indicating that the company would ditch the App Drawer. When launch day came around, LG did get rid of […]


Come comment on this article: LG G5 update finally brings the App Drawer back

Visit TalkAndroid

28 Apr 2016 12:55pm GMT

Motorola schedules a press event for May 17, could be the Moto G4 and G4 Plus

It looks like the Moto G4 and G4 Plus could be just over the horizon, as Motorola has begun sending out invites to media outlets in India for a May 17 press event where the two smartphones are expected to be unveiled. Previous rumors indicated that the handsets would be unveiled on June 9, but that obviously […]


Come comment on this article: Motorola schedules a press event for May 17, could be the Moto G4 and G4 Plus

Visit TalkAndroid

28 Apr 2016 12:35pm GMT

Huawei’s Honor 5C is official with 5.2-inch Full HD display and Kirin 650 processor for $139

First spotted at China's TENAA certification body a couple of weeks ago, the Honor 5C has been officially unveiled at an event in China. Honor is Huawei's budget-minded sub-brand and most recently launched the reasonably priced 5X (reviewed here). Replacing the 4C, the Honor 5C offers a 5.2-inch Full HD display, 13MP rear camera, and runs Android […]


Come comment on this article: Huawei's Honor 5C is official with 5.2-inch Full HD display and Kirin 650 processor for $139

Visit TalkAndroid

28 Apr 2016 12:17pm GMT

Samsung might be using Vulkan for a power saving TouchWiz launcher

Vulkan is going to be a very big deal for mobile phones, but it's going to do more than just improve the gaming experience on your smartphone. While most of the original buzz surrounding the efficient API was centered around lowering CPU overhead so 3D applications could run better and consume less energy, it looks […]


Come comment on this article: Samsung might be using Vulkan for a power saving TouchWiz launcher

Visit TalkAndroid

28 Apr 2016 2:51am GMT

HTC’s Nexus devices this year are going by M1 and S1, likely Marlin and Sailfish

It's about that time of year for Nexus rumors to pick up, and we're all still not-so-secretly hoping that HTC will take over this year. A new leak from Evan Blass seems to confirm this, as he's leaked that there are two devices being developed for Android N that are both HTC manufactured. There are […]


Come comment on this article: HTC's Nexus devices this year are going by M1 and S1, likely Marlin and Sailfish

Visit TalkAndroid

28 Apr 2016 2:37am GMT

27 Apr 2016

feedAndroid Developers Blog

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:

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:

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!

27 Apr 2016 9:06pm GMT

26 Apr 2016

feedAndroid Developers Blog

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:


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.

26 Apr 2016 9:49pm GMT

25 Apr 2016

feedAndroid Developers Blog

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!

25 Apr 2016 9:59pm GMT

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 security@android.com. HTTPS, Android-Security

25 Apr 2016 9:30pm GMT

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.

25 Apr 2016 4:21pm GMT

21 Apr 2016

feedAndroid Developers Blog

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.

21 Apr 2016 6:30pm GMT

20 Apr 2016

feedAndroid Developers Blog

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:

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.

20 Apr 2016 10:16pm GMT

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.

20 Apr 2016 9:26pm GMT

13 Apr 2016

feedAndroid Developers Blog

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.


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:

13 Apr 2016 8:50pm GMT

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:

New human emoji


New activity emoji



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.

13 Apr 2016 5:21pm GMT

07 Apr 2016

feedAndroid Developers Blog

Android Studio 2.0

Posted by Jamal Eason, Product Manager, Android

Android Studio 2.0 is the fastest way to build high quality, performant apps for the Android platform, including phones and tablets, Android Auto, Android Wear, and Android TV. As the official IDE from Google, Android Studio includes everything you need to build an app, including a code editor, code analysis tools, emulators and more. This new and stable version of Android Studio has fast build speeds and a fast emulator with support for the latest Android version and Google Play Services.

Android Studio is built in coordination with the Android platform and supports all of the latest and greatest APIs. If you are developing for Android, you should be using Android Studio 2.0. It is available today as a easy download or update on the stable release channel.

Android Studio 2.0 includes the following new features that Android developer can use in their workflow :


Deeper Dive into the New Features

Instant Run

Today, mobile platforms are centered around speed and agility. And yet, building for mobile can sometimes feel clunky and slow. Instant Run in Android Studio is our solution to keep you in a fast and fluid development flow. The feature increases your developer productivity by accelerating your edit, build, run cycles. When you click on the Instant Run button (), Instant Run will analyze the changes you have made and determine how it can deploy your new code in the fastest way.

New Instant Run Buttons


Whenever possible, it will inject your code changes into your running app process, avoiding re-deployment and re-installation your APK. For some types of changes, an activity or app restart is required, but your edit, build and run cycles should still be generally much faster than before. Instant Run works with any Android Device or emulator running API 14 (Ice Cream Sandwich) or higher.

Since previewing Instant Run at the end of last year, we've spent countless hours incorporating your feedback and refining for the stable release. Look for even more acceleration in future releases because build speeds can never be too fast. To learn how you can make the most out of Instant Run in your app development today, please check out our Instant Run documentation.

Android Emulator

The new Android Emulator is up to 3x faster in CPU, RAM, & I/O in comparison to the previous Android emulator. And when you're ready to build, ADB push speeds are a whopping 10x faster! In most situations, developing on the official Android Emulator is faster than a real device, and new features like Instant Run will work best with the new Android emulator.

In addition to speed and performance, the Android Emulator has a brand user interface and sensor controls. Enhanced since the initial release, with the emulator you can drag and drop APKs for quick installation, resize and rescale the window, use multi-touch actions (pinch & zoom, pan, rotate, tilt) and much more.

Android Emulator User Interface: Toolbar & Extend Controls Panel


Trying out the new emulator is as easy as updating your SDK Tools to 25.1.1 or higher, create a fresh Android Virtual Device using one of the recommended x86 system images and you are ready to go. Learn more about the Android Emulator by checking out the documentation.

Cloud Test Lab

Cloud Test Lab is a new service that allows you to test your app across a wide range of devices and device configurations at scale in the cloud. Once you complete your initial testing with your Android Emulator or Android device, Cloud Test Lab is a great extension to your testing process that provides you to run through a collection of tests against a portfolio of physical devices hosted in Google's data centers. Even if you do not have tests explicitly written, Cloud Test Lab can perform a basic set of tests to ensure that your app does not crash.

The new interface in Android Studio allows you to configure the portfolio of tests you want to run on Cloud Test Lab, and allows you to also see the results of your tests. To learn more about the service go here.

Setup for Cloud Test Lab


App Indexing

It is now easier for your users to find your app in Google Search with the App Indexing API. Android Studio 2.0 helps you to create the correct URL structure in your app code and add attributes in your AndroidManifest.xml file that will work the Google App Indexing service. After you add the URLs to your app, can you test and validate your app indexing code as shown here:

Google App Indexing Testing


Check out this link for more details about app indexing support in Android Studio.

GPU Debugger Preview

If you are developing OpenGL ES games or graphics-intensive apps, you have a new GPU debugger with Android Studio 2.0. Although the GPU debugger is a preview, you can step through your app frame by frame to identify and debug graphics rendering issues with rich information about the GL state. For more details on how to setup your Android device and app to work with the tool, check out the tech documentations here.

GPU Debugger Preview


What's Next

Update

If you are using a previous version of Android Studio, you can check for updates on the Beta 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. If you developing for the N Developer Preview, check out this additional setup instructions.

Set Up Instant Run & Android Emulator

After you update to or download Android Studio 2.0, you should upgrade your projects to use Instant Run, and create a fresh Android Virtual Device (AVD) for the new Android emulator and you are on your way to a fast Android development experience.

Using Instant Run is easy. For each of your existing projects you will see a quick prompt to update your project to the new gradle plugin version (com.android.tools.build:gradle:2.0.0).

Prompt to update your gradle version in your project


For all new app projects in Android Studio 2.0, Instant Run is on by default. Check out the documentation for more details.

We are already hard at work developing the next release of Android Studio. 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 new Google+ page or on Twitter.

07 Apr 2016 5:08pm GMT

06 Apr 2016

feedAndroid Developers Blog

Android Developer Story: Video editing app WeVideo increases user engagement with material design

Posted by Lily Sheringham, Google Play team

WeVideo is a video editing platform founded on a vision to make video creation accessible to anyone, anywhere. They first launched the popular WeVideo Video Editor app for Android, and since the latest update to the app, revenue on the platform has doubled every two months. In fact, almost 85% of their mobile users are on Android devices.

Watch Krishna Menon, President & CTO, and Oleg Tsaregorodtsev, Head of Mobile Development at WeVideo, explain how relaunching their app with material design increased user engagement by 100%. They also share how WeVideo improved monetization and installs using ratings & reviews, store listing experiments, and other features on Google Play.

Find out more about material design principles, and, learn how to find success on Google Play.

06 Apr 2016 4:36pm GMT

04 Apr 2016

feedAndroid Developers Blog

A new method to measure touch and audio latency

Posted by Mark Koudritsky, software engineer

There is a new addition in the arsenal of instruments used by Android and ChromeOS teams in the battle to measure and minimize touch and audio latency: the WALT Latency Timer.

When you use a mobile device, you expect it to respond instantly to your touch or voice: the more immediate the response, the more you feel directly connected to the device. Over the past few years, we have been trying to measure, understand, and reduce latency in our Chromebook and Android products.

Before we can reduce latency, we must first understand where it comes from. In the case of tapping a touchscreen, the time for a response includes the touch-sensing hardware and driver, the application, and the display and graphics output. For a voice command, there is time spent in sampling input audio, the application, and in audio output. Sometimes we have a mixture of these (for example, a piano app would include touch input and audio output).

Most previous work to study latency has focused on measuring a single round-trip latency number. For example, to measure audio latency, an app would measure time from app to speaker/mic and back to the app using the Dr. Rick O'Rang loopback audio dongle together with an appropriate app such as the Dr Rick O'Rang Loopback app or Superpowered Mobile Audio Latency Test App. Similarly, the TouchBot uses a fast camera to measure the round-trip delay from physical touch until a change on the screen is visible. While valuable, the problem with such a setup is that it's very difficult to break down the latency into input vs output components.

An important innovation in WALT (a descendant of QuickStep) is that it synchronizes an external hardware clock with the Android device or Chromebook to within a millisecond. This allows it to measure input and output latencies separately as opposed to measuring a round-trip latency.

WALT is simple. The parts cost less than $50 and with some basic hobby electronics skills, you can build it yourself.

We've been using WALT within Google for Nexus and Chromebook development. We're now opening this tool to app developers and anyone who wants to precisely measure real-world latencies. We hope that having readily accessible tools will help the industry as a whole improve and make all our devices more responsive to touch and voice.

04 Apr 2016 8:01pm GMT

01 Apr 2016

feedAndroid Developers Blog

Get your apps and games ready for space with Google Play (April Fools')

Posted by Lily Sheringham, Google Play team

Google Play lets you distribute your apps and games to over 1 billion active Android users around the world. With advances in space exploration and the advent of galactic tourism, there will be a high number of users beyond this world that developers need to start thinking about, too. Google Play can now help you reach them. We've added new features to the Google Play Developer Console and updated the material design guidelines, to help you design, test, and distribute your apps and games in space.

Here's a look at how The Guardian, one of the largest English-news organizations in the world, enhanced its Android app to enable astronauts and space travellers to stay informed and up-to-date, while in orbit or on the surface of the moon.


"I am pleased to have The Guardian's application to test the growing Interplanetary Internet" says Vint Cerf, distinguished visiting scientist at the Jet Propulsion Laboratory and Google's Chief Internet Evangelist. "The interstellar version is in development and I'm looking forward to having more Google Play apps and games tested in space flight."

Get your apps and games ready for take off today.

01 Apr 2016 6:08am GMT

25 Mar 2016

feedAndroid Developers Blog

Registering OAuth clients for Google Sign-In

Posted by Isabella Chen, Software Engineer, and Laurence Moroney, Developer Advocate

Starting with Google Play services 8.3, we did a major revamp of the Google Sign-In APIs, supporting both client and server auth. Behind the scenes, these APIs use OAuth 2.0 tokens to ensure secure authentication and authorization. To maintain security, we provide tools in the Google Developers Console to register the clients using these tokens.

In this post, we'll discuss the important task of registering OAuth clients for Google Sign-In, and the tools that we offer to make this as easy as possible.

Here are some scenarios that might apply to you:

  1. Start by creating a project in the Google Developers Console, which registers the client app on your behalf.
  2. If you have a backend server in your project, you'll need an OAuth client ID for it, too.
  3. And don't forget to register OAuth clients for other test and release versions of your app, too!

In this post, we'll cover some details on this process and address common pitfalls.

Getting Started - Create a Project in the Google Developers Console.

If you have not used Google Sign-In before, you can start integrating the API into your app by following the 'Get a configuration file' steps on this site. You'll be taken to a setup wizard that will create an OAuth 2.0 client ID as shown in Figure 1.

Figure 1. Configuring your app

Once you've specified your app, you'll be taken to a screen to choose and configure services such as Google Sign-In, Cloud Messaging or Google Analytics that you want your app to be able to use.

Choose Google Sign-In. In order to use it, you'll need to get the SHA-1 of the signing certificate for your Android app. This can either be a debug or a release certificate, and for the purposes of this blog you'll look at a debug one, but keep in mind that you'll need to repeat this process for each package / certificate pair you end up using (described in the last section below).

You can get the debug SHA-1 using the keytool command like this:

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

Once you have your SHA-1, enter it as seen in Figure 2.

Figure 2. Enabling Google Sign-in

Now that your project is set up, you can get started with integrating the Sign-In API. But if you need to configure your project to work with a backend server or additional package name / keystores, keep reading the sections below.

Server Config - Ensure your server is registered within the same project.

If you have your own web or cloud server with data for your application, you'll need OAuth credentials for your backend. Details on doing this can be found in the ID token and server auth code documentation.

Before using these flows, you'll need to make sure you register your web server correctly in the Google Developers Console. Once there, you'll be asked to select your project. See Figure 3.

Figure 3. Going directly to a project in the Google Developers Console.

Once you've selected your project, press the 'Continue' button, and you'll go directly to the Credentials tab where all credential types are managed. Check the "OAuth 2.0 client IDs" section, and you will see the "Web client" and "Android client for com.my.package.name" that were created for you by the setup wizard. See Figure 4.

Figure 4. The Credentials Tab on the Developers Console - Web server OAuth client info

Take note of the Client ID for for your Web client, you'll need it for both your app and server as illustrated below. (If you've created your project in the past and there's no OAuth 2.0 client ID with Type "Web application", then you will need to create one by selecting 'New Credentials' -> 'OAuth client ID'.)

If you use an ID token flow for backend authentication, when you start developing your Android app, request an ID token in your GoogleSignInOptions, supplying the web client ID for your server:

GoogleSignInOptions gso =
    new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(serverClientId)
        .requestEmail()
        .build();

And then on your server, set the same OAuth client ID for your web application to be the audience:

GoogleIdTokenVerifier verifier =
    new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
        .setAudience(Arrays.asList(serverClientId))
        .setIssuer("https://accounts.google.com")
        .build();

Successful verification will allow you to authenticate and issue a session for this newly signed-in user.

Alternatively, if you are using the server auth code flow for backend access to Google APIs, request a server auth code in your GoogleSignInOptions on Android, again supplying the web client ID for your server:

GoogleSignInOptions gso =
    new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
        .requestServerAuthCode(serverClientId)
        .requestEmail()
        .build();

And then on the server, both the OAuth client ID and the "Client secret" will be useful. The server SDK from Google can directly consume a downloaded JSON configuration file. You can click the download icon to download the JSON file (as shown in Figure 4) and use below code to construct GoogleClientSecrets:

GoogleClientSecrets clientSecrets =
    GoogleClientSecrets.load(
        JacksonFactory.getDefaultInstance(),
        new FileReader(PATH_TO_CLIENT_SECRET_FILE));

At which point you can access authenticated Google APIs on behalf of the signed-in user. Note that the "client secret" is really a secret that you should never reveal in your Android client.

Handling multiple environments - Registering other client IDs for your project.

Note that it can be common for apps to have different package names as well as different certificates (and thus SHA-1 keys) for various types of environment (such for different developers or test and release environments). Google uses your package name together with SHA-1 signing-certificate fingerprint to uniquely identify your Android application. It's important to register every package name + SHA1 fingerprint pair in Google Developers Console.

For example, to register the release version of this package, you can do so by selecting 'New Credentials' -> 'OAuth client ID', shown in Figure 5 below, and then following the steps to add the package name and production keystore SHA-1.

Figure 5. The Credentials Tab on the Developers Console - create additional OAuth client ID


Now you are ready to handle the different environments where your app might be running and release to your users!

Hopefully, this has been helpful to you in understanding how to register for OAuth keys to keep your apps and servers secure. For more information, check out the Google Developers homepage for Identity.

25 Mar 2016 5:48pm GMT

10 Nov 2011

feedAndroid Forums

Latest action game INC from OrangePixel now available!

From the developer of Meganoid and Stardash comes a new action arcade game: INC! http://www.youtube.com/watch?v=9j5OEG-3RyM Get it from the...

10 Nov 2011 9:31am GMT

Free online video chat

More than 1000 broadcast cameras for you online - the most incendiary models in Russia. 1000 girls, 1000, the temptations, 1000, full of desire - all...

10 Nov 2011 7:48am GMT

Layout problem

Hi Friends I decided to work with a tab layout application. Program consist of 3 tabs and a button. I like to place the button below the tab. ...

10 Nov 2011 5:20am GMT

[ANDROID]5 New Live Wallpapers for ANDROID !

*1-) Spectrum ICS * Image: http://i.imgur.com/IjE5B.jpg *2-) Alien Shapes* Image: http://i.imgur.com/7hQHA.jpg

10 Nov 2011 12:50am GMT

09 Nov 2011

feedAndroid Forums

New to Android, thinking of getting Asus Transformer

Hey all, New to this site and Android. I'm a 50 year old fireman who has resisted the newest tech gadgets but am wanting a tablet for use at home....

09 Nov 2011 10:33pm GMT

Island Fortress - "reverse Angry Birds" (FREE GAME)

Island Fortress is a free physics based puzzle/construction game where player has to defend the treasure from the pirate's cannonballs....

09 Nov 2011 8:42pm GMT

Unlock Code Question (MyTouch 3G)

I have a question about using an unlock code with an HTC T-Mobile MyTouch 3G. So I got the phone from a guy on Craigslist, and I have AT&T. In order...

09 Nov 2011 8:28pm GMT

[Game] Mini-Bubbles

Free Mini-Bubbles Android Market Link: https://market.android.com/details?id=br.com.dotfive.minibubbles Pop the most bubbles you can within...

09 Nov 2011 6:39pm GMT

Top 6 Android Tablet For 2011

Well now a days we are seeing new tablets coming every day and we see new upcoming tablets leaks too! It's difficult to choose best one which works...

09 Nov 2011 4:15pm GMT

unlock code

Hello, I need unlock code for telephone my touch 3g tmobile. thanks

09 Nov 2011 2:56pm GMT