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 day 17 min ago

Google Play services 4.3

Sun, 04/13/2014 - 00:08
gps

Google Play services 4.3 has now been rolled out to the world, and it contains a number of features you can use to improve your apps. Specifically, this version adds some new members to the Google Play services family: Google Analytics API, Tag Manager, and the Address API. We’ve also made some great enhancements to the existing APIs; everything to make sure you stay on top of the app game out there.

Here are the highlights of the 4.3 release.


Google Analytics and Google Tag Manager

The Analytics API and Google Tag Manager has existed for Android for some time as standalone technologies, but with this release we are incorporating them as first class citizens in Google Play services. Those of you that are used to the API will find it very similar to previous versions, and if you have not used it before we strongly encourage you to take a look at it.

Google Analytics allows you to get detailed statistics on how you app is being used by your users, for example what functionality of your app is being used the most, or which activity triggers users to convert from an advertised version of an app to paid one. Google Tag Manager lets you change characteristics of your app on-the-fly, for example colors, without having to push an update from Google Play.


Google Play Games services Update

The furious speed of innovation in Android mobile gaming has not slowed down and neither have we when it comes to packing the Google Play Game services API with features.

With this release, we are introducing game gifts, which allows players to send virtual in-game requests to anyone in their Google+ circles or through player search. Using this feature, the player can send a 'wish' request to ask another player for an in-game item or benefit, or a 'gift' request to grant an item or benefit to another player.

This is a great way for a game to be more engaging by increasing cross player collaboration and social connections. We are therefore glad to add this functionality as an inherent part of the Games API, it is an much-wanted extension to the multi-player functionality included a couple of releases ago. For more information, see: Unlocking the power of Google for your games.


Drive API

The Google Drive for Android API was just recently added as a member of the Google Play services API family. This release adds a number of important features:

  • Pinning - You can now pin files that should be kept up to date locally, ensuring that it is available when the user is offline. This is great for users that need to use your app with limited or no connectivity
  • App Folders - An app often needs to create files which are not visible to the user, for example to store temporary files in a photo editor. This can now be done using App Folders, a feature is analogous to Application Data Folders in the Google Drive API
  • Change Notifications - You can now register a callback to receive notifications when a file or folder is changed. This mean you no longer need to query Drive continuously to check if the data has changed, just put a change notification on it

In addition to the above, we've also added the ability to access a number of new metadata fields.


Address API

This release will also includes a new Address API, which allows developers to request access to addresses for example to fill out a delivery address form. The kicker is the convenience for the user; a user interface component is presented where they select the desired address, and bang, the entire form is filled out. Developers have been relying on Location data which works very well, but this API shall cater for cases where the Location data is either not accurate or the user actually wants to use a different address than their current physical location. This should sound great to anyone who has done any online shopping during the last decade or so.

That’s it for this time. Now go to work and incorporate these new features to make your apps even better!
And stay tuned for future updates.

For the release video, please see:
DevBytes: Google Play Services 4.3

For details on the APIs, please see:
Google Analytics
Google Tag Manager
Google Play Games services Gifts
Google Drive Android API - Change Events
Google Drive Android API - Pinning
Google Drive Android API - App Folder
Address API







Join the discussion on
+Android Developers


















The latest release of Google Play services has begun rolling out to Android devices worldwide. It includes the full release of the Google Cast SDK, for developing and publishing Google Cast-ready apps.

Once the rollout is complete, you'll be able to download the Google Play services SDK using the SDK Manager and get started with the new APIs. Watch for more information coming soon.

-->
Categories: Programming

Google Play App Translation Service

Tue, 04/08/2014 - 07:04

Posted by Ellie Powers, Google Play team

Today we are happy to announce that the App Translation Service, previewed in May at Google I/O, is now available to all developers. Every day, more than 1.5 million new Android phones and tablets around the world are turned on for the first time. Each newly activated Android device is an opportunity for you as a developer to gain a new user, but frequently, that user speaks a different language from you.

To help developers reach users in other languages, we launched the App Translation Service, which allows developers to purchase professional app translations through the Google Play Developer Console. This is part of a toolbox of localization features you can (and should!) take advantage of as you distribute your app around the world through Google Play.

We were happy to see that many developers expressed interest in the App Translation Service pilot program, and it has been well received by those who have participated so far, with many repeat customers.

Here are several examples from developers who participated in the App Translation Service pilot program: the developers of Zombie Ragdoll used this tool to launch their new game simultaneously in 20 languages in August 2013. When they combined app translation with local marketing campaigns, they found that 80% of their installs came from non-English-language users. Dating app SayHi Chat expanded into 13 additional languages using the App Translation Service. They saw 120% install growth in localized markets and improved user reviews of the professionally translated UI. The developer of card game G4A Indian Rummy found that the App Translation Service was easier to use than their previous translation methods, and saw a 300% increase with user engagement in localized apps. You can read more about these developers’ experiences with the App Translation Service in Developer Stories: Localization in Google Play.

To use the App Translation Service, you’ll want to first read the localization checklist. You’ll need to get your APK ready for translation, and select the languages to target for translation. If you’re unsure about which languages to select, Google Play can help you identify opportunities. First, review the Statistics section in the Developer Console to see where your app has users already. Does your app have a lot of installs in a certain country where you haven’t localized to their language? Are apps like yours popular in a country where your app isn’t available yet? Next, go to the Optimization Tips section in the Developer Console to make sure your APK, store listing, and graphics are consistently translated.

You’ll find the App Translation Service in the Developer Console at the bottom of the APK section — you can start a new translation or manage an existing translation here. You’ll be able to upload your app’s file of string resources, select the languages you want to translate into, select a professional translation vendor, and place your order. Pro tip: you can put your store listing text into the file you upload to the App Translation Service. You’ll be able to communicate with your translator to be sure you get a great result, and download your translated string files. After you do some localization testing, you’ll be ready to publish your newly translated app update on Google Play — with localized store listing text and graphics. Be sure to check back to see the results on your user base, and track the results of marketing campaigns in your new languages using Google Analytics integration.

Good luck! Bonne chance ! ご幸運を祈ります! 행운을 빌어요 ¡Buena suerte! Удачи! Boa Sorte!

Join the discussion on

+Android Developers
Categories: Programming

Improved App Insight by Linking Google Analytics with Google Play

Tue, 04/08/2014 - 02:02

Posted by Ellie Powers, Google Play team

A key part of growing your app’s installed base is knowing more about your users — how they discover your app, what devices they use, what they do when they use your app, and how often they return to it. Understanding your users is now made easier through a new integration between Google Analytics and the Google Play Developer Console.

Starting today, you can link your Google Analytics account with your Google Play Developer Console to get powerful new insights into your app’s user acquisition and engagement. In Google Analytics, you’ll get a new report highlighting which campaigns are driving the most views, installs, and new users in Google Play. In the Developer Console, you’ll get new app stats that let you easily see your app’s engagement based on Analytics data.

This combined data can help you take your app business to the next level, especially if you’re using multiple campaigns or monetizing through advertisements and in-app products that depend on high engagement. Linking Google Analytics to your Developer Console is straightforward — the sections below explain the new types of data you can get and how to get started.

In Google Analytics, see your app’s Google Play referral flow

Once you’ve linked your Analytics account to your Developer Console, you’ll see a new report in Google Analytics called Google Play Referral Flow. This report details each of your campaigns and the user traffic that they drive. For each campaign, you can see how many users viewed listing page in Google Play and how many went on to install your app and ultimately launch it on their mobile devices.

With this data you can track the effectiveness of a wide range of campaigns — such as blogs, news articles, and ad campaigns — and get insight into which marketing activities are most effective for your business. You can find the Google Play report by going to Google Analytics and clicking on Acquisitions > Google Play > Referral Flow.

In the Developer Console, see engagement data from Google Analytics

If you’re already using Google Analytics, you know how important it is to see how users are interacting with your app. How often do they launch it? How much do they do with it? What are they doing inside the app?

Once you link your Analytics account, you’ll be able to see your app’s engagement data from Google Analytics right in the Statistics page in your Developer Console. You’ll be able to select two new metrics from the drop-down menu at the top of the page:

  • Active users: the number of users who have launched your app that day
  • New users: the number of users who have launched your app for the first time that day

These engagement metrics are integrated with your other app statistics, so you can analyze them further across other dimensions, such as by country, language, device, Android version, app version, and carrier.

How to get started

To get started, you first need to integrate Google Analytics into your app. If you haven’t done this already, download the Google Analytics SDK for Android and then take a look at the developer documentation to learn how to add Analytics to your app. Once you’ve integrated Analytics into your app, upload the app to the Developer Console.

Next, you’ll need to link your Developer Console to Google Analytics. To do this, go to the Developer Console and select the app. At the bottom of the Statistics page, you’ll see directions about how to complete the linking. The process takes just a few moments.

