Skip to content

Software Development Blogs: Programming, Software Testing, Agile Project Management

Methods & Tools

Subscribe to Methods & Tools
if you are not afraid to read more than one page to be a smarter software developer, software tester or project manager!

Android Developers Blog
Syndicate content
An Open Handset Alliance Project.
Updated: 1 hour 8 min ago

Sky Force 2014 Reimagined for Android TV

Mon, 11/24/2014 - 22:39
By Jamil Moledina, Games Strategic Partnerships Lead, Google Play

In the coming months, we’ll be seeing more media players, like the recently released Nexus Player, and TVs from partners with Android TV built-in hit the market. While there’s plenty of information available about the technical aspects of adapting your app or game to Android TV, it’s also useful to consider design changes to optimize for the living room. That way you can provide lasting engagement for existing fans as well as new players discovering your game in this new setting. Here are three things one developer did, and how you can do them too.

Infinite Dreams is an indie studio out of Poland, co-founded by hardcore game fans Tomasz Kostrzewski and Marek Wyszyński. With Sky Force 2014 TV, they brought their hit arcade style game to Android TV in a particularly clever way. The mobile-based version of Sky Force 2014 reimaged the 2004 classic by introducing stunning 3D visuals, and a free-to-download business model using in-app purchasing and competitive tournaments to increase engagement. In bringing Sky Force 2014 to TV, they found ways to factor in the play style, play sessions, and real-world social context of the living room, while paying homage to the title’s classic arcade heritage. As Wyszyński puts it, “We decided not to take any shortcuts, we wanted to make the game feel like it was designed to be played on TV.”

Orientation For starters, Sky Force 2014 is played vertically on a smartphone or tablet, also known as portrait mode. In the game, you’re piloting a powerful fighter plane flying up the screen over a scrolling landscape, targeting waves of steampunk enemies coming down at you. You can see far enough up the screen, enabling you to plan your attacks and dodge enemies in advance. Vertical play on the mobile version When bringing the game to TV, the quickest approach would have been to preserve that vertical orientation of the gameplay, by pillarboxing the field of play.

With Sky Force 2014, Infinite Dreams considered their options, and decided to scale the gameplay horizontally, in landscape mode, and recompose the view and combat elements. You’re still aiming up the screen, but the world below and the enemies coming at you are filling out a much wider field of view. They also completely reworked the UI to be comfortably operated with a gamepad or simple remote. From Wyszyński’s point of view, “We really didn't want to just add support for remote and gamepad on top of what we had because we felt it would not work very well.” This approach gives the play experience a much more immersive field of view, putting you right there in the middle of the action. More information on designing for landscape orientation can be found here.

Multiplayer Like all mobile game developers building for the TV, Infinite Dreams had to figure out how to adapt touch input onto a controller. Sky Force 2014 TV accepts both remote control and gamepad controller input. Both are well-tuned, and fighter handling is natural and responsive, but Infinite Dreams didn’t stop there. They took the opportunity to add cooperative multiplayer functionality to take advantage of the wider field of view from a TV. In this way, they not only scaled the visuals of the game to the living room, but also factored in that it’s a living room where people play together. Given the extended lateral patterns of advancing enemies, multiplayer strategies emerge, like “divide and conquer,” or “I got your back” for players of different skill levels. More information about adding controller support to your Android game can be found here, handling controller actions here, and mapping each player’s paired controllers here.
Players battle side by side in the Android TV version
Business Model Infinite Dreams is also experimenting with monetization and extending play session length. The TV version replaces several $1.99 in-app purchases and timers with a try-before-you-buy model which charges $4.99 after playing the first 2 levels for free. We’ve seen this single purchase model prove successful with other arcade action games like Mediocre’s Smash Hit for smartphones and tablets, in which the purchase unlocks checkpoint saves. We’re also seeing strong arcade action games like Vector Unit’s Beach Buggy Racing and Ubisoft’s Hungry Shark Evolution retain their existing in-app purchase models for Android TV. More information on setting up your games for these varied business models can be found here. We’ll be tracking and sharing these variations in business models on Android TV, including variations in premium, as the Android TV platform grows.

Reflecting on the work involved in making these changes, Wyszyński says, “From a technical point of view the process was not really so difficult – it took us about a month of work to incorporate all of the features and we are very happy with the results.” Take a moment to check out Sky Force 2014 TV on a Nexus Player and the other games in the Android TV collection on Google Play, most of which made no design changes and still play well on a TV. Consider your own starting point, take a look at the Android TV section on our developer blog, and build the version of your game that would be most satisfying to players on the couch.

Join the discussion on

+Android Developers
Categories: Programming

musiXmatch drives user engagement through innovation

Thu, 11/20/2014 - 15:54

Posted by Leticia Lago, Google Play team

musiXmatch is an app that offers Android users the unique and powerful feature FloatingLyrics. FloatingLyrics pops up a floating window showing synched lyrics as users listen to tracks on their favorite player and music services. It’s achieved through a seamless integration with intents on the platform, something that’s technically possible only on Android.

As a result musiXmatch has seen “a dramatic increase in terms of engagement’, says founder Max Ciociola, “which has been two times more active users and even two times more the average time they spend in the app.”

The ability to deliver lyrics to a range of different devices — such as Chromecast, Android TV, and Android Wear — is creating opportunities for musiXmatch. It’s helping them turn their app into a smart companion for their users and getting them closer to their goal of reaching 100 million people.

In the following video, Max and Android engineer Sebastiano Gottardo talk about the unique capabilities that Android offers to musiXmatch:

To learn about achieving great user engagement and retention and reaching more users through different form factors, be sure to check out these resources:

  • Convert installs to active users — Watch this video to hear from Matteo Vallone, Partner Development Manager for Google Play, about the best practices in engaging and retaining app users using intents, identity, context, and rich notifications as well as delivering a cross-platform user experience.
  • Expanding to new form factors: Tablet, Wear & TV — Watch this panel discussion with Google experts talking about cross-platform opportunities and answering developer questions.
Join the discussion on

+Android Developers
Categories: Programming

Chinese Developers Can Now Offer Paid Applications to Google Play Users in More Than 130 countries

Thu, 11/20/2014 - 03:07

By Ellie Powers, product manager for Google Play

Google Play is the largest digital store for Android users to discover and purchase their favorite mobile app and games, and the ecosystem is continuing to grow globally. Over the past year, we’ve expanded the list of countries where app developers can sign up to be merchants on Google Play, totaling 60 countries, including Lebanon, Jordan, Oman, Pakistan, Puerto Rico, Qatar and Venezuela most recently.

As part of that continued effort, we’re excited to announce merchant support in China, enabling local developers to export and sell their apps to Google Play users in more than 130 countries. Chinese developers can now offer both free and paid applications through various monetization models, including in-app purchasing and subscriptions. For revenue generated on Google Play, developers will receive payment to their Chinese bank accounts via USD wire transfers.

If you develop Android apps in China and want to start distributing your apps to a global audience through Google Play, visit play.google.com/apps/publish and register as a developer. If you want to sell apps and in-app products, you'll need to also sign up for a Google Wallet merchant account, which is available on the “Revenue” page in the Google Play Developer Console. After you’ve uploaded your apps, you can set prices in the Developer Console and later receive reports on your revenue. You’ll receive your developer payouts via wire transfer. For more details, please visit our developer help center.

We look forward to continuing to roll out Google Play support to developers in many more countries around the world.

中国开发者可以向全球130个国家的Google Play用户提供付费应用啦

发表者:Ellie Powers, Google Play产品经理

Google Play是一个可让Android用户发现和购买他们喜爱的移动应用程序和游戏的全球最大的应用商店,这个生态系统在全球迅速成长。过去一年中,我们已经扩展到60个国家,让应用程序开发人员可以注册成为 Google Play的商家,其中新近支持的国家包括黎巴嫩、约旦、阿曼、巴基斯坦、波多黎各、卡塔尔和委内瑞拉。

作为持续改进 Google Play努力的一部分,我们很高兴地宣布在中国增加了对商家的支持,让中国的开发者能售卖应用程序到130个国家的 Google Play 用户。中国的开发者现在可以提供通过各种盈利模式的免费和付费应用,包括应用内购买和订阅。在 Google Play 产生的营收将通过美元电汇的方式支付给开发者的中国的银行账户。

如果你在中国开发Android应用程序,并希望通过 Google Play 把应用程序推广到全球,请登录play.google.com/apps/publish 并建立你的 Google Play 开发者账户。如果你想售卖付费的应用程序和应用程序内的产品,则需要再注册一个Google 电子钱包商家帐户,通过Google Play开发者控制台里的”营收”页面进行设置。上传应用程序后,你可以通过开发者控制台设定价格,之后就可以收到营收报告,你将会通过电汇的方式获得收入。

我们将继续增加更多 Google Play 商家支持的国家,敬请关注。

更多详情,请访问我们的开发者帮助中心

Join the discussion on

+Android Developers
Categories: Programming

Keeping Your Saved Games in the Cloud

Wed, 11/19/2014 - 19:47

Posted by Todd Kerpelman, Developer Advocate

Saved Games Are the Future!

I think most of us have at least one or two games we play obsessively. Me? I'm a Sky Force 2014 guy. But maybe you're into matching colorful objects, battling monsters, or helping avians with their rage management issues. Either way, there's probably some game where you've spent hours upon hours upgrading your squad, reaching higher and higher levels, or unlocking every piece of bonus content in the game.

Now imagine losing all of that progress when you decide to get a new phone. Or reinstall your game. Yikes!

That's why, when Google Play Games launched, one of the very first features we included was the ability for users to save their game to the cloud using a service called the AppState API. For developers who didn't need an entire server-based infrastructure to run their game, but didn't want to lose players when they upgraded their devices, this feature was a real life-saver.

But many developers wanted even more. With AppState, you were limited to 4 slots of 256k of data each, and for some games, this just wasn't enough. So this past year at Google I/O, we launched an entirely new Saved Games feature, powered by Google Drive. This gave you huge amounts of space (up to 3MB per saved game with unlimited save slots), the ability to save a screenshot and metadata with your saved games, and some nice features like showing your player's saved games directly in the Google Play app.

...But AppState is Yesterday's News

Since the introduction of Saved Games, we've seen enough titles happily using the service and heard enough positive feedback from developers that we're convinced that Saved Games is the better offering and the way to go in the future. With that in mind, we've decided to start deprecating the old cloud save system using AppState and are encouraging everybody who's still using it to switch over to the new Saved Games feature (referred to in our libraries as "Snapshots").

What does this mean for you as a game developer?

If you haven't yet added Saved Games to your game, now would be the perfect time! The holidays are coming up and your players are going to start getting new devices over the next couple of months. Wouldn't it be great if they could take your game's progress with them? Unless, I guess, "not retaining users" is part of your business plan.

If you're already using the new Saved Games / Snapshot system, put your feet up and relax. None of these changes affect you. Okay, now put your feet down, and get back to work. You probably have a seasonal update to work on, don't you?

If you're using the old AppState system, you should start migrating your player's data over to the new Saved Games service. Luckily, it's easy to include both systems in the same game, so you should be able to migrate your users' data with their ever knowing. The process would probably work a little something like this:

  • Enable the new Saved Game service for your game by
    • Adding the Drive.SCOPE_APPFOLDER scope to your list of scopes in your GoogleApiClient.
    • Turning on Saved Games for your game in the Google Play Developer Console.
  • Next, when your app tries to load the user's saved game
    • First see if any saved game exists using the new Saved Games service. If there is, go ahead and use it.
    • Otherwise, grab their saved game from the AppState service.
  • When you save the user's game back to the cloud, save it using the new Saved Games service.
  • And that should be it! The next time your user loads up your game, it will find their saved data in the new Saved Games service, and they'll be all set.
  • We've built a sample app that demonstrates how to perform these steps in your application, so we encourage you to check it out.

In a few months, we will be modifying the old AppState service to be read-only. You'll still be able to read your user's old cloud save games and transfer them to the new Saved Games service, but you'll no longer be able to save games using the old service. We are evaluating early Q2 of 2015 to make this change, which should give you enough time to push your "start using Saved Games" update to the world.

If you want to find out more about Saved Games and how they work, feel free to review our documentation, our sample applications, or our Game On! videos. And we look forward to many more hours of gaming, no matter how many times we switch devices.

Join the discussion on

+Android Developers
Categories: Programming

Coding Android TV games is easy as pie

Wed, 11/19/2014 - 19:28
Posted by Alex Ames, Fun Propulsion Labs at Google*

We’re pleased to announce Pie Noon, a simple game created to demonstrate multi-player support on the Nexus Player, an Android TV device. Pie Noon is an open source, cross-platform game written in C++ which supports:

  • Up to 4 players using Bluetooth controllers.
  • Touch controls.
  • Google Play Games Services sign-in and leaderboards.
  • Other Android devices (you can play on your phone or tablet in single-player mode, or against human adversaries using Bluetooth controllers).

Pie Noon serves as a demonstration of how to use the SDL library in Android games as well as Google technologies like Flatbuffers, Mathfu, fplutil, and WebP.

  • Flatbuffers provides efficient serialization of the data loaded at run time for quick loading times. (Examples: schema files and loading compiled Flatbuffers)
  • Mathfu drives the rendering code, particle effects, scene layout, and more, allowing for efficient mathematical operations optimized with SIMD. (Example: particle system)
  • fplutil streamlines the build process for Android, making iteration faster and easier. Our Android build script makes use of it to easily compile and run on on Android devices.
  • WebP compresses image assets more efficiently than jpg or png file formats, allowing for smaller APK sizes.

You can download the game in the Play Store and the latest open source release from our GitHub page. We invite you to learn from the code to see how you can implement these libraries and utilities in your own Android games. Take advantage of our discussion list if you have any questions, and don’t forget to throw a few pies while you’re at it!

* Fun Propulsion Labs is a team within Google that's dedicated to advancing gaming on Android and other platforms.

Join the discussion on

+Android Developers
Categories: Programming

Begin developing with Android Auto

Tue, 11/18/2014 - 19:09

Posted by Daniel Holle, Product Manager

At Google I/O back in June, we provided a preview of Android Auto. Today, we’re excited to announce the availability of our first APIs for building Auto-enabled apps for audio and messaging. Android apps can now be extended to the car in a way that is optimized for the driving experience.

For users, this means they simply connect their Android handheld to a compatible vehicle and begin utilizing a car-optimized Android experience that works with the car’s head unit display, steering wheel buttons, and more. For developers, the APIs and UX guidelines make it easy to provide a simple way for users to get the information they need while on the road. As an added bonus, the Android Auto APIs let developers easily extend their existing apps targeting Android 5.0 (API level 21) or higher to work in the car without having to worry about vehicle-specific hardware differences. This gives developers wide reach across manufacturers, model and regions, by just developing with one set of APIs and UX standards.

There are two use cases that Android Auto supports today:

  • Audio apps that expose content for users to browse and allow audio playback from the car, such as music, podcasts, news, etc.
  • Messaging apps that receive incoming notifications, read messages aloud, and send replies via voice from the car.

To help you get started with Android Auto, check out our Getting Started guide. It’s important to note that while the APIs are available today, apps extended with Android Auto cannot be published quite yet. More app categories will be supported in the future, providing more opportunities for developers and drivers of Android Auto. We encourage you to join the Android Auto Developers Google+ community to stay up-to-date on the latest news and timelines.

We’ve already started working with partners to develop experiences for Android Auto: iHeartRadio, Joyride, Kik, MLB.com, NPR, Pandora, PocketCasts, Songza, SoundCloud, Spotify, Stitcher, TextMe, textPlus, TuneIn, Umano, and WhatsApp. If you happen to be in the Los Angeles area, stop by the LA Auto Show through November 30 and visit us in the Hyundai booth to take Android Auto and an app or two for a test drive.

Join the discussion on

+Android Developers
Categories: Programming

Google Play services 6.5

Tue, 11/18/2014 - 06:46
Posted by Ian Lake, Developer Advocate

To offer more seamless integration of Google products within your app, we’re excited to start the rollout of the latest version of Google Play services.

Google Play services 6.5 includes new features in Google Maps, Google Drive and Google Wallet as well as the recently launched Google Fit API. We are also providing developers with more granular control over which Google Play services APIs your app depends on to help you maintain a lean app.

Google Maps

We’re making it easier to get directions to places from your app! The Google Maps Android API now offers a map toolbar to let users open Google Maps and immediately get directions and turn by turn navigation to the selected marker. This map toolbar will show by default when you compile against Google Play services 6.5.

In addition, there is also a new ‘lite mode’ map option, ideal for situations where you want to provide a number of smaller maps, or a map that is so small that meaningful interaction is impractical, such as a thumbnail in a list. A lite mode map is a bitmap image of a map at a specified location and zoom level.

In lite mode, markers and shapes are drawn client-side on top of the static image, so you still have full control over them. Lite mode supports all of the map types, the My Location layer, and a subset of the functionality of a fully-interactive map. Users can tap on the map to launch Google Maps when they need more details.

The Google Maps Android API also exposes a new getMapAsync(OnMapReadyCallback) method to MapFragment and MapView which will notify you exactly when the map is ready. This serves as a replacement for the now deprecated getMap() method.

We’re also exposing the Google Maps for Android app intents available to your apps including displaying the map, searching, starting turn by turn navigation, and opening Street View so you can build upon the familiar and powerful maps already available on the device.

Drive

You can now add both public and application private custom file properties to a Drive file which can be used to build very efficient search queries and allow apps to save information which is guaranteed to persist across editing by other apps.

We’ve also made it even easier to make syncing your files to Drive both user and battery friendly with the ability to control when files are uploaded by network type or charging status and cancel pending uploads.

Google Wallet

In addition to the existing ‘Buy with Google’ button available to quickly purchase goods & services using Google Wallet, this release adds a ‘Donate with Google’ button for providing the same ease of use in collecting donations.

Google Fit

The Google Fit SDK was recently officially released as part of Google Play services and can be used to super-charge your fitness apps with a simple API for working with sensors, recording activity data, and reading the user’s aggregated fitness data.