That’s it! You can now see both the Google Play Referral Flow report in Google Analytics and the new engagement metrics in the Developer Console.

Join the discussion on

+Android Developers
Categories: Programming

Google Play Services 4.2

Mon, 04/07/2014 - 04:27
gps

Google Play services 4.2 is now available on Android devices worldwide. It introduces the full release of the Google Cast SDK, for developing and publishing Google Cast-ready apps, and other new APIs.

You can get started developing today by downloading the Google Play services SDK from the SDK Manager.

Google Cast SDK

The Google Cast SDK makes it easy to bring your content to the TV. There’s no need to create a new app — just incorporate the SDK into your existing mobile and web apps. You are in control of how and when you publish your Google Cast-ready app to users through the Google Cast developer console.

You can find out more about the Cast SDK by reading Ready to Cast on the Google Developers Blog. For complete information about the Cast SDK and how to use the Cast APIs, see the Google Cast developer page.

Google Drive

The Google Drive API introduced in Google Play services 4.1 has graduated from developer preview. The latest version includes refinements to the API as well as improvements for performance and stability.

Google client API

This release introduces a new Google API client that unifies the connection model across Google services. Instead of needing to work with separate client classes for each API you wanted to use, you can now work with a single client API model. This makes it easier to build Google services into your apps and provides a more continuous user experience when you are using multiple services.

For an introduction to the new Google client API and what it means for your app, start by reading New Client API in Google Play Services.

More About Google Play Services

To learn more about Google Play services and the APIs available to you through it, visit the Google Services area of the Android Developers site. Details on the APIs are available in the API reference.

For information about getting started with Google Play services APIs, see Set Up Google Play Services SDK

Join the discussion on

+Android Developers The latest release of Google Play services has begun rolling out to Android devices worldwide. It includes the full release of the Google Cast SDK, for developing and publishing Google Cast-ready apps.

Once the rollout is complete, you'll be able to download the Google Play services SDK using the SDK Manager and get started with the new APIs. Watch for more information coming soon.

-->
Categories: Programming

Unlocking the Power of Google for Your Games, at GDC

Mon, 04/07/2014 - 04:26

By Greg Hartrell, Google Play Games team

Today, everyone is a gamer — in fact, 3 in every 4 Android users are playing games, allowing developers to reach an unprecedented audience of players in an Android ecosystem that’s activated over one billion devices. This has helped Google Play Games — Google’s cross-platform game service and SDK for Android, iOS and the web (which lets you easily integrate features like achievements, leaderboards, multiplayer and cloud save into your games) — grow at tremendous speed. The momentum continues on Google Play, where four times more money was paid out to developers in 2013 than in 2012.

With the Game Developers Conference (GDC) this week, we announced a number of new features for Google Play Games and other Google products. As they launch over the coming weeks, these new services and tools will help you unlock the power of Google to take your games to the next level.

Power your game and get discovered

With game gifts, players in your games can send virtual in-game objects to anyone in their circles or through multiplayer search.

To help players get the most out of your games, Play Games will be expanding engagement and discovery options.

We'll be introducing game gifts, a new service that lets players send virtual in-game objects to anyone in their circles or through player search. The Play Games app now supports multiplayer invites directly, further helping players discover your game and keep them playing. And the Google Play Store will also feature 18 new game categories, making it easier for players to find games they'll love.

Tools to take your game to the next level

Further enhancing Google Play Game services, we're expanding multiplayer to support iOS, bringing turn-based and real-time multiplayer capabilities to both Android and iOS.

To further help with cross platform game development, we're updating our Play Games Unity Plug-in to support cross-platform multiplayer services, and introducing an early Play Games C++ SDK to support achievements and leaderboards.

In addition, we're launching enhanced Play Games statistics on the Google Play Developer Console, providing easy game analytics for Play Games adopters. Developers will gain a daily dashboard that visualizes player and engagement statistics for signed in users, including daily active users, retention analysis and achievement, and leaderboard performance.

Ad features to better optimize your business

Of course, once you build a great gaming experience, it's important to get rewarded for your work, which is why we'll also be introducing new features to the AdMob platform. We're making Google Analytics available directly in the AdMob interface, so you can gain deeper insights into how users are interacting with your app. Turning those insights into effective action is vital, so we're excited by the opportunities that in-app purchase ads will offer — enabling you to target users with specific promotions to buy items in your game. Advertising continues to be a core vehicle driving many game developers' success, so we're also bringing you new ways to optimize your ads to earn the most revenue.

Watch the Google Sessions at GDC

Check out the stream from our Google Developer Day sessions at GDC 2014. Learn more about how to reach and engage with hundreds of millions of users on Google Play, build Games that scale in the cloud, grow in-game advertising businesses with AdMob, track revenue with Google Analytics, as well as explore new gaming frontiers, like Glass.



Join the discussion on

+Android Developers
Categories: Programming

Android Wear Developer Preview Now Available

Sat, 04/05/2014 - 22:55

By Austin Robison, Android Wear team

Android Wear extends the Android platform to wearables. These small, powerful devices give users useful information just when they need it. Watches powered by Android Wear respond to spoken questions and commands to provide info and get stuff done. These new devices can help users reach their fitness goals and be their key to a multiscreen world.

We designed Android Wear to bring a common user experience and a consistent developer platform to this new generation of devices. We can’t wait to see what you will build.

Getting started

Your app’s notifications will already appear on Android wearables and starting today, you can sign up for the Android Wear Developer Preview. You can use the emulator provided to preview how your notifications will appear on both square and round Android wearables. The Developer Preview also includes new Android Wear APIs which will let you customize and extend your notifications to accept voice replies, feature additional pages, and stack with similar notifications. Head on over to developer.android.com/wear to sign up and learn more.

For a brief introduction to the developer features of Android Wear, check out these DevBytes videos. They include demos and a discussion about the code snippets driving them.

What’s next?

We’re just getting started with the Android Wear Developer Preview. In the coming months we’ll be launching new APIs and features for Android Wear devices to create even more unique experiences for the wrist.

Join the Android Wear Developers community on Google+ to discuss the Preview and ask questions.

We’re excited to see what you build!

Join the discussion on

+Android Developers
Categories: Programming

Join us at Game Developers Conference 2014!

Mon, 03/24/2014 - 00:49

By Greg Hartrell, Google Play Games team

When we’re not guiding a tiny bird across a landscape of pipes on our phones, we’re getting ready for our biggest-ever Developer Day at this year’s Game Developers Conference in San Francisco.

On Tuesday 18 March, all the teams at Google dedicated to gaming will share their insights on the best ways to build games, grow audiences, engage players and make money.

Some of the session highlights include:

  • Growth Hacking with Play Games
  • Making Money on Google Play: Best Practices in Monetization
  • Grow Your Game Revenue with AdMob
  • From Players to Customers: Tracking Revenue with Google Analytics
  • Build Games that Scale in the Cloud
  • From Box2D to Liquid Fun: Just Add Water-like Particles!

And there’s a lot more, so check out the full Google Developer Day schedule on the GDC website, where you can also buy tickets. We hope to see you there, but if you can’t make the trip, don’t worry; all the talks will be livestreamed on YouTube, starting at 10:00AM PDT (5:00PM UTC).

Then from 19-21 March, meet the Google teams in person from AdMob, Analytics, and Cloud at the Google Education Center in the Moscone Center’s South Hall (booth 218), and you could win a Nexus 7.

Join the discussion on

+Android Developers
Categories: Programming

Google Developer Day at GDC

Tue, 03/18/2014 - 16:32

Day 2 of Game Developers Conference 2014 is getting underway and today Google is hosting a special Developer Day at Moscone Center in San Francisco.

Join us at the sessions

Building on yesterday’s announcements for game developers, we'll be presenting a series of sessions that walk you through the new features, services, and tools, explaining how they work and what they can bring to your games.

We'll also be talking with you about how to reach and engage with hundreds of millions of users on Google Play, build Games that scale in the cloud, grow in-game advertising businesses with AdMob, track revenue with Google Analytics, as well as explore new gaming frontiers, like Glass.

If you’re at the conference, the Google Developer Day sessions are a great opportunity to meet the developer advocates, engineers, and product managers of the Google products that drive users, engagement and retention for your games. If you’re remote, we invite you to sit-in on the sessions by joining the livestream below or on Google Developers channel on YouTube.

The Developer Day sessions (and livestream) kick off at 10:00AM PDT (5:00PM UTC). A complete agenda is available on the GDC Developer Day page.



LiquidFun 1.0

Last December we announced the initial release of LiquidFun, a C++ library that adds particle physics, including realistic fluid dynamics, to the open-source Box2D.