In this release, we’ve made it easier for developers to add activity segments (predefined time periods of running, walking, cycling, etc) when inserting sessions, making it easy to support pauses or multiple activity type workouts. We’ll also be adding additional samples to help kick-start your Google Fit integration.

Granular Dependency Management

As we’ve continued to add more APIs across the wide range of Google services, it can be hard to maintain a lean app, particularly if you're only using a portion of the available APIs. Now with Google Play services 6.5, you’ll be able to depend only on a minimal common library and the exact APIs your app needs. This makes it very lightweight to get started with Google Play services.

SDK Coming Soon!

We’ll be rolling out Google Play services 6.5 over the next few days, and we’ll update this blog post, publish the documentation, and make the SDK available once the rollout completes.

To learn more about Google Play services and the APIs available to you through it, visit the Google Play Services section on the Android Developer site.

Join the discussion on

+Android Developers
Categories: Programming

EyeEm Improves User Engagement through Android Design

Wed, 11/12/2014 - 20:39

By Leticia Lago, Google Play team

EyeEm is a global community for photographers that goes beyond sharing photos with friends: photographers can share tips, take part in missions, and sell their photos. To win more customers, a design that best showcases photos from the community is very important for this Berlin-based company.

With the idea of bringing a beautiful, simple experience to their fast growing base of Android users, the team recently embarked on a redesign of their app. Following the Android design principles, they stripped back the UI and simplified navigation. This allowed them to deliver a more streamlined app experience, along with a clean, crisp design that presents photos beautifully. And it paid off. According to Ramzi Rizk, EyeEm co-founder and CTO, “Our new design helped improve user growth and retention across the board, in every single metric we have.”

In the following video, Rizk and colleague Matias Castello, Product Head of Mobile, talk about their experience applying Android design to their app and the improvements in user engagement it has achieved:


Resources to help you with design

To learn more about how to design your apps for Android devices and achieve great user engagement and retention, be sure to check out these resources:

  • Android Design — all the information you need to understand and implement Android design principles in your app.
  • Design.Bytes — presented by the Google designers who created Material Design and apps, such as the Google I/O 2014 app, these videos provide a fun and informative introduction to Android design.
Join the discussion on

+Android Developers
Categories: Programming

Utilities for C/C++ Android Developers: fplutil 1.0

Mon, 11/10/2014 - 19:07

By Stewart Miles, Fun Propulsion Labs at Google*

Today we're announcing the 1.0 release of fplutil, a set of small libraries and tools by Fun Propulsion Labs at Google (the FPL in fplutil) that is useful when developing C/C++ applications for Android.

fplutil introduces the following:

  • build_all_android.py, an all-in-one build script that allows you to build (with the Android NDK), install and run native (C/C++) Android apps from the command line. This is ideal for build automation, but is also useful in a developer’s compile/run loop.
  • buildutil performs the configuration, build and archive steps of Android and Linux C/C++ applications using a suite of Python modules. This suite of modules can automate builds in a continuous integration environment. This framework uses legacy tools in the Android Development Toolkit.
  • libfplutil enables C/C++ developers to write traditional applications (like Hello World) using "main()" and "printf()" on Android.
  • android_ndk_perf.py is a desktop tool that enables native (C/C++) developers to measure the CPU utilization of their applications on Android, guiding their optimization efforts. An example report is shown below:

android_ndk_perf.py example HTML report

You can download the latest open source release from our github page. We invite you to contribute to the project and join our discussion list!

*Fun Propulsion Labs is a team within Google that's dedicated to advancing gaming on Android and other platforms.

Join the discussion on

+Android Developers
Categories: Programming

AppCompat v21 — Material Design for Pre-Lollipop Devices!

Sat, 11/08/2014 - 03:14

By Chris Banes, Android Developer Relations

The Android 5.0 SDK was released last Friday, featuring new UI widgets and material design, our visual language focused on good design. To enable you to bring your latest designs to older Android platforms we have expanded our support libraries, including a major update to AppCompat, as well as new RecyclerView, CardView and Palette libraries.

In this post we'll take a look at what’s new in AppCompat and how you can use it to support material design in your apps.

What's new in AppCompat?

AppCompat (aka ActionBarCompat) started out as a backport of the Android 4.0 ActionBar API for devices running on Gingerbread, providing a common API layer on top of the backported implementation and the framework implementation. AppCompat v21 delivers an API and feature-set that is up-to-date with Android 5.0

In this release, Android introduces a new Toolbar widget. This is a generalization of the Action Bar pattern that gives you much more control and flexibility. Toolbar is a view in your hierarchy just like any other, making it easier to interleave with the rest of your views, animate it, and react to scroll events. You can also set it as your Activity’s action bar, meaning that your standard options menu actions will be display within it.

You’ve likely already been using the latest update to AppCompat for a while, it has been included in various Google app updates over the past few weeks, including Play Store and Play Newsstand. It has also been integrated into the Google I/O Android app, pictured above, which is open-source.

Setup

If you’re using Gradle, add appcompat as a dependency in your build.gradle file:

dependencies {
    compile "com.android.support:appcompat-v7:21.0.+"
}
New integration

If you are not currently using AppCompat, or you are starting from scratch, here's how to set it up:

  • All of your Activities must extend from ActionBarActivity, which extends from FragmentActivity from the v4 support library, so you can continue to use fragments.
  • All of your themes (that want an Action Bar/Toolbar) must inherit from Theme.AppCompat. There are variants available, including Light and NoActionBar.
  • When inflating anything to be displayed on the action bar (such as a SpinnerAdapter for list navigation in the toolbar), make sure you use the action bar’s themed context, retrieved via getSupportActionBar().getThemedContext().
  • You must use the static methods in MenuItemCompat for any action-related calls on a MenuItem.

For more information, see the Action Bar API guide which is a comprehensive guide on AppCompat.

Migration from previous setup

For most apps, you now only need one theme declaration, in values/:

values/themes.xml:

<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
    <!-- Set AppCompat’s actionBarStyle -->
    <item name="actionBarStyle">@style/MyActionBarStyle</item>

    <!-- Set AppCompat’s color theming attrs -->
    <item name=”colorPrimary”>@color/my_awesome_red</item>
    <item name=”colorPrimaryDark”>@color/my_awesome_darker_red</item>
    
    <!-- The rest of your attributes -->
</style>

You can now remove all of your values-v14+ Action Bar styles.

Theming

AppCompat has support for the new color palette theme attributes which allow you to easily customize your theme to fit your brand with primary and accent colors. For example:

values/themes.xml:

<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
    <!-- colorPrimary is used for the default action bar background -->
    <item name=”colorPrimary”>@color/my_awesome_color</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name=”colorPrimaryDark”>@color/my_awesome_darker_color</item>

    <!-- colorAccent is used as the default value for colorControlActivated,
         which is used to tint widgets -->
    <item name=”colorAccent”>@color/accent</item>

    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight, and colorSwitchThumbNormal. -->
    
</style>

When you set these attributes, AppCompat automatically propagates their values to the framework attributes on API 21+. This automatically colors the status bar and Overview (Recents) task entry.

On older platforms, AppCompat emulates the color theming where possible. At the moment this is limited to coloring the action bar and some widgets.

Widget tinting

When running on devices with Android 5.0, all of the widgets are tinted using the color theme attributes we just talked about. There are two main features which allow this on Lollipop: drawable tinting, and referencing theme attributes (of the form ?attr/foo) in drawables.

AppCompat provides similar behaviour on earlier versions of Android for a subset of UI widgets:

You don’t need to do anything special to make these work, just use these controls in your layouts as usual and AppCompat will do the rest (with some caveats; see the FAQ below).

Toolbar Widget

Toolbar is fully supported in AppCompat and has feature and API parity with the framework widget. In AppCompat, Toolbar is implemented in the android.support.v7.widget.Toolbar class. There are two ways to use Toolbar:

  • Use a Toolbar as an Action Bar when you want to use the existing Action Bar facilities (such as menu inflation and selection, ActionBarDrawerToggle, and so on) but want to have more control over its appearance.
  • Use a standalone Toolbar when you want to use the pattern in your app for situations that an Action Bar would not support; for example, showing multiple toolbars on the screen, spanning only part of the width, and so on.
Action Bar

To use Toolbar as an Action Bar, first disable the decor-provided Action Bar. The easiest way is to have your theme extend from Theme.AppCompat.NoActionBar (or its light variant).

Second, create a Toolbar instance, usually via your layout XML:

<android.support.v7.widget.Toolbar
    android:id=”@+id/my_awesome_toolbar”
    android:layout_height=”wrap_content”
    android:layout_width=”match_parent”
    android:minHeight=”?attr/actionBarSize”
    android:background=”?attr/colorPrimary” />

The height, width, background, and so on are totally up to you; these are just good examples. As Toolbar is just a ViewGroup, you can style and position it however you want.

Then in your Activity or Fragment, set the Toolbar to act as your Action Bar:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blah);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);
}

From this point on, all menu items are displayed in your Toolbar, populated via the standard options menu callbacks.