To get Google Developer Day started, we’re releasing LiquidFun 1.0, an update that adds multiple particle systems, new particle behaviors, and other new features.

Check out the video below to see what Liquid Fun 1.0 can do, visit the LiquidFun home page, or join today's LiquidFun session at Google Developer Day to learn how LiquidFun works and how to use particle physics in your games. The session starts at 4:35PM PDT (11:35PM UTC).



Join the discussion on

+Android Developers
Categories: Programming

RenderScript in the Android Support Library

Sun, 03/16/2014 - 00:05
p.note { border-color: #258AAF; } p.note, div.note, p.caution, div.caution, p.warning, div.warning { padding: 0 0 0 10px; border-left: 4px solid; } Renderscript Support library on devices

The RenderScript Support Library lets you take advantage of the latest RenderScript features on devices running Android 2.2 and later.

Posted by Tim Murray, Android RenderScript team

One of the requests we hear most commonly from developers is to enable more devices to run the latest features of RenderScript. Over the past several releases of Android, we’ve added a ton of functionality to the RenderScript runtime, but the runtime's dependence on the core Android platform version has limited the range of devices that can support that new functionality. We’ve been working on a solution to this since last year, and we’re now ready to share it with all Android developers.

Today we're announcing a new RenderScript Support Library and updated SDK tools that together let you take advantage of RenderScript on plaform versions all the way back to Android 2.2 (Froyo).

With ADT v22.2, SDK Tools v22.2, and Android Build Tools v18.1.0, apps targeting Android 2.2 and later can now make use of almost all of the functionality available natively in RenderScript with Android 4.3. This includes access to the newest RenderScript features such as high-performance intrinsics and the new performance optimizations available to scripts.

Using the RenderScript Support Library

Using the RenderScript Support Library is straightforward. Once you've updated ADT and your SDK tools, there are only two things that you have to do to start using Renderscript in your apps:

  1. In your classes that use RenderScript, import the RenderScript Support Library from android.support.v8.renderscript. If you are already using native RenderScript, you can change your import from android.renderscript to android.support.v8.renderscript.
    import android.support.v8.renderscript.*;
  2. In your project.properties, make sure you’re targeting android-18 and add the following lines:
    renderscript.target=18
    renderscript.support.mode=true
    sdk.buildtools=18.1.0

That’s it! With the RenderScript Support Library, you can continue to use the same APIs from your app as with the native RenderScript package (with a few minor exceptions that we’ll talk about below), and you can use the same features in your own scripts as you would with the latest RenderScript toolchain.

For complete details on how to set up the RenderScript Support Library, see Accessing RenderScript Java APIs.

API and Implementation details

If you'd like to use RenderScript Support Library in your app, there are few things you should know:

  • First, the RenderScript Support Library supports almost all of the RenderScript API functions as the native API that's available in API level and higher. The one notable exception is that Allocation.USAGE_IO_INPUT and Allocation.USAGE_IO_OUTPUT are not currently available in the RenderScript Support Library.
  • Second, devices running Android 4.2 and earlier will always run their RenderScript applications on the CPU, while devices running Android 4.3 or later will run their RenderScript applications on whatever processors are available on that particular device. Because the Support Library versions of the scripts have to be precompiled to support all possible platforms, there is a performance hit when running the precompiled scripts compared to runtime compilation on Android 4.3 due to more restrictions on compiler optimizations.

We’re really pleased with how the RenderScript Support Library has turned out. We've already seen how it performs in a shipping app — it's been part of the photo editor in the Google+ Android app since May 2013, and it’s definitely proven itself in a large and widely used application. We hope you’ll be happy with it too.

Join the discussion on

+Android Developers
Categories: Programming

Process Stats: Understanding How Your App Uses RAM

Thu, 02/27/2014 - 03:48

Posted by Dianne Hackborn, Android framework team

Android 4.4 KitKat introduced a new system service called procstats that helps you better understand how your app is using the RAM resources on a device. Procstats makes it possible to see how your app is behaving over time — including how long it runs in the background and how much memory it uses during that time. It helps you quickly find inefficiencies and misbehaviors in your app that can affect how it performs, especially when running on low-RAM devices.

You can access procstats data using an adb shell command, but for convenience there is also a new Process Stats developer tool that provides a graphical front-end to that same data. You can find Process Stats in Settings > Developer options > Process Stats.

In this post we’ll first take a look at the Process Stats graphical tool, then dig into the details of the memory data behind it, how it's collected, and why it's so useful to you as you analyze your app.

Process Stats overview of memory used by background processes over time.

Looking at systemwide memory use and background processes

When you open Process Stats, you see a summary of systemwide memory conditions and details on how processes are using memory over time. The image at right gives you an example of what you might see on a typical device.

At the top of the screen we can see that:

  • We are looking at that data collected over the last ~3.5 hours.
  • Currently the device’s RAM is in good shape ("Device memory is currently normal").
  • During that entire time the memory state has been good — this is shown by the green bar. If device memory was getting low, you would see yellow and red regions on the left of the bar representing the amount of total time with low memory.

Below the green bar, we can see an overview of the processes running in the background and the memory load they've put on the system:

  • The percentage numbers on the right indicate the amount of time each process has spent running during the total duration.
  • The blue bars indicate the relative computed memory load of each process. (The memory load is runtime*avg_pss, which we will go into more detail on later.)
  • Some apps may be listed multiple times, since what is being shown is processes (for example, Google Play services runs in two processes). The memory load of these apps is the sum of the load of their individual processes.
  • There are a few processes at the top that have all been running for 100% of the time, but with different weights because of their relative memory use.
Analyzing memory for specific processes

The example shows some interesting data: we have a Clock app with a higher memory weight than Google Keyboard, even though it ran for less than half the time. We can dig into the details of these processes just by tapping on them:

Process Stats memory details for Clock and Keyboard processes over the past 3.5 hours.

The details for these two processes reveal that:

  • The reason that Clock has been running at all is because it is being used as the current screen saver when the device is idle.
  • Even though the Clock process ran for less than half the time of the Keyboard, its ram use was significantly larger (almost 3x), which is why its overall weight is larger.

Essentially, procstats provides a “memory use” gauge that's much like the storage use or data use gauges, showing how much RAM the apps running in the background are using. Unlike with storage or data, though, memory use is much harder to quantify and measure, and procstats uses some tricks to do so. To illustrate the complexity of measuring memory use, consider a related topic: task managers.

Understanding task managers and their memory info

We’ve had a long history of task managers on Android. Android has always deeply supported multitasking, which means the geeky of us will tend to want to have some kind of UI for seeing and controlling this multitasking like the traditional UI we are used to from the desktop. However, multitasking on Android is actually quite a bit more complicated and fundamentally different than on a traditional desktop operating system, as I previously covered in Multitasking the Android Way. This deeply impacts how we can show it to the user.

Multitasking and continuous process management

To get a feel for just how different process management is on Android, you can take a look at the output of an important system service, the activity manager, with adb shell dumpsys activity. The example below shows a snapshot of current application processes on Android 4.4, listing them from most important to least:

ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)
Process LRU list (sorted by oom_adj, 22 total, non-act at 2, non-svc at 2):
  PERS #21: sys   F/ /P  trm: 0 23064:system/1000 (fixed)
  PERS #20: pers  F/ /P  trm: 0 23163:com.android.systemui/u0a12 (fixed)
  PERS #19: pers  F/ /P  trm: 0 23344:com.nuance.xt9.input/u0a77 (fixed)
  PERS #18: pers  F/ /P  trm: 0 23357:com.android.phone/1001 (fixed)
  PERS #17: pers  F/ /P  trm: 0 23371:com.android.nfc/1027 (fixed)
  Proc # 3: fore  F/ /IB trm: 0 13892:com.google.android.apps.magazines/u0a59 (service)
    com.google.android.apps.magazines/com.google.apps.dots.android.app.service.SyncService<=Proc{23064:system/1000}
  Proc # 2: fore  F/ /IB trm: 0 23513:com.google.process.gapps/u0a8 (provider)
    com.google.android.gsf/.gservices.GservicesProvider<=Proc{13892:com.google.android.apps.magazines/u0a59}
  Proc # 0: fore  F/A/T  trm: 0 24811:com.android.settings/1000 (top-activity)
  Proc # 4: vis   F/ /IF trm: 0 23472:com.google.process.location/u0a8 (service)
    com.google.android.backup/.BackupTransportService<=Proc{23064:system/1000}
  Proc #14: prcp  F/ /IF trm: 0 23298:com.google.android.inputmethod.latin/u0a57 (service)
    com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME<=Proc{23064:system/1000}
  Proc # 1: home  B/ /HO trm: 0 23395:com.android.launcher/u0a13 (home)
  Proc #16: cch   B/ /CA trm: 0 23966:com.google.android.deskclock/u0a36 (cch-act)
  Proc # 6: cch   B/ /CE trm: 0 7716:com.google.android.music:main/u0a62 (cch-empty)
  Proc # 5: cch   B/ /CE trm: 0 8644:com.google.android.apps.docs/u0a39 (cch-empty)
  Proc # 8: cch+2 B/ /CE trm: 0 5131:com.google.android.youtube/u0a78 (cch-empty)
  Proc # 7: cch+2 B/ /CE trm: 0 23338:com.google.android.gms/u0a8 (cch-empty)
  Proc #10: cch+4 B/ /CE trm: 0 8937:com.google.android.apps.walletnfcrel/u0a24 (cch-empty)
  Proc # 9: cch+4 B/ /CE trm: 0 24689:com.google.android.apps.plus/u0a70 (cch-empty)
  Proc #15: cch+6 B/ /S  trm: 0 23767:com.google.android.apps.currents/u0a35 (cch-started-services)
  Proc #13: cch+6 B/ /CE trm: 0 9115:com.google.android.gm/u0a44 (cch-empty)
  Proc #12: cch+6 B/ /S  trm: 0 7738:android.process.media/u0a6 (cch-started-services)
  Proc #11: cch+6 B/ /CE trm: 0 8922:com.google.android.setupwizard/u0a19 (cch-empty)