Standalone

The difference in standalone mode is that you do not set the Toolbar to act as your action bar. For this reason, you can use any AppCompat theme and you do not need to disable the decor-provided Action Bar.

In standalone mode, you need to manually populate the Toolbar with content/actions. For instance, if you want it to display actions, you need to inflate a menu into it:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blah);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);

    // Set an OnMenuItemClickListener to handle menu item clicks
    toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // Handle the menu item
            return true;
        }
    });

    // Inflate a menu to be displayed in the toolbar
    toolbar.inflateMenu(R.menu.your_toolbar_menu);
}

There are many other things you can do with Toolbar. For more information, see the Toolbar API reference.

Styling

Styling of Toolbar is done differently to the standard action bar, and is set directly onto the view.

Here's a basic style you should be using when you're using a Toolbar as your action bar:

<android.support.v7.widget.Toolbar  
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

The app:theme declaration will make sure that your text and items are using solid colors (i.e 100% opacity white).

DarkActionBar

You can style Toolbar instances directly using layout attributes. To achieve a Toolbar which looks like 'DarkActionBar' (dark content, light overflow menu), provide the theme and popupTheme attributes:

<android.support.v7.widget.Toolbar
    android:layout_height=”wrap_content”
    android:layout_width=”match_parent”
    android:minHeight=”@dimen/triple_height_toolbar”
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
SearchView Widget

AppCompat offers Lollipop’s updated SearchView API, which is far more customizable and styleable (queue the applause). We now use the Lollipop style structure instead of the old searchView* theme attributes.

Here’s how you style SearchView:

values/themes.xml:
<style name=”Theme.MyTheme” parent=”Theme.AppCompat”>
    <item name=”searchViewStyle”>@style/MySearchViewStyle</item>
</style>
<style name=”MySearchViewStyle” parent=”Widget.AppCompat.SearchView”>
    <!-- Background for the search query section (e.g. EditText) -->
    <item name="queryBackground">...</item>
    <!-- Background for the actions section (e.g. voice, submit) -->
    <item name="submitBackground">...</item>
    <!-- Close button icon -->
    <item name="closeIcon">...</item>
    <!-- Search button icon -->
    <item name="searchIcon">...</item>
    <!-- Go/commit button icon -->
    <item name="goIcon">...</item>
    <!-- Voice search button icon -->
    <item name="voiceIcon">...</item>
    <!-- Commit icon shown in the query suggestion row -->
    <item name="commitIcon">...</item>
    <!-- Layout for query suggestion rows -->
    <item name="suggestionRowLayout">...</item>
</style>

You do not need to set all (or any) of these, the defaults will work for the majority of apps.

Toolbar is coming...

Hopefully this post will help you get up and running with AppCompat and let you create some awesome material apps. Let us know in the comments/G+/Twitter if you’re have questions about AppCompat or any of the support libraries, or where we could provide more documentation.

FAQ
Why is my EditText (or other widget listed above) not being tinted correctly on my pre-Lollipop device?

The widget tinting in AppCompat works by intercepting any layout inflation and inserting a special tint-aware version of the widget in its place. For most people this will work fine, but I can think of a few scenarios where this won’t work, including:

  • You have your own custom version of the widget (i.e. you’ve extended EditText)
  • You are creating the EditText without a LayoutInflater (i.e., calling new EditText()).

The special tint-aware widgets are currently hidden as they’re an unfinished implementation detail. This may change in the future.

Why has X widget not been material-styled when running on pre-Lollipop?
Only some of the most common widgets have been updated so far. There are more coming in future releases of AppCompat.
Why does my Action Bar have a shadow on Android Lollipop? I’ve set android:windowContentOverlay to null.
On Lollipop, the action bar shadow is provided using the new elevation API. To remove it, either call getSupportActionBar().setElevation(0), or set the elevation attribute in your Action Bar style.
Why are there no ripples on pre-Lollipop?
A lot of what allows RippleDrawable to run smoothly is Android 5.0’s new RenderThread. To optimize for performance on previous versions of Android, we've left RippleDrawable out for now.
How do I use AppCompat with Preferences?
You can continue to use PreferenceFragment in your ActionBarActivity when running on an API v11+ device. For devices before that, you will need to provide a normal PreferenceActivity which is not material-styled.
Join the discussion on

+Android Developers
Categories: Programming

Implementing Material Design in Your Android app

Sat, 11/08/2014 - 03:13
By Chris Banes and Nick Butcher, Android Developer Relations

Material design is a comprehensive approach to visual, interaction and motion design for the multi-screen world. Android 5.0 Lollipop and the updated support libraries help you to create material UIs. Here’s a rundown of some of the major elements of material design and the APIs and widgets that you can use to implement them in your app.

Tangible surfaces

In material design, UIs are composed of pieces of digital paper & ink. The surfaces and the shadows they cast provide visual cues to the structure of the application, what you can touch and how it will move. This digital material can move, expand and reform to create flexible UIs.

Shadows

A surface’s position and depth result in subtle changes in lighting and shadows. The new elevation property lets you specify a view’s position on the Z-axis and the framework then casts a real-time dynamic shadow on items behind it. You can set the elevation declaratively in your layouts, defined in dips:

<ImageView …
    android:elevation="8dp" />

You can also set this from code using getElevation()/setElevation() (with shims in ViewCompat). The shadow a view casts is defined by its outline, which by default is derived from its background. For example if you set a circular shape drawable as the background for a floating action button, then it would cast an appropriate shadow. If you need finer control of a view’s shadow, you can set a ViewOutlineProvider which can customise the Outline in getOutline().

Cards

Cards are a common pattern for creating surfaces holding a distinct piece of information. The new CardView support library allows you to create them easily, providing outlines and shadows for you (with equivalent behaviour on prior platforms).

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <!-- Your card content -->

</android.support.v7.widget.CardView>

CardView extends FrameLayout and provides default elevation and corner radius for you so that cards have a consistent appearance across the platform. You can customise these via the cardElevation and cardCornerRadius attributes, if required. Note that Cards are not the only way of achieving dimensionality and you should be wary of over-cardifying your UI!

Print-like Design

Material utilises classic principles from print design to create clean, simple layouts that put your content front and center. Bold deliberate color choices, intentional whitespace, tasteful typography and a strong baseline grid create hierarchy, meaning and focus.

Typography

Android 5.0 updates the system font Roboto to beautifully and clearly display text no matter the display size. A new medium weight has been added (android:fontFamily=”sans-serif-medium”) and new TextAppearance styles implement the recommended typographic scale for balancing content density and reading comfort. For instance you can easily use the ‘Title’ style by setting android:textAppearance=”@android:style/TextAppearance.Material.Title”. These styles are available on older platforms through the AppCompat support library, e.g. “@style/TextAppearance.AppCompat.Title”.

Color

Your application’s color palette brings branding and personality to your app so we’ve made it simple to colorize UI controls by using the following theme attributes:

  • colorPrimary. The primary branding color for the app; used as the action bar background, recents task title and in edge effects.
  • colorAccent. Vibrant complement to the primary branding color. Applied to framework controls such as EditText and Switch.
  • colorPrimaryDark. Darker variant of the primary branding color; applied to the status bar.

Further attributes give fine grained control over colorizing controls, see: colorControlNormal, colorControlActivated, colorControlHighlight, colorButtonNormal, colorSwitchThumbNormal, colorEdgeEffect, statusBarColor and navigationBarColor.

AppCompat provides a large subset of the functionality above, allowing you to colorize controls on pre-Lollipop platforms.

Dynamic color

Material Design encourages dynamic use of color, especially when you have rich images to work with. The new Palette support library lets you extract a small set of colors from an image to style your UI controls to match; creating an immersive experience. The extracted palette will include vibrant and muted tones as well as foreground text colors for optimal legibility. For example:

Palette.generateAsync(bitmap,
        new Palette.PaletteAsyncListener() {
    @Override
    public void onGenerated(Palette palette) {
         Palette.Swatch vibrant =
                 palette.getVibrantSwatch();
          if (swatch != null) {
              // If we have a vibrant color
              // update the title TextView
              titleView.setBackgroundColor(
                  vibrant.getRgb());
              titleView.setTextColor(
                  vibrant.getTitleTextColor());
          }
    }
});
Authentic Motion

Tangible surfaces don’t just appear out of nowhere like a jump-cut in a movie; they move into place helping to focus attention, establish spatial relationships and maintain continuity. Materials respond to touch to confirm your interaction and all changes radiate outward from your touch point. All motion is meaningful and intimate, aiding the user’s comprehension.

Activity + Fragment Transitions

By declaring ‘shared elements’ that are common across two screens you can create a smooth transition between the two states.

album_grid.xml
…
    <ImageView
        …
        android:transitionName="@string/transition_album_cover" />
album_details.xml
…
    <ImageView
        …
        android:transitionName="@string/transition_album_cover" />

AlbumActivity.java
Intent intent = new Intent();
String transitionName = getString(R.string.transition_album_cover);
…
ActivityOptionsCompat options =
ActivityOptionsCompat.makeSceneTransitionAnimation(activity,
    albumCoverImageView,   // The view which starts the transition
    transitionName    // The transitionName of the view we’re transitioning to
    );
ActivityCompat.startActivity(activity, intent, options.toBundle());

Here we define the same transitionName in two screens. When starting the new Activity and this transition is animated automatically. In addition to shared elements, you can now also choreograph entering and exiting elements.

Ripples

Materials respond to users’ touch with an ink ripple surface reaction. Interactive controls such as Buttons exhibit this behaviour by default when you use or inherit from Theme.Material (as will ?android:selectableItemBackground). You can add this feedback to your own drawables by simply wrapping them in a ripple element:

<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/accent_dark">
    <item>
        <shape
            android:shape="oval">
            <solid android:color="?android:colorAccent" />
        </shape>
    </item>
</ripple>

Custom views should propagate touch location down to their drawables in the View#drawableHotspotChanged callback so that the ripple can start from the touch point.

StateListAnimator

Materials also respond to touch by raising up to meet your finger, like a magnetic attraction. You can achieve this effect by animating the translationZ attribute which is analogous to elevation but intended for transient use; such that Z = elevation + translationZ. The new stateListAnimator attribute allows you to easily animate the translationZ on touch (Buttons do this by default):

layout/your_layout.xml
<ImageButton …
    android:stateListAnimator="@anim/raise" />
anim/raise.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_pressed="true">
        <objectAnimator
            android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ"
            android:valueTo="@dimen/touch_raise"
            android:valueType="floatType" />
    </item>
    <item>
        <objectAnimator
            android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ"
            android:valueTo="0dp"
            android:valueType="floatType" />
    </item>
</selector>
Reveal

A hallmark material transition for showing new content is to reveal it with an expanding circular mask. This helps to reinforce the user’s touchpoint as the start of all transitions, with its effects radiating outward radially. You can implement this using the following Animator:

Animator reveal = ViewAnimationUtils.createCircularReveal(
                    viewToReveal, // The new View to reveal
                    centerX,      // x co-ordinate to start the mask from
                    centerY,      // y co-ordinate to start the mask from
                    startRadius,  // radius of the starting mask
                    endRadius);   // radius of the final mask
reveal.start();
Interpolators

Motion should be deliberate, swift and precise. Unlike typical ease-in-ease-out transitions, in Material Design, objects tend to start quickly and ease into their final position. Over the course of the animation, the object spends more time near its final destination. As a result, the user isn’t left waiting for the animation to finish, and the negative effects of motion are minimized. A new fast-in-slow-out interpolator has been added to achieve this motion.

For elements entering and exiting the screen (which should do so at peak velocity), check out the linear-out-slow-in and fast-out-linear-in interpolators respectively.

Adaptive design

Our final core concept of material is creating a single adaptive design that works across devices of all sizes and shapes, from watches to giant TVs. Adaptive design techniques help us realize the vision that each device reflects a different view of the same underlying system. Each view is tailored to the size and interaction appropriate for that device. Colors, iconography, hierarchy, and spatial relationships remain constant. The material design system provides flexible components and patterns to help you build a design that scales.

Toolbar

The toolbar is a generalization of the action bar pattern, providing similar functionality, but much more flexibility. Unlike the standard action bar, toolbar is a view in your hierarchy just like any other, so you can place instances wherever you like, interleave them with the rest of your views, animate, react to scroll events and so on. You can make the Toolbar act as your Activity’s Action Bar by calling Activity.setActionBar().

In this example, the blue toolbar is an extended height, overlaid by the screen content and provides the navigation button. Note that two further toolbars are used in the list and detail views.

For details of implementing toolbars, see this post.

Go Forth and Materialize

Material Design helps you to build understandable, beautiful and adaptive apps, which are alive with motion. Hopefully, this post has inspired you to apply these principles to your app and signposted some of the new (and compatibility) APIs to achieve this.

Join the discussion on

+Android Developers
Categories: Programming

Material Design on Android Checklist