Example output of dumpsys activity command, showing all processes currently running.

There are a few major groups of processes here — persistent system processes, the foreground processes, background processes, and finally cached processes — and the category of a process is extremely important for understanding its impact on the system.

At the same time, processes on this list change all of the time. For example, in the snapshot above we can see that “com.google.android.gm” is currently an important process, but that is because it is doing a background sync, something the user would not generally be aware of or want to manage.

Snapshotting per-process RAM use

The traditional use of a task manager is closely tied to RAM use, and Android provides a tool called meminfo for looking at a snapshot of current per-process RAM use. You can access it with the command adb shell dumpsys meminfo. Here's an example of the output.

Total PSS by OOM adjustment:
    31841 kB: Native
               13173 kB: zygote (pid 23001)
                4372 kB: surfaceflinger (pid 23000)
                3721 kB: mediaserver (pid 126)
                3317 kB: glgps (pid 22993)
                1656 kB: drmserver (pid 125)
                 995 kB: wpa_supplicant (pid 23148)
                 786 kB: netd (pid 121)
                 518 kB: sdcard (pid 132)
                 475 kB: vold (pid 119)
                 458 kB: keystore (pid 128)
                 448 kB: /init (pid 1)
                 412 kB: adbd (pid 134)
                 254 kB: ueventd (pid 108)
                 238 kB: dhcpcd (pid 10617)
                 229 kB: tf_daemon (pid 130)
                 200 kB: installd (pid 127)
                 185 kB: dumpsys (pid 14207)
                 144 kB: healthd (pid 117)
                 139 kB: debuggerd (pid 122)
                 121 kB: servicemanager (pid 118)
    48217 kB: System
               48217 kB: system (pid 23064)
    49095 kB: Persistent
               34012 kB: com.android.systemui (pid 23163 / activities)
                7719 kB: com.android.phone (pid 23357)
                4676 kB: com.android.nfc (pid 23371)
                2688 kB: com.nuance.xt9.input (pid 23344)
    24945 kB: Foreground
               24945 kB: com.android.settings (pid 24811 / activities)
    17136 kB: Visible
               14026 kB: com.google.process.location (pid 23472)
                3110 kB: com.android.defcontainer (pid 13976)
     6911 kB: Perceptible
                6911 kB: com.google.android.inputmethod.latin (pid 23298)
    14277 kB: A Services
               14277 kB: com.google.process.gapps (pid 23513)
    26422 kB: Home
               26422 kB: com.android.launcher (pid 23395 / activities)
    21798 kB: B Services
               16242 kB: com.google.android.apps.currents (pid 23767)
                5556 kB: android.process.media (pid 7738)
   145869 kB: Cached
               41588 kB: com.google.android.apps.plus (pid 24689)
               21417 kB: com.google.android.deskclock (pid 23966 / activities)
               14463 kB: com.google.android.apps.docs (pid 8644)
               14303 kB: com.google.android.gm (pid 9115)
               11014 kB: com.google.android.music:main (pid 7716)
               10688 kB: com.google.android.apps.magazines (pid 13892)
               10240 kB: com.google.android.gms (pid 23338)
                9882 kB: com.google.android.youtube (pid 5131)
                8807 kB: com.google.android.apps.walletnfcrel (pid 8937)
                3467 kB: com.google.android.setupwizard (pid 8922)

Total RAM: 998096 kB
 Free RAM: 574945 kB (145869 cached pss + 393200 cached + 35876 free)
 Used RAM: 392334 kB (240642 used pss + 107196 buffers + 3856 shmem + 40640 slab)
 Lost RAM: 30817 kB
   Tuning: 64 (large 384), oom 122880 kB, restore limit 40960 kB (high-end-gfx)

Example output of dumpsys meminfo command, showing memory currently used by running processes.

We are now looking at the same processes as above, again organized by importance, but now with on their impact on RAM use.

Usually when we measure RAM use in Android, we do this with Linux’s PSS (Proportional Set Size) metric. This is the amount of RAM actually mapped into the process, but weighted by the amount it is shared across processes. So if there is a 4K page of RAM mapped in to two processes, its PSS amount for each process would be 2K.

The nice thing about using PSS is that you can add up this value across all processes to determine the actual total RAM use. This characteristic is used at the end of the meminfo report to compute how much RAM is in use (which comes in part from all non-cached processes), versus how much is "free" (which includes cached processes).

Task-manager style memory info, showing a snapshot of memory used by running apps.

Task manager UI based on PSS snapshot

Given the information we have so far, we can imagine various ways to present this in a somewhat traditional task manager UI. In fact, the UI you see in Settings > Apps > Running is derived from this information. It shows all processes running services (“svc” adjustment in the LRU list) and on behalf of the system (the processes with a “<=Proc{489:system/1000}” dependency), computing the PSS RAM for each of these and any other processes they have dependencies on.

The problem with visualizing memory use in this way is that it gives you the instantaneous state of the apps, without context over time. On Android, users don’t directly control the creation and removal of application processes — they may be kept for future use, removed when the system decides, or run in the background without the user explicitly launching them. So looking only at the instantaneous state of memory use only, you would be missing important information about what is actually going on over time.

For example, in our first look at the process state we see the com.google.android.apps.magazines process running for a sync, but when we collected the RAM use right after that it was no longer running in the background but just being kept around as an old cached process.

To address this problem, the new procstats tool continually monitors the state of all application processes over time, aggregating that information and collecting PSS samples from those processes while doing so. You can view the raw data being collected by procstats with the command adb shell dumpsys procstats.

Seeing memory use over time with procstats

Let’s now go back to procstats and take a look at the context it provides by showing memory use over time. We can use the command adb shell dumpsys procstats --hours 3 to output memory information collected over the last 3 hours. This is the same data as represented graphically in the first Process Stats example.

The output shows all of the processes that have run in the last 3 hours, sorted with the ones running the most first. (Processes in a cached state don’t count for the total time in this sort.) Like the initial graphical representation, we now clearly see a big group of processes that run all of the time, and then some that run occasionally — this includes the Magazines process, which we can now see ran for 3.6% of the time over the last 3 hours.

  * com.google.android.inputmethod.latin / u0a57:
           TOTAL: 100% (6.4MB-6.7MB-6.8MB/5.4MB-5.4MB-5.4MB over 21)
          Imp Fg: 100% (6.4MB-6.7MB-6.8MB/5.4MB-5.4MB-5.4MB over 21)
  * com.google.process.gapps / u0a8:
           TOTAL: 100% (12MB-13MB-14MB/10MB-11MB-12MB over 211)
          Imp Fg: 0.11%
          Imp Bg: 0.83% (13MB-13MB-13MB/11MB-11MB-11MB over 1)
         Service: 99% (12MB-13MB-14MB/10MB-11MB-12MB over 210)
  * com.android.systemui / u0a12:
           TOTAL: 100% (29MB-32MB-34MB/26MB-29MB-30MB over 21)
      Persistent: 100% (29MB-32MB-34MB/26MB-29MB-30MB over 21)
  * com.android.phone / 1001:
           TOTAL: 100% (6.5MB-7.1MB-7.6MB/5.4MB-5.9MB-6.4MB over 21)
      Persistent: 100% (6.5MB-7.1MB-7.6MB/5.4MB-5.9MB-6.4MB over 21)
  * com.nuance.xt9.input / u0a77:
           TOTAL: 100% (2.3MB-2.5MB-2.7MB/1.5MB-1.5MB-1.5MB over 21)
      Persistent: 100% (2.3MB-2.5MB-2.7MB/1.5MB-1.5MB-1.5MB over 21)
  * com.android.nfc / 1027:
           TOTAL: 100% (4.2MB-4.5MB-4.6MB/3.2MB-3.2MB-3.3MB over 21)
      Persistent: 100% (4.2MB-4.5MB-4.6MB/3.2MB-3.2MB-3.3MB over 21)
  * com.google.process.location / u0a8:
           TOTAL: 100% (13MB-13MB-14MB/10MB-11MB-11MB over 21)
          Imp Fg: 100% (13MB-13MB-14MB/10MB-11MB-11MB over 21)
  * system / 1000:
           TOTAL: 100% (42MB-46MB-56MB/39MB-42MB-48MB over 21)
      Persistent: 100% (42MB-46MB-56MB/39MB-42MB-48MB over 21)
  * com.google.android.apps.currents / u0a35:
           TOTAL: 100% (16MB-16MB-16MB/14MB-14MB-14MB over 17)
         Service: 100% (16MB-16MB-16MB/14MB-14MB-14MB over 17)
  * com.android.launcher / u0a13:
           TOTAL: 77% (25MB-26MB-27MB/22MB-23MB-24MB over 73)
             Top: 77% (25MB-26MB-27MB/22MB-23MB-24MB over 73)
          (Home): 23% (25MB-26MB-26MB/23MB-23MB-24MB over 12)
  * android.process.media / u0a6:
           TOTAL: 48% (5.0MB-5.3MB-5.5MB/4.0MB-4.2MB-4.2MB over 11)
          Imp Fg: 0.00%
          Imp Bg: 0.00%
         Service: 48% (5.0MB-5.3MB-5.5MB/4.0MB-4.2MB-4.2MB over 11)
        Receiver: 0.00%
        (Cached): 22% (4.1MB-4.5MB-4.8MB/3.0MB-3.5MB-3.8MB over 8)
  * com.google.android.deskclock / u0a36:
           TOTAL: 42% (20MB-21MB-21MB/18MB-19MB-19MB over 8)
          Imp Fg: 42% (20MB-21MB-21MB/18MB-19MB-19MB over 8)
         Service: 0.00%
        Receiver: 0.01%
        (Cached): 58% (17MB-20MB-21MB/16MB-18MB-19MB over 14)
  * com.android.settings / 1000:
           TOTAL: 23% (19MB-22MB-28MB/15MB-19MB-24MB over 31)
             Top: 23% (19MB-22MB-28MB/15MB-19MB-24MB over 31)
      (Last Act): 77% (9.7MB-14MB-20MB/7.5MB-11MB-18MB over 8)
        (Cached): 0.02%
  * com.google.android.apps.magazines / u0a59:
           TOTAL: 3.6% (10MB-10MB-10MB/8.7MB-9.0MB-9.0MB over 6)
          Imp Bg: 0.03%
         Service: 3.6% (10MB-10MB-10MB/8.7MB-9.0MB-9.0MB over 6)
        (Cached): 17% (9.9MB-10MB-10MB/8.7MB-8.9MB-9.0MB over 5)
  * com.android.defcontainer / u0a5:
           TOTAL: 1.4% (2.7MB-3.0MB-3.0MB/1.9MB-1.9MB-1.9MB over 7)
             Top: 1.2% (3.0MB-3.0MB-3.0MB/1.9MB-1.9MB-1.9MB over 6)
          Imp Fg: 0.19% (2.7MB-2.7MB-2.7MB/1.9MB-1.9MB-1.9MB over 1)
         Service: 0.00%
        (Cached): 15% (2.6MB-2.6MB-2.6MB/1.8MB-1.8MB-1.8MB over 1)
  * com.google.android.youtube / u0a78:
           TOTAL: 1.3% (9.0MB-9.0MB-9.0MB/7.8MB-7.8MB-7.8MB over 1)
          Imp Bg: 1.0% (9.0MB-9.0MB-9.0MB/7.8MB-7.8MB-7.8MB over 1)
         Service: 0.27%
      Service Rs: 0.01%
        Receiver: 0.00%
        (Cached): 99% (9.1MB-9.4MB-9.7MB/7.7MB-7.9MB-8.1MB over 24)
  * com.google.android.gms / u0a8:
           TOTAL: 0.91% (9.2MB-9.2MB-9.2MB/7.6MB-7.6MB-7.6MB over 1)
          Imp Bg: 0.79% (9.2MB-9.2MB-9.2MB/7.6MB-7.6MB-7.6MB over 1)
         Service: 0.11%
        Receiver: 0.00%
        (Cached): 99% (8.2MB-9.4MB-10MB/6.5MB-7.6MB-8.1MB over 25)
  * com.google.android.gm / u0a44:
           TOTAL: 0.56%
          Imp Bg: 0.55%
         Service: 0.01%
        Receiver: 0.00%
        (Cached): 99% (11MB-13MB-14MB/10MB-12MB-13MB over 24)
  * com.google.android.apps.plus / u0a70:
           TOTAL: 0.22%
          Imp Bg: 0.22%
         Service: 0.00%
        Receiver: 0.00%
        (Cached): 100% (38MB-40MB-41MB/36MB-38MB-39MB over 17)
  * com.google.android.apps.docs / u0a39:
           TOTAL: 0.15%
          Imp Bg: 0.09%
         Service: 0.06%
        (Cached): 54% (13MB-14MB-14MB/12MB-12MB-13MB over 17)
  * com.google.android.music:main / u0a62:
           TOTAL: 0.11%
          Imp Bg: 0.04%
         Service: 0.06%
        Receiver: 0.01%
        (Cached): 70% (7.7MB-10MB-11MB/6.4MB-9.0MB-9.3MB over 20)
  * com.google.android.apps.walletnfcrel / u0a24:
           TOTAL: 0.01%
        Receiver: 0.01%
        (Cached): 69% (8.1MB-8.4MB-8.6MB/7.0MB-7.1MB-7.1MB over 13)
  * com.google.android.setupwizard / u0a19:
           TOTAL: 0.00%
        Receiver: 0.00%
        (Cached): 69% (2.7MB-3.2MB-3.4MB/1.8MB-2.0MB-2.2MB over 13)

Run time Stats:
  SOff/Norm: +1h43m29s710ms
  SOn /Norm: +1h37m14s290ms
      TOTAL: +3h20m44s0ms

          Start time: 2013-11-06 07:24:27
  Total elapsed time: +3h42m23s56ms (partial) libdvm.so chromeview

Example output of dumpsys procstats --hours 3 command, showing memory details for processes running in the background over the past ~3 hours.

The percentages tell you how much of the overall time each process has spent in various key states. The memory numbers tell you about memory samples in those states, as minPss-avgPss-maxPss / minUss-avgUss-maxUss. The procstats tool also has a number of command line options to control its output — use adb shell dumpsys procstats -h to see a list of the available options.

Comparing this raw data from procstats with the visualization of its data we previously saw, we can see that it is showing only process run data from a subset of states: Imp Fg, Imp Bg, Service, Service Rs, and Receiver. These are the situations where the process is actively running in the background, for as long as it needs to complete the work it is doing. In terms of device memory use, these are the process states that tend to cause the most trouble: apps running in the background taking RAM from other things.

Getting started with procstats

We have already found the new procstats tool to be invaluable in better understanding the overall memory behavior of Android systems, and it has been a key part of the Project Svelte effort in Android 4.4.

As you develop your own applications, be sure to use procstats and the other tools mentioned here to help understand how your own app is behaving, especially how much it runs in the background and how much RAM it uses during that time.

More information about how to analyze and debug RAM use on Android is available on the developer page Investigating Your RAM Usage.

Join the discussion on

+Android Developers
Categories: Programming

Unlocking More Users, with Tablets and Games

Sun, 02/23/2014 - 02:50

Posted by Purnima Kochikar, Director of Business Development, Games & Applications

Last week, we unveiled a number of new things in the world of Android. And while we already showcased the new tools available at your disposal in Android 4.3, we also unveiled a new Nexus 7 tablet, as well as the Google Play Games app, both of which represent opportunities to take advantage of a growing number of users.

Nexus 7 and the Android tablet revolution

If you’re a developer optimizing your app for Android tablets, no doubt you’re familiar with the original Nexus 7. It was Google’s statement on what a great Android tablet experience should look like, and since then, the Android tablet ecosystem has come a long way. There have already been more than 70 million activations of Android tablets, with more than 1 in 2 tablets sold today running Android. We’re starting to see with Android tablets what could be the hockey stick growth all of us experienced a couple of years ago with Android smartphones, and we hope that the new Nexus 7 continues to fuel this growth even further.