Sat, 11/08/2014 - 03:13
ul.checklist { list-style-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNCIgaGVpZ2h0PSIxMC41IiB2aWV3Qm94PSIwIDYuOSAxNiAxMiI+DQogIDxwYXRoIGQ9Ik01LDE2LjRsLTMuOC0zLjhMMCwxMy45bDUsNUwxNS45LDguMWwtMS4zLTEuM0w1LDE2LjR6Ii8+DQo8L3N2Zz4NCg=='); clear: left; } .sectionintro { max-width: 400px; border: 1px solid #ccc; position: relative; padding: 10px 10px 10px 90px; font-style: italic; margin-top: 10px; margin-bottom: 10px; min-height: 75px; } .sectionintro img { position: absolute; left: 5px; top: 5px; border: 0 !important; box-shadow: 0 !important; } h3 { margin-top: 20px; font-size: 150%; } h4 { margin-top: 20px; } ul.checklist li { margin-top: 10px; } div.in-code { color: #aaa; padding-left: 20px; } div.in-code em { color: #c60; font-weight: bold; font-style: normal; }

By Roman Nurik, Design Advocate

Android 5.0 brings in material design as the new design system for the platform and system apps. Consumers will soon start getting Android 5.0 and they’re already seeing glimpses of material design with apps like Google Play Newsstand, Inbox by Gmail and Tumblr. Meanwhile, developers now have the Android 5.0 SDK, along with AppCompat for backward compatibility. And designers now have access to Photoshop, Illustrator and Sketch templates. All this means that now—yes now!—is the time to start implementing material design in your Android apps. Today, let’s talk about what implementing material design really boils down to.

Below, you’ll find a material design checklist that you can use to mark progress as you implement the new design system. The checklist is divided into 4 key sections based on the 4 key aspects of material design.

If you include a good chunk of the items in the checklist below, especially the ones indicated as signature elements, and follow traditional Android design best practices (i.e. these, these, and things we discussed on ADiA), you’ll be well on your way to material design awesomeness!

Tangible Surfaces UIs consist of surfaces (pieces of “digital paper”) arranged at varying elevations, casting shadows on surfaces behind them.
Figure 1. Surfaces and layering.
  • Signature element: Shadows are used to communicate which surfaces are in front of others, helping focus attention and establish hierarchy. Read more on depth and layering in UIs. In code: This is the android:elevation and android:translationZ attribute in Android 5.0. On earlier versions, shadows are normally provided as PNG assets.
  • Shadows and surfaces are used in a consistent and structured way. Each shadow indicates a new surface. Surfaces are created thoughtfully and carefully.
  • There are generally between 2 and 10 surfaces on the screen at once; avoid too much layering/nesting of surfaces.
  • Scrollable content either scrolls to the edges of the screen or behind another surface that casts a shadow over the content’s surface. Never clip an element against an invisible edge—elements don’t just scroll off into nowhere. Put another way, you rarely scroll the ink on a surface; you scroll the surface itself. In code: android:clipToPadding=false often helps with this when using ListView and ScrollView.
  • Surfaces have simple, single-color backgrounds.
A Bold, Print-Like Aesthetic The “digital ink” you draw on those pieces of digital paper is informed by classic print design, with an emphasis on bold use of color and type, contextual imagery, and structured whitespace.
Figure 2. Primary and accent colors.

Figure 3. Keylines.
  • Signature element: Apps use a primary color and an accent color (Figure 2) to color surface backgrounds and key UI widgets such as text fields and checkboxes. The accent color contrasts very well with the primary color (for example an app can use a dark blue primary color and a neon pink accent color). The accent color is high-contrast and is used to call attention to key UI elements, like a circular floating action button, selected tab strips, or form fields. In code: Set the android:colorPrimary and android:colorAccent attributes in your theme (drop the android prefix if using AppCompat). AppCompat automatically colors text fields, checkboxes, and more on pre-L devices.
  • Signature element: On Android 5.0, the status bar is colored to match the app’s primary color, or the current screen’s content. For full-bleed imagery, the status bar can be translucent. In code: Set the android:colorPrimaryDark or android:statusBarColor attribute in your theme (drop the android prefix if using AppCompat) or call Window.setStatusBarColor.
  • Icons, photos/images, text, and other foreground elements are colored “ink” on their surfaces. They don’t have shadows and don’t use gradients.
  • Colors extracted from images can be used to color adjacent UI elements or surfaces. In code: This can be done using the Palette support library.
  • Signature element: Icons in the app follow the system icon guidelines, and standard icons use the material design icon set.
  • Photos are generally immersive and full-bleed. For example, for detail screens, run edge-to-edge and can even appear behind the app bar or status bar. In code: The new Toolbar widget (and its AppCompat equivalent) can be transparent and placed directly in your layout. For the status bar, check this Stack Overflow post.
  • Signature element: Where appropriate, elements like body text, thumbnails, app bar titles, etc. are aligned to 3 keylines (Figure 3). On phones, those keylines are 16dp and 72dp from the left edge and 16dp from the right edge of the screen. On tablets those values are 24dp and 80dp.
  • UI elements are aligned to and sized according to an 8dp baseline grid. For example, app bars are 56dp tall on phones and 64dp tall on tablets. Padding and margins can take on values like 8dp, 16dp, 24dp, etc. More precise text positioning uses a 4dp grid.
Authentic Motion Motion helps communicate what’s happening in the UI, providing visual continuity across app contexts and states. Motion also adds delight using smaller-scale transitions. Motion isn’t employed simply for motion’s sake.
Figure 4. "Hero" transitions.
  • In general, UI and content elements don’t just appear or disappear—they animate into place, either together as a unit, or individually.
  • Signature element: When touching an item to see its details, there’s a “hero” transition (Figure 4) that moves and scales the item between its position in the browsing screen and its position in the detail screen. In code: These are called “shared element transitions” in the SDK. The support version of FragmentTransaction also includes some shared element support.
  • Signature element: Ripple effects originating from where you touched the screen are used to show touch feedback on an item. In code: The default android:selectableItemBackground and android:selectableItemBackgroundBorderless have this, or you can use RippleDrawable (<ripple>) to customize the effect. On pre-5.0 devices, ripples aren’t an expected feature, so defer to the default android:selectableItemBackground behavior.
  • Signature element: UI elements can appear using a circular “reveal” animation. In code: See this doc or the ViewAnimationUtils class for more.
  • Signature element: Animations are used in more subtle, delightful ways, such as to convey the transition between icon states or text states. For example, a “+” icon can morph into an “x” symbol, or an outlined heart icon can be filled using a paint-bucket fill effect. In code: Icon transitions can be implemented using AnimatedStateListDrawable and its XML counterpart. An example can be found in the Google I/O app source. There’s also support for animated vector icons.
  • Animations and transitions are fast—generally under 300ms.
  • Crossfades are often replaced by translate/slide transitions: vertical slides for descendant navigation and horizontal slides for lateral navigation. For slide transitions, prefer quick acceleration and gentle ease-in deceleration over simple linear moves. See the material design spec on motion for more.
Adaptive Design (and UI Patterns) Tangible surfaces, bold graphic design, and meaningful motion work together to bring a consistent experience across any screen, be it phones, tablets, laptops, desktops, TVs, wearables, or even cars. Additionally, the key UI patterns below help establish a consistent character for the app across devices.
Figure 5. The floating action button.
  • The app uses responsive design best practices to ensure screens lay themselves out appropriately on any screen size, in any orientation. See the Tablet App Quality Checklist for a list of ways to optimize for tablets, and this blog post for high-level tablet optimization tips.
    • In material design, detail screens are often presented as popups that appear using “hero” transitions (see above).
    • In multi-pane layouts, the app can use multiple toolbars to place actions contextually next to their related content.
  • Signature element: Where appropriate, the app promotes the key action on a screen using a circular floating action button (FAB). The FAB (Figure 5) is a circular surface, so it casts a shadow. It is colored with a bright, accent color (see above). It performs a primary action such as send, compose, create, add, or search. It floats in front of other surfaces, and is normally at an 8dp elevation. It frequently appears at the bottom right of the screen, or centered on an edge where two surfaces meet (a seam or a step).

App bar
  • Signature element: The app uses a standard Android app bar. The app bar doesn’t have an app icon. Color and typography are used for branding instead. The app bar casts a shadow (or has a shadow cast on it by a surface below and behind it). The app bar normally has a 4dp elevation. In code: Use the new Toolbar widget in Android 5.0 that is placed directly into the activity’s view hierarchy. AppCompat also provides android.support.v7.widget.Toolbar, which supports all modern platform versions.
  • The app bar might be for example 2 or 3 times taller than the standard height; on scroll, the app bar can smoothly collapse into its normal height.
  • The app bar might be completely transparent in some cases, with the text and actions overlaying an image behind it. For example, see the Google Play Newsstand app.
  • App bar titles align to the 2nd keyline (see more info on keylines above) In code: when using the Toolbar widget, use the android:contentInsetStart attribute.
  • Where appropriate, upon scrolling down, the app bar can scroll off the screen, leaving more vertical space for content. Upon scrolling back up, the app bar should be shown again.
Tabs
Figure 6. Tabs with material design.
  • Signature element: Tabs follow the newer material design interactions and styling (Figure 6). There are no vertical separators between tabs. If the app uses top-level tabs, tabs are visually a part of the app bar; tabs are a part of the app bar’s surface. In code: See the SlidingTabsBasic sample code in the SDK or the Google I/O app source (particularly the "My Schedule" section for phones).
  • Tabs should support a swipe gesture for moving between them. In code: All tabs should be swipeable using the ViewPager widget, which is available in the support library.
  • Selected tabs are indicated by a foreground color change and/or a small strip below the tab text (or icon) colored with an accent color. The tab strip should smoothly slide as you swipe between tabs.
Navigation drawer
Figure 7. Navigation drawers
with material design.
  • Signature element: If the app uses a navigation drawer, it follows the newer material design interactions and styling (Figure 7). The drawer appears in front of the app bar. It also appears semitransparent behind the status bar. In code: Implement drawers using the DrawerLayout widget from the support library, along with the new Toolbar widget discussed above. See this Stack Overflow post for more.
  • Signature element: The leftmost icon in the app bar is a navigation drawer indicator; the app icon is not visible in the app bar. Optionally, on earlier versions of the platform, if the app has a drawer, the top-left icon can remain the app icon and narrower drawer indicator, as in Android 4.0.
  • The drawer is a standard width: No wider than 320dp on phones and 400dp on tablets, but no narrower than the screen width minus the standard toolbar height (360dp - 56dp = 304dp on the Nexus 5)
  • Item heights in the drawer follow the baseline grid: 48dp tall rows, 8dp above list sections and 8dp above and below dividers.
  • Text and icons should follow the keylines discussed above.

More and more apps from Google and across the Google Play ecosystem will be updating with material design soon, so expect Winter 2014 to be a big quarter for design on Android. For more designer resources on material design, check out the DesignBytes series. For additional developer resources, check the Creating Apps with Material Design docs!

Join the discussion on

+Android Developers
Categories: Programming

Your Chance to be on TV!

Sat, 11/08/2014 - 03:12

By Tarjei Vassbotn and Dan Galpin, Developer Advocates, Android TV

We’re excited to see the launch of Nexus Player, the first consumer streaming media player running Android TV. Android TV delivers an entertainment experience tailored for users, including movies, shows, games and more.
Now is a great time to develop apps for Android TV that reach a whole new audience.

Starting today, you can publish your apps for Android TV on Google Play, the largest digital store for apps and games. We’ve provided guidance on how to get started building great apps for Android TV in this post.

"Google has done an insanely good job to ease the developer’s task of creating a TV application, mainly thanks to the Leanback support library. It literally takes 2 hours to create a fully working and possibly fancy app, which is awesome."

- Sebastiano Gottardo A high bar for quality experiences

We want to offer the best possible experience for users to enjoy your apps and games. To make this possible, your Android TV app must meet the basic requirements for usability. When your app meets these requirements, users will be able to discover and download it directly on their Android TV devices.

Even if you have already uploaded your app to the Google Play Developer Console, you will need to add TV graphics and screenshots, and opt-in to distribution on TV on the Pricing & Distribution page. For complete information about the requirements and process of publishing your Android TV app for Google Play, make sure to check out the publishing documentation.

Get started!

With our Leanback Library we’ve made it easy for you to extend your existing app to the TV screen or even build a completely new app for Android TV. For a quick look at the Leanback Library, check out this DevBytes video.

We’ve only begun scratching the surface of what’s possible with this new form factor, and we are very excited to see what you will build, start developing today!

Join the discussion on

+Android Developers
Categories: Programming

The fastest route between voice search and your app

Sat, 11/08/2014 - 02:00
By Jarek Wilkiewicz, Developer Advocate, Google Search

How many lines of code will it take to let your users say Ok Google, and search for something in your app? Hardly any. Starting today, all you need is a small addition to your AndroidManifest.xml in order to connect the Google Now SEARCH_ACTION with your searchable activity:

<activity android:name=".SearchableActivity">
    <intent-filter>
        <action android:name="com.google.android.gms.actions.SEARCH_ACTION"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

Once you make these changes, your app can receive the SEARCH_ACTION intent containing the SearchManager.QUERY extra with the search expression.

At Google, we always look for innovative ways to help you improve mobile search and drive user engagement back to your app. For example, users can now say to the Google app: “Ok Google, search pizza on Eat24” or “Ok Google, search for hotels in Maui on TripAdvisor.”

This feature is available on English locale Android devices running Jelly Bean and above with the Google app v3.5 or greater. Last but not least, users can enable the Ok Google hot-word detection from any screen, which offers them the fastest route between their search command and your app!


Join the discussion on
+Android Developers


Categories: Programming

Improved Game Testing with Google Play Games Management API

Thu, 11/06/2014 - 23:36

By Ben Frenkel, Google Play Games team

We’re always looking to help developers improve the gaming experience for their users on Google Play. So today, we've expanded our existing suite of Management APIs to let you fully control all resources in your Google Play Games-enabled game during development and testing, with better support for alpha and beta groups.

Let’s take a quick dive into the expanded offering.

  • Reset a single tester’s state for any resource (e.g., achievements, leaderboards), or do it for all resources at once. For example, you can now completely reset a given tester’s data if they’ve ended up in a bad state due to an experimental build. You can do this for individual instances or all instances of achievements, events, quests, or leaderboards scores.
  • Reset the state of a single draft resource for all testers, or do it for all draft resources at once. You can now reset all draft leaderboards in your game before publishing with a single API call. This ensures the members of your alpha or beta communities don’t have an unfair advantage on release day. You can do this for individual instances or all instances of achievements, events, quests, or leaderboards scores.
  • Clear global match state for all real time or turn based matches composed solely of testers. You can now reset all turn-based matches on release day. This will ensure that all matches from that point on are on the release version of the game. This is available for both real-time or turn-based games.

These updates make it far less complex and error prone to manage data during testing, saving you time and improving the rate at which you can make and test changes to your games.

Play Games Management API background

The Management API is a set of tools that enable developers to do things like manage tester data and clean up bogus leaderboard score submissions. Developers can also use the API to control and manipulate resources (e.g., achievements, events, multiplayer match data). Getting started

You can get started with the latest version of the Management API right now. Review the updated API reference documentation, start with an example management interface, or download the sample client libraries to get on your way.

Join the discussion on

+Android Developers
Categories: Programming

Introducing a New Guide, “The Secrets to App Success on Google Play”

Thu, 11/06/2014 - 17:31

By Dom Elliott, Google Play team

With more than 50 billion apps and games downloaded in total, Google Play is helping developers and content creators around the world build successful businesses. In fact, we paid out more than $5 billion over the last year to developers for creating incredible apps that are changing the way people communicate, live, work, and play.

Developing an app or game and distributing it on Google Play is a good start, but it’s only the first step to building a sustainable business. That’s why we’ve written “The Secrets to App Success on Google Play,” a detailed playbook on the best practices and tools you can use to maximize the reach, retention, and revenue of your new app.

The guide is separated into the following sections:

  • Publishing on Google Play — using the Google Play Developer Console to distribute your app to over 1 billion Android users worldwide.
  • Quality — The fundamentals of building a great app and an insight into the Google Play guidelines and policies.
  • Discoverability & reach — Maximizing your app's discoverability and reaching the widest audience possible.
  • Engagement & retention — Converting installations into active users and improving user retention.
  • Monetization — Monetization strategies to generate ongoing, growing revenue streams.
  • Measurement with Google Analytics — Understanding your users and improving your app experience, conversions, and marketing.
  • Going global — Launching your app in local markets around the world.

Download the guide now in English (PDF, 11MB) or get it on Google Play. We’ll release the guide in more languages in the coming months. If you’re in the US or the UK, we also have a limited number of printed copies that we are offering to send for free. Request a printed copy here.

Once you’ve checked out the guide, we’d love to hear your feedback so we can continue to improve, let us know what you think.

Join the discussion on

+Android Developers
Categories: Programming

Going Global: Space Ape Games Finds Success in Japan

Thu, 11/06/2014 - 06:22

By Leticia Lago, Google Play team

There are many ways to find success for a game on the international stage: it’s not a simple formula, it’s a combination of things, ranging from localizing effectively to choosing the right price. London-based Space Ape Games brought together a range of resources and tactics to take Samurai Siege into Japan, growing that market to contribute up to 15% of the game’s average $55,000 daily earnings.

John Earner, Simon Hade, and Toby Moore founded Space Ape Games in 2012 with just 12 people. Their goal, to create amazing multiplayer mobile games. Samurai Siege is their first game and they found that Android players have great retention and monetize well. “Our experience has been great with Google Play. We have found that it is half of our audience and half of our business,” says John.

Check out the video below to hear more about how Space Ape expanded to Japan.


Resources to help you grow globally

You can grow your games business worldwide too, and maximize your distribution potential with Google Play. Be sure to check out these resources:

  • Reaching players in new territories panel [VIDEO] — Hear first hand experiences from game developers who have successfully taken games to international markets. Antonin Lhuillier (Gameloft), Anatoly Ropotov (Game Insight), Saad Choudri (Miniclip), Eyal Rabinovich (Playscape), and Joe Raeburn (Space Ape Games) share their tips for localization, culturalization, and more.
  • Go Global session [VIDEO] — Hyunse Chang, from the Google Play Apps and Games team in Korea, shares key insights into APAC markets and trends among successful apps and games in the region. Leverage these pro tips and best practices to expand your reach to a wider audience.
  • Localization checklist — This document identifies the essential aspects of localization, to help you get your app ready for a successful worldwide launch on Google Play.
Join the discussion on

+Android Developers
Categories: Programming

Tips for integrating with Google Accounts on Android

Tue, 10/28/2014 - 18:24
By Laurence Moroney, Developer Advocate

Happy Tuesday! We've had a few questions come in recently regarding Google Accounts on Android, so we've put this post together to show you some of our best practices. The tips today will focus on Android-based authentication, which is easily achieved through the integration of Google Play services. Let's get started.

Unique Identifiers

A common confusion happens when developers use the account name (a.k.a. email address) as the primary key to a Google Account. For instance, when using GoogleApiClient to sign in a user, a developer might use the following code inside of the onConnected callback for a registered GoogleApiClient.ConnectedCallbacks listener:

[Error prone pseudocode]
String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
// createLocalAccount() is specific to the app's local storage strategy.
createLocalAccount(accountName);

While it is OK to store the email address for display or caching purposes, it is possible for users to change the primary email address on a Google Account. This can happen with various types of accounts, but these changes happen most often with Google Apps For Work accounts.

So what's a developer to do? Use the Google Account ID (as opposed to the Account name) to key any data for your app that is associated to a Google Account. For most apps, this simply means storing the Account ID and comparing the value each time the onConnected callback is invoked to ensure the data locally matches the currently logged in user. The API provides methods that allow you to get the Account ID from the Account Name. Here is an example snippet you might use:

[Google Play Services 6.1+]
String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
String accountID = GoogleAuthUtil.getAccountId(accountName);
createLocalAccount(accountID);
[Earlier Versions of Google Play Services (please upgrade your client)]
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String accountID = currentUser.getID();
createLocalAccount(accountID);

This will key the local data against a Google Account ID, which is unique and stable for the user even after changing an email address.

So, in the above scenario, if your data was keyed on an ID, you wouldn’t have to worry if your users change their email address. When they sign back in, they’ll still get the same ID, and you won’t need to do anything with your data.

Multiple Accounts

If your app supports multiple account connections simultaneously (like the Gmail user interface shown below), you are calling setAccountName on the GoogleApiClient.Builder when constructing GoogleApiClients. This requires you to store the account name as well as the Google Account ID within your app. However, the account name you’ve stored will be different if the user changes their primary email address. The easiest way to deal with this is to prompt the user to re-login. Then, update the account name when onConnected is called after login. Any time a login occurs you, can use code such as this to compare Account IDs and update the email address stored locally for the Account ID.

[Google Play Services 6.1+]
String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
String accountID = GoogleAuthUtil.getAccountId(accountName);
// isExistingLocalAccount(), createLocalAccount(), 
// getLocalDataAccountName(), and updateLocalAccountName() 
// are all specific to the app's local storage strategy.
boolean existingLocalAccountData = isExistingLocalAccount(accountID);
if (!existingLocalAccountData) {
    // New Login.
    createLocalAccount(accountID, accountName);
} else {
    // Existing local data for this Google Account.
    String cachedAccountName = getLocalDataAccountName(accountID);    
    if (!cachedAccountName.equals(accountName)) {
        updateLocalAccountName(accountID, accountName);
    }
}

This scenario reinforces the importance of using the Account ID to store data all data in your app.

Online data

The same best practices above apply to storing data for Google Accounts in web servers for your app. If you are storing data on your servers in this manner and treating the email address as the primary key:

ID [Primary Key] Field 1 Field 2 Field 3 user1@gmail.com Value 1 Value 2 Value 3

You need to migrate to this model where the primary key is the Google Account ID.:

ID [Primary Key] Email Field 1 Field 2 Field 3 108759069548186989918 user1@gmail.com Value 1 Value 2 Value 3

If you don't make Google API calls from your web server, you might be able to depend on the Android application to notify your web server of changes to the primary email address when implementing the updateLocalAccountName method referenced in the multiple accounts sample code above. If you make Google API calls from your web server, you likely implemented it using the Cross-client authentication and can detect changes via the OAuth2 client libraries or REST endpoints on your server as well.

Conclusion

When using Google Account authentication for your app, it’s definitely a best practice to use the account ID, as opposed to the account name to distinguish data for the user. In this post, we saw three scenarios where you may need to make changes to make your apps more robust. With the growing adoption of Google for Work, users who are changing their email address, but keeping the same account ID, may occur more frequently, so we encourage all developers to make plans to update their code as soon as possible.


Join the discussion on
+Android Developers


Categories: Programming

Getting Your Apps Ready for Nexus 6 and Nexus 9

Fri, 10/24/2014 - 00:53

By Katherine Kuan, Developer Advocate

Updated material design Tumblr app on Nexus 6.

Last week, we unveiled the Nexus 6 and Nexus 9, the newest additions to our Nexus family that will ship with Android 5.0 Lollipop. Together, they deliver a pure Google experience, showcasing fresh visual styles with material design, improved performance, and additional features.

Let’s make sure your apps and games are optimized to give your users the best mobile experience on these devices. We’ve outlined some best practices below.

Nexus 6 Screen

The Nexus 6 boasts an impressive 5.96” Quad HD screen display at a resolution of 2560 x 1440 (493 ppi). This translates to ~ 730 x 410 dp (density independent pixels).

Check your assets

It has a quantized density of 560 dpi, which falls in between the xxhdpi and xxxhdpi primary density buckets. For the Nexus 6, the platform will scale down xxxhdpi assets, but if those aren’t available, then it will scale up xxhdpi assets.

Provide at least an xxxhdpi app icon because devices can display large app icons on the launcher. It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density. For example, an xxxhdpi app icon can be used on the launcher for an xxhdpi device.

res/
   mipmap-mdpi/
      ic_launcher.png
   mipmap-hdpi/
      ic_launcher.png
   mipmap-xhdpi/
      ic_launcher.png  
   mipmap-xxhdpi/
      ic_launcher.png
   mipmap-xxxhdpi/   
      ic_launcher.png  # App icon used on Nexus 6 device launcher

Choosing to add xxxhdpi versions for the rest of your assets will provide a sharper visual experience on the Nexus 6, but does increase apk size, so you should make an appropriate decision for your app.

res/
   drawable-mdpi/
      ic_sunny.png
   drawable-hdpi/
      ic_sunny.png
   drawable-xhdpi/   
      ic_sunny.png
   drawable-xxhdpi/  # Fall back to these if xxxhdpi versions aren’t available
      ic_sunny.png 
   drawable-xxxhdpi/ # Higher resolution assets for Nexus 6
      ic_sunny.png
Make sure you are not filtered on Google Play

If you are using the <compatible-screens> element in the AndroidManifest.xml file, you should stop using it because it’s not scalable to re-compile and publish your app each time new devices come out. However, if you must use it, make sure to update the manifest to add the configuration for these devices (by screen size and density). Otherwise your app may be excluded from Google Play search results on these devices.

Nexus 9 Screen

The Nexus 9 is a premium 8.9” tablet with a screen size of 2048 x 1536 pixels (288 ppi), which translates to 1024 x 768 dip. This is a 4:3 aspect ratio, which is unique compared to earlier tablets. The Nexus 9 falls into the xhdpi density bucket, and you should already have assets in the drawable-xhdpi folder.

Updated Material Design Wall Street Journal app on Nexus 9.

Enable NDK apps for 64-bit

The Nexus 9 runs on a 64-bit Dual Core processor, which makes it the first Android device to ship with a 64-bit ARM instruction set. Support for 64-bit processors was just added in Android 5.0, so if you have an NDK app, enable it by updating the APP_ABI value in your Application.mk file:

APP_ABI := armeabi armeabi-v7a arm64-v8a x86 x86_64 mips mips64

More detailed instructions are provided in the developer site. You can test your 64-bit enabled app on a physical device with a 64-bit processor running Android 5.0, or take advantage of the recently announced 64-bit emulator in Android Studio.

Update your hardware keyboard support

The Nexus 9 Keyboard Folio will be available as an accessory in Google Play. It’s very important that you don’t lock your app to a single orientation. The Nexus 9’s natural orientation is portrait mode, while it’s used in landscape mode with the keyboard. If you lock to the device’s natural orientation, the app may appear sideways for devices with keyboards.

Users should be able to navigate around the main content of the app with the keyboard, while relying on touch input or keyboard shortcuts for toolbar actions and button bars. Therefore, ensure that your app has proper keyboard navigation and shortcuts for primary actions. Keyboard shortcuts that are invoked with Ctrl + [shortcut] combo can be defined via menu items using:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menu_create"
        android:title="@string/menu_create"
        android:alphabeticShortcut="c” />
</menu/>

Alternatively, shortcuts can be defined using Activity#onKeyShortcut or View#onKeyShortcut. Learn more about keyboard actions here.

In MainActivity.java:

@Override
public boolean onKeyShortcut(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_R:
            Toast.makeText(this, "Reply", Toast.LENGTH_SHORT).show();
            return true;
        default:
            return super.onKeyShortcut(keyCode, event);
    }
}
Responsive layouts with w- and sw- qualifiers