Most top developers on Android have already prepared their applications for this wave of new Android tablet users, including many of the essentials, like the New York Times, Zappos, Evernote, Flipboard, Pinterest and more. To help users find your tablet-designed apps more easily on Google Play, you can now choose to only see apps designed for tablets in the top lists. There are also over 50 new collections, which highlight outstanding tablet apps.

To take advantage of the Android tablet revolution, check out our Tablet App Quality Checklist, which has tips and techniques on how to deliver a great app experience for tablet users. It details all of the key things you need to do to optimize your app for tablets, like taking advantage of the extra screen real estate and adjusting font sizes and touch targets, to things you can do on the distribution side, like declaring support for tablet screens and showcasing your tablet UI on Google Play by uploading tablet-specific screenshots. Optimizing your app for Android tablets will unlock a whole new group of users, like those who are about to receive their new Nexus 7 tablets.

Taking your game to the next level

The Android games category on Google Play is on fire; in fact, the vast majority of top mobile game developers are building Android tablet games, and most new titles launch immediately on Android. To help game developers take advantage of the next generation of games, at Google I/O in May, we introduced Google Play game services, our gaming platform for Android, iOS, and the web. By building on Google’s strengths in mobile and cloud services, Google Play game services allows game developers to focus on what they’re good at: creating great gaming experiences for their users.

Turbocharging that growth even more, on Wednesday we introduced the Google Play Games app, which brings your friends together with the games you love, where you can invite a friend and start challenging gamers around the world, compete for top achievements, and race to the top of the leaderboard.

Since the launch at Google I/O, just over two months ago, over one thousand games have added Google Play game services, with millions of users enjoying features like leaderboards and multiplayer inside of the games they love. Some of those early developers using Google Play game services are reporting incredible upticks in vital engagement metrics; for instance, Concrete Software is seeing session length up 15%, and Glu is reporting a 40% increase in 7-day user retention.

Here are a few things you can do to take your game to the next level with Google Play:

  • Integrate with Play Games using achievements and leaderboards to activate your players.
  • Add real-time multiplayer to competitive and cooperative games and increase engagement.
  • Use Play Games branding guidelines and create rich visuals that bolster your presence in the Google Play Games app.

Whether it be getting your app ready for the wave of new Android tablets that are lighting up each day, or opening up a whole new set of features for your users with Google Play game services, a great Android experience starts with a great app or game. That’s why we’re working hard to help provide you with the tools and features needed to create those great experiences for your users, and to help you reach as many of them as possible in the process, with Google Play.

Join the discussion on

+Android Developers
Categories: Programming

Respecting Audio Focus

Sun, 02/23/2014 - 02:49
table { border-collapse: collapse; border-spacing: 0; border:0; margin: .5em 1em 1em 0; width:100%; /* consistent table widths; within IE's quirks */ background-color:#f7f7f7; } th, td { padding: 4px 12px; vertical-align: top; text-align: left; } td { background-color:inherit; border:solid 1px #DDD; } td *:last-child { margin-bottom:0; } th { background-color: #999; color: #fff; border:solid 1px #DDD; font-weight: normal; } tr:first-of-type th:first-of-type:empty { visibility: hidden; } p.note { border-color: #258AAF; } p.note, div.note, p.caution, div.caution, p.warning, div.warning { padding: 0 0 0 10px; border-left: 4px solid; }

Posted by Kristan Uccello, Google Developer Relations

It’s rude to talk during a presentation, it disrespects the speaker and annoys the audience. If your application doesn’t respect the rules of audio focus then it’s disrespecting other applications and annoying the user. If you have never heard of audio focus you should take a look at the Android developer training material.

With multiple apps potentially playing audio it's important to think about how they should interact. To avoid every music app playing at the same time, Android uses audio focus to moderate audio playback—your app should only play audio when it holds audio focus. This post provides some tips on how to handle changes in audio focus properly, to ensure the best possible experience for the user.

Requesting audio focus

Audio focus should not be requested when your application starts (don’t get greedy), instead delay requesting it until your application is about to do something with an audio stream. By requesting audio focus through the AudioManager system service, an application can use one of the AUDIOFOCUS_GAIN* constants (see Table 1) to indicate the desired level of focus.

Listing 1. Requesting audio focus.

1. AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
2.     
3.  int result = am.requestAudioFocus(mOnAudioFocusChangeListener,
4.    // Hint: the music stream.
5.    AudioManager.STREAM_MUSIC,
6.    // Request permanent focus.
7.    AudioManager.AUDIOFOCUS_GAIN);
8.  if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
9.    mState.audioFocusGranted = true;
10. } else if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
11.   mState.audioFocusGranted = false;
12. }

In line 7 above, you can see that we have requested permanent audio focus. An application could instead request transient focus using AUDIOFOCUS_GAIN_TRANSIENT which is appropriate when using the audio system for less than 45 seconds.

Alternatively, the app could use AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK, which is appropriate when the use of the audio system may be shared with another application that is currently playing audio (e.g. for playing a "keep it up" prompt in a fitness application and expecting background music to duck during the prompt). The app requesting AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK should not use the audio system for more than 15 seconds before releasing focus.

Handling audio focus changes

In order to handle audio focus change events, an application should create an instance of OnAudioFocusChangeListener. In the listener, the application will need to handle theAUDIOFOCUS_GAIN* event and AUDIOFOCUS_LOSS* events (see Table 1). It should be noted that AUDIOFOCUS_GAIN has some nuances which are highlighted in Listing 2, below.

Listing 2. Handling audio focus changes.

1. mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {  
2.   
3. @Override
4. public void onAudioFocusChange(int focusChange) {
5.   switch (focusChange) {
6.   case AudioManager.AUDIOFOCUS_GAIN:
7.     mState.audioFocusGranted = true;
8.        
9.     if(mState.released) {
10.   initializeMediaPlayer();
11.    }
12.
13.    switch(mState.lastKnownAudioFocusState) {
14.    case UNKNOWN:
15.      if(mState.state == PlayState.PLAY && !mPlayer.isPlaying()) {
16.        mPlayer.start();
17.      }
18.      break;
19.    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
20.      if(mState.wasPlayingWhenTransientLoss) {
21.        mPlayer.start();
22.      }
23.      break;
24.    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
25.      restoreVolume();
26.      break;
27.    }
28.        
29.    break;
30.  case AudioManager.AUDIOFOCUS_LOSS:
31.    mState.userInitiatedState = false;
32.    mState.audioFocusGranted = false;
33.    teardown();
34.    break;
35.  case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
36.    mState.userInitiatedState = false;
37.    mState.audioFocusGranted = false;
38.    mState.wasPlayingWhenTransientLoss = mPlayer.isPlaying();
39.    mPlayer.pause();
40.    break;
41.  case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
42.   mState.userInitiatedState = false;
43.   mState.audioFocusGranted = false;
44.   lowerVolume();
45.   break;
46.  }
47.  mState.lastKnownAudioFocusState = focusChange;
48.  }
49.};

AUDIOFOCUS_GAIN is used in two distinct scopes of an applications code. First, it can be used when registering for audio focus as shown in Listing 1. This does NOT translate to an event for the registered OnAudioFocusChangeListener, meaning that on a successful audio focus request the listener will NOT receive an AUDIOFOCUS_GAIN event for the registration.

AUDIOFOCUS_GAIN is also used in the implementation of an OnAudioFocusChangeListener as an event condition. As stated above, the AUDIOFOCUS_GAIN event will not be triggered on audio focus requests. Instead the AUDIOFOCUS_GAIN event will occur only after an AUDIOFOCUS_LOSS* event has occurred. This is the only constant in the set shown Table 1 that is used in both scopes.

There are four cases that need to be handled by the focus change listener. When the application receives an AUDIOFOCUS_LOSS this usually means it will not be getting its focus back. In this case the app should release assets associated with the audio system and stop playback. As an example, imagine a user is playing music using an app and then launches a game which takes audio focus away from the music app. There is no predictable time for when the user will exit the game. More likely, the user will navigate to the home launcher (leaving the game in the background) and launch yet another application or return to the music app causing a resume which would then request audio focus again.

However another case exists that warrants some discussion. There is a difference between losing audio focus permanently (as described above) and temporarily. When an application receives an AUDIOFOCUS_LOSS_TRANSIENT, the behavior of the app should be that it suspends its use of the audio system until it receives an AUDIOFOCUS_GAIN event. When the AUDIOFOCUS_LOSS_TRANSIENT occurs, the application should make a note that the loss is temporary, that way on audio focus gain it can reason about what the correct behavior should be (see lines 13-27 of Listing 2).

Sometimes an app loses audio focus (receives an AUDIOFOCUS_LOSS) and the interrupting application terminates or otherwise abandons audio focus. In this case the last application that had audio focus may receive an AUDIOFOCUS_GAIN event. On the subsequent AUDIOFOCUS_GAIN event the app should check and see if it is receiving the gain after a temporary loss and can thus resume use of the audio system or if recovering from an permanent loss, setup for playback.

If an application will only be using the audio capabilities for a short time (less than 45 seconds), it should use an AUDIOFOCUS_GAIN_TRANSIENT focus request and abandon focus after it has completed its playback or capture. Audio focus is handled as a stack on the system — as such the last process to request audio focus wins.

When audio focus has been gained this is the appropriate time to create a MediaPlayer or MediaRecorder instance and allocate resources. Likewise when an app receives AUDIOFOCUS_LOSS it is good practice to clean up any resources allocated. Gaining audio focus has three possibilities that also correspond to the three audio focus loss cases in Table 1. It is a good practice to always explicitly handle all the loss cases in the OnAudioFocusChangeListener.

Table 1. Audio focus gain and loss implication.

GAIN LOSS AUDIOFOCUS_GAIN AUDIOFOCUS_LOSS AUDIOFOCUS_GAIN_TRANSIENT AUDIOFOCUS_LOSS_TRANSIENT AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK

Note: AUDIOFOCUS_GAIN is used in two places. When requesting audio focus it is passed in as a hint to the AudioManager and it is used as an event case in the OnAudioFocusChangeListener. The gain events highlighted in green are only used when requesting audio focus. The loss events are only used in the OnAudioFocusChangeListener.

Table 2. Audio stream types.

Stream Type Description STREAM_ALARM The audio stream for alarms STREAM_DTMF The audio stream for DTMF Tones STREAM_MUSIC The audio stream for "media" (music, podcast, videos) playback STREAM_NOTIFICATION The audio stream for notifications STREAM_RING The audio stream for the phone ring STREAM_SYSTEM The audio stream for system sounds

An app will request audio focus (see an example in the sample source code linked below) from the AudioManager (Listing 1, line 1). The three arguments it provides are an audio focus change listener object (optional), a hint as to what audio channel to use (Table 2, most apps should use STREAM_MUSIC) and the type of audio focus from Table 1, column 1. If audio focus is granted by the system (AUDIOFOCUS_REQUEST_GRANTED), only then handle any initialization (see Listing 1, line 9).

Note: The system will not grant audio focus (AUDIOFOCUS_REQUEST_FAILED) if there is a phone call currently in process and the application will not receive AUDIOFOCUS_GAIN after the call ends.

Within an implementation of OnAudioFocusChange(), understanding what to do when an application receives an onAudioFocusChange() event is summarized in Table 3.

In the cases of losing audio focus be sure to check that the loss is in fact final. If the app receives an AUDIOFOCUS_LOSS_TRANSIENT or AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK it can hold onto the media resources it has created (don’t call release()) as there will likely be another audio focus change event very soon thereafter. The app should take note that it has received a transient loss using some sort of state flag or simple state machine.

If an application were to request permanent audio focus with AUDIOFOCUS_GAIN and then receive an AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK an appropriate action for the application would be to lower its stream volume (make sure to store the original volume state somewhere) and then raise the volume upon receiving an AUDIOFOCUS_GAIN event (see Figure 1, below).

Table 3. Appropriate actions by focus change type.

Focus Change Type Appropriate Action AUDIOFOCUS_GAIN Gain event after loss event: Resume playback of media unless other state flags set by the application indicate otherwise. For example, the user paused the media prior to loss event. AUDIOFOCUS_LOSS Stop playback. Release assets. AUDIOFOCUS_LOSS_TRANSIENT Pause playback and keep a state flag that the loss is transient so that when the AUDIOFOCUS_GAIN event occurs you can resume playback if appropriate. Do not release assets. AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK Lower volume or pause playback keeping track of state as with AUDIOFOCUS_LOSS_TRANSIENT. Do not release assets. Conclusion and further reading

Understanding how to be a good audio citizen application on an Android device means respecting the system's audio focus rules and handling each case appropriately. Try to make your application behave in a consistent manner and not negatively surprise the user. There is a lot more that can be talked about within the audio system on Android and in the material below you will find some additional discussions.

Example source code is available here:

https://android.googlesource.com/platform/development/+/master/samples/RandomMusicPlayer

Join the discussion on

+Android Developers
Categories: Programming

Tablet changes in Google Play

Sun, 02/23/2014 - 02:46

Posted by Ellie Powers, Google Play team

Fueled by the Nexus 7 and other great devices, more than 70 million Android tablets have been activated. Thousands of developers have already designed their apps to look great on tablets, and with the holidays fast approaching, we’re making it even easier for the next wave of tablet owners to discover great apps and games.

Play Store tablet changes coming up on November 21

Last year, Google Play added a “designed for tablets” section, where users could easily discover apps that look great on their 7”- and 10”-tablets. This section includes only apps and games which meet criteria and guidelines we established last year. (Here’s an overview if you missed it.) Developers who invest the time to meet the criteria are seeing great results; take Remember The Milk, which saw an 83% increase in tablet downloads from being in this section. (see the whole story here).

On November 21 2013, the Play Store made a series of changes so it’s even easier for tablet users to find those apps that are best for their devices. First, by default, users browsing Google Play on a tablet will now see apps and games that are designed for tablets on the top lists (Top Paid, Top Free, Top Grossing, Top New Paid, Top New Free, and Trending). Tablet users will still be able to switch the view so they can see all apps or games if they choose. Also starting November 21, apps and games that do not meet the “designed for tablets” criteria will be marked as “designed for phones” for users who browse the Play Store on tablets.

You’ll want to make sure that your app is designed for tablets; read more about how to do this at the end of this blog post.

Make sure your app is ready!

If you want to be sure your app is included in the “Designed for tablets” view, go to the Developer Console to check your tablet optimization tips. If you see any issues listed there, you’ll need to address them in your app and upload a new binary for distribution. If there are no issues listed, your app is eligible to be included in the “Designed for tablets" view in the top lists.

Also, make sure to read the full tablet quality checklist to understand how to build outstanding tablet experiences.

Everyday, thousands of Android developers are taking advantage of the tremendous Android tablet opportunity. The flood of new users coupled with the increased screen size means new user experiences, more engagement and more monetization opportunities. We’re excited to see what you do!

Join the discussion on

+Android Developers
Categories: Programming

Bring Your Apps into the Classroom, with Google Play for Education

Sun, 02/23/2014 - 02:38

Posted by Shazia Makhdumi, Head of Strategic EDU Partnerships, Google Play team

Google Play for Education has officially launched. It’s an extension of Google Play that’s designed for schools, simplifying discovery of educational apps and enabling developers and content providers to reach K-12 educators in the U.S. It offers bulk purchasing with purchase orders and instant distribution of educational apps, videos and other educational content to students' Android tablets via the cloud. Google Play for Education helps your apps gain visibility with the right audiences, without having to knock on school doors.

If you've built an Android app that would be awesome for schools—or even have an idea for one—now's the time to jump in. We'll put you one click away from getting purchased and installed by entire school districts. Class Dojo, Explain Everything, Nearpod, and Socrative are already getting discovered in Google Play for Education.

How to join Google Play for Education

If you already have an educational Android app you can use the Google Play Developer Console to mark your apps for inclusion in Google Play for Education. Marking your app identifies it as suitable for the US K-12 educational market and queues it for educator approval. These educators perform a first-pass qualification of apps, assigning the appropriate subject, grade, and common core standards metadata, while evaluating if the app meets the Google Play for Education criteria for classroom use.

Designing great apps for classrooms

High quality apps are top priority for teachers. Whether you already have an existing K-12 educational app or are looking to build one, take a look at our detailed requirements and guidelines—which we have compiled for you based on educator feedback—to ensure your app is appropriate for a K-12 environment. Also ensure that your app is optimized for both 7” and 10” Android tablets. Then, upload your new or updated app through the Developer Console, opt in to Google Play for Education, and publish. We will email you when your app has been evaluated.

For more information, please visit the Google Play for Education pages on the Android developer site. We are excited to be supporting schools to bring the best content and tools to their students. We look forward to seeing your app on Google Play for Education.



Join the discussion on

+Android Developers
Categories: Programming

New Client API Model in Google Play Services

Fri, 02/14/2014 - 00:54
gps

By Magnus Hyttsten, Google Developer Relations

Google Play services 4.2 has now been rolled out to the world, and it’s packed with much-anticipated features such as the brand new Cast API and the updated Drive API.

In addition to these blockbuster announcements, we are also launching a slightly less visible but equally important new API — a new way to connect client APIs and manage API requests. As with the initial Drive API, these changes were available as a developer preview in earlier releases of Google Play services. We're now happy to graduate those APIs to fully supported and official.

In this post we'll take a look at the new Google Play services client APIs and what they mean for your apps — for details be sure to read Accessing Google Play services and the API reference documentation.