In order to take advantage of the screen real estate on the Nexus 6 and Nexus 9, we emphasize the importance of responsive design. In the past, if you assumed that landscape mode is significantly wider than portrait mode, you may run into problems on a device like the Nexus 9, which has an aspect ratio of 4:3. Instead of declaring layouts using the layout-land or layout-port resource folder qualifiers, we strongly recommend switching to the w<N>dp width resource folder qualifier so that content is laid out based on available screen width.

Think about content first and foremost. Decide on min and max screen real estate that your content requires, and determine cutoff points at different screen widths where you can modify the layout composition for your app (# of grid columns, multi-pane layout, etc…).

For example, a single pane layout for your main activity on phones can be defined in:

res/layout/activity_main.xml

On larger screen devices, where the current orientation is at least 600dp in width, a new two-pane layout with a list alongside a detail pane could be declared in:

res/layout-w600dp/activity_main.xml

On even larger screen devices, where the current orientation is at least 720dp in width, a new multi-pane layout where the detail pane requires even more horizontal space could be declared in:

res/layout-w720dp/activity_main.xml

As for attributes based on form factor, instead of declaring them in values-large or values-xlarge resource directories, use the sw<N>dp smallest width qualifier. For example, you could style your TextViews to have a medium font size on phones.

In res/values/styles.xml:

<style name="DescriptionTextStyle">
  <item name="android:textAppearance">?android:attr/textAppearanceMedium</item>
</style>

Meanwhile, TextViews could have a large font size when the smallest width of the device (taking the minimum of the landscape and portrait widths) is 600dp or wider. This ensures the font size of your app doesn’t change when you rotate this large screen device.

In res/values-sw600dp/styles.xml:

<style name="DescriptionTextStyle">
  <item name="android:textAppearance">?android:attr/textAppearanceLarge</item>
</style> 
Take advantage of 5.0 and Material

Set your android:targetSdkVersion to "21". Take note of the important behavior changes in Android 5.0 Lollipop including ART, the new Android runtime, to ensure that your app continues to run well. You can also leverage new platform APIs like richer notifications.

Nexus 6 and Nexus 9 users will be immersed in the new world of material design, and they’ll expect the same seamless transitions, bold colors, and delightful details from your app. As you invest time in bringing your app up to date with our latest design language, there’s a whole host of resources to help you make the leap, including important new updates to the support library, videos, and a getting started guide. Good luck and we can’t wait to see your apps!

Join the discussion on

+Android Developers
Categories: Programming

GPS on Android Wear Devices

Fri, 10/24/2014 - 00:03

By Wayne Piekarski, Developer Advocate

With the latest release of Android Wear, wearables with built-in GPS like the Sony Smartwatch 3 can now give you a GPS location update directly from the wearable, without a paired phone nearby. You can now build an app like MyTracks that lets a user track their run even when they leave their phone at home. For wearable devices that do not have built-in GPS, a software solution has always existed in Google Play Services that automatically uses the GPS from your connected phone.

The Golfshot wearable app uses built-in GPS to calculate your distance to the next hole, even when you don’t have your phone with you.


Implementing GPS location updates

Implementing GPS location updates for Android Wear is simple. On the wearable, use the FusedLocationProviderApi from Google Play services to request location updates. This is the same API that has been available on mobile, so you can easily reuse your existing code and samples.

FusedLocationProviderApi automatically makes the most power-efficient decision about where to get location updates. If the phone is connected to the wearable, it uses the GPS on the phone and sends the updates to the wearable. If the phone is not connected to the wearable and the wearable has a built-in GPS, then it uses the wearable’s GPS.

One case you’ll need to handle is if the phone is not connected to the wearable and the wearable does not have built-in GPS. You will need to detect this and provide a graceful recovery mechanism, such as a message telling the user to bring their phone with them. However, for the most part, deciding which GPS to use, and sending the position from the phone to the wearable, is handled automatically. You do not need to deal with the low-level implementation details yourself.

Data synchronization

When writing an app that runs on the wearable, you will eventually want to synchronize the data it collects with the paired phone. When the wearable is being taken out for a run, especially with the built-in GPS, there may not be a phone present. So you will want to store your location data using the Data Layer API, and when the phone reconnects with the wearable later, the data will be automatically synchronized.

For more details about how to use the location API, check out the extensive documentation and sample here.

Android Wear apps on Google Play

Also, as a heads up, starting on November 3 with the public release of Android 5.0, you will be able to submit your apps for clearer designation as Android Wear apps on Google Play. If your apps follow the criteria in the Wear App Quality checklist and are accepted as Wear apps on Play, it will be easier for Android Wear users to discover your apps. Stay tuned for more information about how to submit your apps for Android Wear review through the Google Play Developer Console.

Join the discussion on

+Android Developers
Categories: Programming