Connecting Client APIs

The client connection model has now been unified for all the APIs. As you may recall, you were previously required to use separate client classes for each API you wanted to use, for example: PlusClient, GamesClient, etc. Instead, you should now use GoogleApiClient, which allows you to connect to multiple APIs using a single call. This has great advantages such as:

  • Simplicity—The onConnected() method will be called once, and only when connectivity to all the client APIs you are using have been established. This means you do not have to intercept multiple callbacks, one for each API connected, which simplifies the code and state management.
  • Improved user experience—With this design, Google Play services knows about everything your app needs up front. All APIs, all scopes, the works. This means that we can take care of the user consents at once, creating a single consolidated user experience for all the APIs. No more sign-in mid-process terminations, partial state management, etc.

Below is an example of establishing a connection the Google+ and Drive APIs. To see the reference information for this new client connection model, you should check out the com.google.android.gms.common.api package.

@Override
protected void onCreate(Bundle b) {
    super.onCreate(b);

    // Builds single client object that connects to Drive and Google+
    mClient = new GoogleApiClient.Builder(this)
            .addApi(Drive.API)
            .addScope(Drive.SCOPE_FILE)
            .addApi(Plus.API, plusOptions)
            .addScope(Plus.SCOPE_PLUS_LOGIN)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();      
}

@Override
protected void onStart() {
    super.onStart();

    // Connect to Drive and Google+
    mClient.connect();
}

@Override
protected void onConnected(Bundle connectionHint) {
    // All clients are connected
    startRockAndRoll();
}

@Override
protected void onConnectionFailed(ConnectionResult result) {
    // At least one of the API client connect attempts failed
    // No client is connected
    ...
}
Enqueuing API Calls

Another new feature is enqueuing of API calls, which allows you to call read methods before the API clients are connected. This means you can issue these calls up front, for example in onStart/onResume, rather than having to wait and issue them in different callback methods. This is something which will greatly simplify code if your app requires data to be read when it is started. Here is an example of where a call like this can be placed:

@Override
protected void onStart() {
    super.onStart();
    mClient.connect();
}

@Override
protected void onResume() {
    super.onResume();

    // Enqueue operation.
    // This operation will be enqueued and issued once the API clients are connected.
    // Only API retrieval operations are allowed.
    // Asynchronous callback required to not lock the UI thread.
    Plus.PeopleApi.load(mClient, “me”, “you”, “that”).setResultCallback(this);
}
Supporting both Asynchronous and Synchronous Execution

With this release of Google Play services, you now have the option to specify if an API call should execute asynchronously (you will receive a callback once it is finished), or synchronously (the thread will block until the operation has completed). This is achieved by using the classes PendingResult, Result, and Status in the com.google.android.gms.common.api package.

In practice, this means that API operations will return an instance of PendingResult, and you can choose if you want the method to execute asynchronously using setResultCallback or synchronously using await. The following example demonstrates how to synchronously retrieve the metadata for a file and then clear any starred flag setting:

// Must be run in a background task and not on UI thread
new AsyncTask <DriveFile, Void, Void> {
    protected void doInBackground(DriveFile driveFile) {

        // Get the metadata synchronously
        MetaDataResult mdGetResult = driveFile.getMetadata(mClient).await();
        if (!mdGetResult.isSuccess()) {
            // Handle error
        }

        MetaData md = mdGetResult.getMetadata()
        // Perform operations based on metadata

        // Update the meta data, unconditionally clear the starred flag        
        MetaDataChangeSet mdCS = new MetadataChangeSet.Builder()
            .setStarred(false)
            .build();

        MetaDataResult mdUpdateResult =driveFile.updateMetaData(mClient,mdCS).await();
        if (!mdUpdateResult.isSuccess()) {
            // Handle error
        }

        … // continue doing other things synchronously
}).execute(fileName);

It should be stressed though that the old best practice rule — do not block the UI thread — is still in effect. This means that the execution of this sequence of API calls described above must be performed from a background thread, potentially by using AsyncTask as in the example above.

Moving your apps to the new client API

We believe these changes will make it easier for you to build with Google Play services in your apps. For those of you using the older clients, we recommend refactoring your code as soon as possible to take advantage of these features. Apps deployed using the old client APIs will continue to work since these changes do not break binary compatibility, but the old APIs are now deprecated and we'll be removing them over time.

That’s it for this time. Google Play services allows Google to provide you with new APIs and features faster than ever, and with the capabilities described in this post, you now have a generic way of using multiple client APIs and executing API calls. Make sure to check out the video below for a closer look at the new client APIs.

To learn more about Google Play services and the APIs available to you through it, visit the Google Services area of the Android Developers site. Details on the APIs are available in the API reference.

For information about getting started with Google Play services APIs, see Set Up Google Play Services SDK



Join the discussion on

+Android Developers
Categories: Programming

Google Play Services 4.1

Thu, 01/16/2014 - 20:13
gps

The latest release of Google Play services is now available on Android devices worldwide. It includes new Turn Based Multiplayer support for games, and a preliminary API for integrating Google Drive into your apps. This update also improves battery life for all users with Google Location Reporting enabled.

You can get started developing today by downloading the Google Play services SDK from the SDK Manager.

Turn Based Multiplayer

Play Games now supports turn-based multiplayer! Developers can build asynchronous games to play with friends and auto-matched players, supporting 2-8 players per game. When players take turns, their turn data is uploaded to Play Services and shared with other players automatically.

We are also providing an optional new “Connecting to Play Games” transition animation during sign-in, before the permission dialog appears. This helps contextualize the permission dialog, especially in games that ask for sign in on game start.

Google Drive

This version of Google Play Services includes a developer preview of the new Google Drive API for Android. You can use it to easily read and write files in Google Drive so they're available across devices and on the web. Users can work with files offline too — changes are synced with Google Drive automatically when they reconnect.

The API also includes common UI components including a file picker and save dialog.

Google Mobile Ads

With Google Play services 4.1, the Google Mobile Ads SDK now fully supports DoubleClick for Publishers, DoubleClick Ad Exchange, and Search Ads for Mobile Apps. You can also use a new publisher-provided location API to provide Google with the location when requesting ads. Location-based ads can improve your app monetization.

Google+

An improved Google+ sharing experience makes it even easier for users to share with the right people from your app. It includes better auto-complete and suggested recipients from Gmail contacts, device contacts and people on Google+.

More About Google Play Services

To learn more about Google Play services and the APIs available to you through it, visit the Google Services area of the Android Developers site. Details on the APIs are avaialble in the API reference.

For information about getting started with Google Play services APIs, see Set Up Google Play Services SDK

Join the discussion on

+Android Developers
Categories: Programming

The Beautiful Design Winter 2013 Collection on Google Play

Thu, 12/26/2013 - 20:29
Posted by Marco Paglia, Android Design Team

While beauty’s in the eye of the beholder, designing apps for a platform also requires an attention to platform norms to ensure a great user experience. The Android Design site is an excellent resource for designers and developers alike to get familiar with Android’s visual, interaction, and written language. Many developers have taken advantage of the tools and techniques provided on the site, and every now and then we like to showcase a few notable apps that go above and beyond the guidelines.

This summer, we published the first Beautiful Design collection on Google Play. Today, we're refreshing the collection with a new set of apps just in time for the holiday season.

As a reminder, the goal of this collection is to highlight beautiful apps with masterfully crafted design details such as beautiful presentation of photos, crisp and meaningful layout and typography, and delightful yet intuitive gestures and transitions.

The newly updated Beautiful Design Winter 2013 collection includes:

Timely (by Bitspin), a clock app that takes animation to a whole new level. Screen transitions are liquid smooth and using the app feels more like playing with real objects than fussing around with knobs and buttons. If you’ve ever wondered if setting an alarm could be fun, Timely unequivocally answers “yes”.

Circa, a news reader that’s fast, elegant and full of beautiful design details throughout. Sophisticated typography and banner image effects, coupled with an innovative and "snappy" interaction, makes reading an article feel fast and very, very fun.

Etsy, an app that helps you explore a world of wonderful hand-crafted goods with thoughtfully designed screen transitions, beautifully arranged layouts, and subtle flourishes like a blur effect that lets you focus on the task at hand. This wonderfully detailed app is an absolute joy to use.

Airbnb, The Whole Pantry, Runtastic Heart Rate Pro, Tumblr, Umano, Yahoo! Weather… each with delightful design details.

Grand St. and Pinterest, veterans of the collection from this summer.

If you’re an Android developer, make sure to play with some of these apps to get a sense for the types of design details that can separate good apps from great ones. And remember to review the Android Design guidelines and the Android Design in Action video series for more ideas on how to design your next beautiful Android app.


Join the discussion on

+Android Developers
Categories: Programming