Get Paid To Promote, Get Paid To Popup, Get Paid Display Banner

Friday, April 13, 2012

Android C2DM — Client Login key expiration

[This post is by Francesco Nerieri, engineering team lead for C2DM — Tim Bray]

In the upcoming weeks, some of the older Client Login authentication keys will expire. If you generated the token you’re currently using to authenticate with the C2DM servers before October 2011, it will stop working.

If the response from the C2DM servers contains an Update-Client-Auth header, you’ll need to replace the current token with the one included in the header.

  // Check for updated token header
String updatedAuthToken = conn.getHeaderField(UPDATE_CLIENT_AUTH);
if (updatedAuthToken != null && !authToken.equals(updatedAuthToken)) {
log.info("Got updated auth token from datamessaging servers: " +
updatedAuthToken);
serverConfig.updateToken(updatedAuthToken);
}

We suggest that you start using the Update-Client-Auth response header to update tokens regularly, as keys will expire periodically from now on. For example, have a look at the Chrome to Phone service hosted on code.google.com; this code takes care of authenticating via Client Login and then sending a message:

Alternatively, you can manually generate a new Client Login token now and replace the one currently in use. ClientLogin can be used with any application that can make an HTTPS POST request. The POST request should be structured as a form post with the default encoding application/x-www-form-urlencoded, like this:

POST /accounts/ClientLogin HTTP/1.0
Content-type: application/x-www-form-urlencoded

accountType=GOOGLE&Email=johndoe@gmail.com&Passwd=north23AZ&service=ac2dm

If the POST succeeds, the response contains the authorization token, labeled "Auth", which is your new token. You could even do this from the command line:

curl -d \
"accountType=HOSTED_OR_GOOGLE&Email=johndoe@gmail.com&Passwd=north23AZ&service=ac2dm" \
https://www.google.com/accounts/ClientLogin | \
grep Auth

If your request fails or if you are prompted for captchas, please read ClientLogin for Installed Applications. And of course, if you updated your code to use the Update-Client-Auth header after the keys had expired, then you will first need to manually generate a new token.

Have fun with C2DM!

Thursday, April 12, 2012

New Seller Countries in Google Play

Over the past year we’ve been working to expand the list of countries and currencies from which Android developers can sell their products. Starting today, developers in Czech Republic, Israel, Poland, and Mexico can sell priced applications and in-app products on Google Play, using their local bank accounts for payments. Welcome developers!



If you develop Android apps in one of the new countries and want to get started selling them, visit play.google.com/apps/publish and set up a new Google Play developer account. Once you’ve uploaded your apps, you can price them in any available buyer currencies, publish, and then receive payouts and financial data in your local currency.



If you are based in Israel or Mexico and are currently selling apps through an AdSense merchant account, you will need to migrate your apps to a new Google Play developer account in your local currency. Watch for an email that provides complete information on the migration process and timeline.



Additionally, we encourage developers everywhere to visit the Developer Console as soon as possible to set prices for their products in the currencies of these new countries. Stay tuned for more announcements soon as we continue to roll out our new billing infrastructure to buyers and sellers throughout the world.



Join the discussion on

+Android Developers



Tuesday, April 10, 2012

Accessibility: Are You Serving All Your Users?

[This post is by Joe Fernandez, a technical writer for developer.android.com who cares about accessibility and usability. — Tim Bray.]

We recently published some new resources to help developers make their Android applications more accessible:

“But,” you may be thinking, “What is accessibility, exactly? Why should I make it a priority? How do I do it? And most importantly, how do I spell it?” All good questions. Let’s hit some of the key points.

Accessibility is about making sure that Android users who have limited vision or other physical impairments can use your application just as well as all those folks in line at the supermarket checking email on their phones. It’s also about the Mom over in the produce section whose kids are driving her to distraction, and really needs to see that critical notification your application is trying to deliver. It’s also about you, in the future; Is your eyesight getting better over time? How about that hand-eye coordination?

When it comes down to it, making an application accessible is about having a deep commitment to usability, getting the details right and delighting your users. It also means stepping into new territory and getting a different perspective on your application. Try it out: Open up an application you developed (or your all-time favorite app), then close your eyes and try to complete a task. No peeking! A little challenging, right?

How Android Enables Accessibility

One of main ways that Android enables accessibility is by allowing users to hear spoken feedback that announces the content of user interface components as they interact with applications. This spoken feedback is provided by an accessibility service called TalkBack, which is available for free on Google Play and has become a standard component of recent Android releases.

Now enable TalkBack, and try that eyes-closed experiment again. Being able to hear your application’s interface probably makes this experiment a little easier, but it’s still challenging. This type of interaction is how many folks with limited vision use their Android devices every day. The spoken feedback works because all the user interface components provided by the Android framework are built so they can provide descriptions of themselves to accessibility services like TalkBack.

Another key element of accessibility on Android devices is the ability to use alternative navigation. Many users prefer directional controllers such as D-pads, trackballs or keyboard arrows because it allows them to make discrete, predictable movements through a user interface. You can try out directional control with your apps using the virtual keyboard in the Android emulator or by installing and enabling the Eyes-Free Keyboard on your device. Android enables this type of navigation by default, but you, as a developer, may need to take a few steps to make sure users can effectively navigate your app this way.

How to Make Your Application Accessible

It would be great to be able to give you a standard recipe for accessibility, but the truth of the matter is that the right answer depends on the design and functionality of your application. Here are some key steps for ensuring that your application is accessible:

  1. Task flows: Design well-defined, clear task flows with minimal navigation steps, especially for major user tasks, and make sure those tasks are navigable via focus controls (see item 4).

  2. Action target size: Make sure buttons and selectable areas are of sufficient size for users to easily touch them, especially for critical actions. How big? We recommend that touch targets be 48dp (roughly 9mm) or larger.
  3. Label user interface controls: Label user interface components that do not have visible text, especially ImageButton, ImageView, and EditText components. Use the android:contentDescription XML layout attribute or setContentDescription() to provide this information for accessibility services.

  4. Enable focus-based navigation: Make sure users can navigate your screen layouts using hardware-based or software directional controls (D-pads, trackballs and keyboards). In a few cases, you may need to make UI components focusable or change the focus order to be more logical.

  5. Use framework-provided controls: Use Android's built-in user interface controls whenever possible, as these components provide accessibility support by default.

  6. Custom view controls: If you build custom interface controls for your application, implement accessibility interfaces for your custom views and provide text labels for the controls.

  7. Test: Checking off the items on this list doesn’t guarantee your app is accessible. Test accessibility by attempting to navigate your application using directional controls, and also try eyes free navigation with the TalkBack service enabled.

Here’s an example of implementing some basic accessibility features for an ImageButton inside an XML layout:

<ImageButton
android:id="@+id/add_note_button"
android:src="@drawable/add_note_image"
android:contentDescription="@string/add_note_description"/>

Notice that we’ve added a content description that accessibility services can use to provide an audible explanation of the button. Users can navigate to this button and activate it with directional controls, because ImageButton objects are focusable by default (so you don’t have to include the android:focusable="true" attribute).

The good news is that, in most cases, implementing accessibility isn’t about radically restructuring your application, but rather working through the subtle details of accessibility. Making sure your application is accessible is an opportunity to look at your app from a different perspective, improve the overall quality of your app and ensure that all your users have a great experience.

Monday, April 9, 2012

A Faster Emulator with Better Hardware Support

[This post is by Xavier Ducrohet and Reto Meier of the Android engineering team. — Tim Bray.]

The Android emulator is a key tool for Android developers in building and testing their apps. As the power and diversity of Android devices has grown quickly, it’s been hard for the emulator keep pace.

Today we’re thrilled to announce several significant improvements to the emulator, including a dramatic performance upgrade and support for a broader range of hardware features, notably sensors and multi-finger input.

Added GPU Support

The system image we’re shipping today has built-in GPU support (Android 4.0.3 r2). With Android’s growing reliance on using the GPU to improve performance, the difference is significant. In the video below, the emulator is still interpreting ARM instructions; the performance boost is the effect of putting the GPU to work.


As a bonus, since we’re now supporting OpenGL ES 2.0, your OpenGL games can now run inside the emulator.

Please note that there are a lot of GPUs out there, and we haven’t tested all of them for this beta release, so let us know if you have feedback or encounter issues.

More Hardware Feature Emulation

The hardware features of mobile devices are a significant part of what makes them a unique platform for development, so we’re also pleased to announce that in addition to the camera support we added last year, it’s now possible to use a tethered Android device to supply inputs for sensors and multi-touch input.

We’re working on providing emulator support for more hardware features including Bluetooth and NFC.

Improved CPU Performance

We’ve also improved the CPU performance of the Android emulator. Hardware floating point operation has been available for system images since Ice Cream Sandwich (Android 4.0), allowing CPU operations to be emulated roughly twice as quickly.

Last week’s r17 developer tools release included x86 system images and host drivers (available through the SDK Manager), allowing the emulator to access the host CPU natively and offer significantly faster execution.

This video shows a CPU-bound application on two emulators running the same system image, one with virtualization, one without.

Building a modern emulator

Because the Android platform allows deep interaction between applications, and with system components, we need to provide an emulator with a complete system image. Our emulator virtualizes a complete device: hardware, kernel, low-level system libraries, and app framework.

Of course, the system being emulated typically has an ARM CPU; historically, we’d been emulating those instructions in software, and that worked OK until the advent of tablet support with additional animations and complexity in Android 3.0.

The missing pieces were the completion of Android x86 support, and the GPU support in last week’s release of SDK Tools r17. This works by funneling the OpenGL ES 2.0 instructions from the emulator to the host OS, converted to standard OpenGL 2.0, and running natively on the host GPU.

Conclusion

The Android ecosystem has a lot of devices in many different form factors. Developers need a good way of testing these apps without having to own everything out there and a fast, rich Android emulator is immensely helpful.

We hope that these new improvements will make the emulator a more useful tool in your development and testing, and look forward to improving it further for you.

Tuesday, April 3, 2012

The Gmail Public Labels API

[This post is by Nadav Aharony, a product manager on the Android team — Tim Bray]

We’re rolling out new developer features for the Gmail Android app: It now includes a public ContentProvider that you can use to retrieve label data. You can use this to access up-to-date unread counts for specific accounts’ inboxes and labels.

To use the API, the Gmail app needs to be at version 2.3.6 or higher on Froyo or Gingerbread; 4.0.5 or higher on Honeycomb and ICS. Before using it, be sure you first check the Gmail app version; we’ve provided a handy GmailContract.canReadLabels(Context) method to help with this. Your app will need the com.google.android.gm.permission.READ_CONTENT_PROVIDER permission.

Finding the Gmail accounts set up on the device

The Labels API needs a valid Gmail account to build a query for per-label information. Assuming the GET_ACCOUNTS permission, the AccountManager can be used to fetch this information:

// Get the account list, and pick the first one
final String ACCOUNT_TYPE_GOOGLE = "com.google";
final String[] FEATURES_MAIL = {
"service_mail"
};
AccountManager.get(this).getAccountsByTypeAndFeatures(ACCOUNT_TYPE_GOOGLE, FEATURES_MAIL,
new AccountManagerCallback() {
@Override
public void run(AccountManagerFuture future) {
Account[] accounts = null;
try {
accounts = future.getResult();
if (accounts != null && accounts.length > 0) {
String selectedAccount = accounts[0].name;
queryLabels(selectedAccount);
}

} catch (OperationCanceledException oce) {
// TODO: handle exception
} catch (IOException ioe) {
// TODO: handle exception
} catch (AuthenticatorException ae) {
// TODO: handle exception
}
}
}, null /* handler */);

Getting and accessing existing labels

Once you’ve got the email account, you can get a ContentProvider URI to query against. We've provided a simple support class called GmailContract.java for constructing the URI and defining the columns and relevant constants.

You can access any label, predefined or user-defined. The predefined labels include (you have to use symbolic constants rather than these strings, see below):

  • Priority Inbox

  • Starred

  • Chats

  • Sent

  • Drafts

  • All mail

  • Spam

  • Trash

To obtain a Cursor with information for all labels in an account, your app can either query this URI directly or use a CursorLoader. Here’s an example:

Cursor c = 
getContentResolver().query(GmailContract.Labels.getLabelsUri(selectedAccount),
null, null, null, null);

You can query and watch for changes on a single label by storing the URI value in the GmailContract.Labels.URI column from the cursor data.

The NAME value for pre-defined labels can vary by locale, so don’t use GmailContract.Labels.NAME. Instead, identify pre-defined labels like Inbox, Sent or Drafts using the String value in the GmailContract.Labels.CANONICAL_NAME column. Here’s an example:

// loop through the cursor and find the Inbox
if (c != null) {
final String inboxCanonicalName = GmailContract.Labels.LabelCanonicalName.CANONICAL_NAME_INBOX;
final int canonicalNameIndex = c.getColumnIndexOrThrow(GmailContract.Labels.CANONICAL_NAME);
while (c.moveToNext()) {
if (inboxCanonicalName.equals(c.getString(canonicalNameIndex))) {
// this row corresponds to the Inbox
}
}
}

If you choose to use a CursorLoader, it will keep the label counts up to date as they change over time.

Sample App

You can find a sample app that makes use of the new API here. The app provides a basic readout of label and message-count information.

People care about their incoming mail; we’re looking forward to seeing what you do with access to this information. We’re also open to suggestions as to how to improve and extend this new API.

Thursday, March 29, 2012

Making the Android Developer Console work for your whole team

[This post is by Ellie Powers, a product manager on the Google Play team. — Tim Bray]

As your apps have gotten more successful, more people have joined your team. Today, we’re making it easier to work together on analyzing and managing your published Android apps. Sharing passwords is generally a bad idea; so as of now, there’s no need to do that for the Android Developer Console — everyone can use his or her own Google account.



The account that you use today to sign into the Android Developer Console will become the account owner; only the account owner can manage access to the Console. The account owner can email an invitation to anyone; when they accept it, they’ll need to use a Google account to sign in.



Different people in your team do different jobs, so when you invite someone to your Android Developer Console, you’ll be able to specify what access they need. Today, you can limit access per-user to financial reports. In the future, we’ll give you more fine-grained control over access to the Console. For details, see Account owner and user access.



We hope this helps your team collaborate more easily. If you have any issues, feel free to get in touch via the Developer Help Center.



Join the discussion on

+Android Developers



Thursday, March 22, 2012

New Sales Reports on Google Play



[This post is by Debashish Chatterjee, Krishna Atkuru, and Ellie Powers of the Google Play Publisher Site team. —Dirk Dougherty]



For app publishers, complete and timely sales reporting is incredibly useful for managing a business on Google Play. Today we are introducing a new financial tool — Estimated Sales Reports — to give you visibility over ongoing product sales and help you support customers between payout cycles.



The new sales reports show you complete transaction details of recent sales and refunds for all products in your developer account, including both in-app products and paid apps. Each report is a cumulative for the current payout period, updated nightly with the details of recent transactions. As customers complete purchases and their accounts are charged (or refunds are applied), the new transaction details are appended to the Estimated Sales Report. Depending on account timezone differences, transactions appear on the estimated sales report within 2 days of completion. Finally, at the close of the monthly payout cycle, the current Estimated Sales Report is archived and a new report is created for the next cycle.





You can access current or past sales reports from the “Merchant Reports” section of the Developer Console. The Estimated Sales Reports are downloadable CSV (comma-separated values) files, so you can analyze the data using any tools you choose, in the same way as you've been doing for payout reports. The sales reports list the same details as payout reports — buyer and order, product, device information, amount, currency of sale, and more — except without final payment details. This makes it easier for you to reconcile recorded sales against your actual payouts. Estimated sales reports are available with data starting February 1, 2012.



We’ve also taken this opportunity to rename our existing “Merchant Sales Reports” to Monthly Payout Reports, to better reflect their content.



Together with the application statistics introduced last month, the Estimated Sales and Monthly Payout Reports give you a more complete view of your products’ download and sales activity over time. We hope you’ll find them useful. As always, please feel free to give us feedback through the Developer Help Center.



Join the discussion on

+Android Developers



Wednesday, March 21, 2012

Updated SDK Tools and ADT revision 17

Today we are releasing an update to the SDK Tools and the Eclipse plugin. Revision 17 brings a lot of new features and bug fixes in various areas such as Lint, the build system as well as the emulator.

Lint is a static checker which analyzes Android projects for a variety of issues around correctness, security, performance, usability and accessibility, checking your XML resources, bitmaps, ProGuard configuration files, source files and even compiled bytecode. It can be run from within Eclipse or from the command line.
New for r17:

  • Added check for Android API calls that require a version of Android higher than the minimum supported version. You can use the new @TargetApi annotation to specify local overrides for conditionally loaded code. For more information, read here.
  • Added over 40 new Lint rules for a total of over 80, including checks for performance, XML layouts, manifest and file handling. For a full list read here.
  • Added ability to suppress Lint warnings in Java code with the new @SuppressLint annotation, and in XML files with the new tools: namespace prefix and ignore attribute. For more information, read here.
  • Improved HTML and XML reporting and Eclipse integration. For more information, read here.

We’ve also made improvements to the build systems for Eclipse and Ant:

  • Added strict dependency support for 3rd party Jar files. You can read more information here.
  • Added support for custom views with custom attributes in libraries. Layouts using custom attributes must use the namespace URI http://schemas.android.com/apk/res-auto instead of the URI that includes the app package name. This URI is replaced with the app specific one at build time.
  • Added a feature that allows you to run some code only in debug mode. Builds now generate a class called BuildConfig containing a DEBUG constant that is automatically set according to your build type. You can check the (BuildConfig.DEBUG) constant in your code to run debug-only functions such as outputting debug logs.

The emulator is seeing some big improvements as well:

  • Thanks to contributions to AOSP from Intel, the emulator now supports running x86 system images in virtualization mode on Windows and Mac OS X. This allows the emulator running at near native speed. The drivers are available through the SDK Manager. Read more here.
  • After adding webcam support and sensor emulation, we are adding experimental support for Multi-Touch input through a tethered Android device. (Read more here)

Finally, we are also releasing an updated Support Library with the following improvements:

  • ShareCompat provides easy helper classes for both sending and receiving content for social sharing apps.
  • NavUtils and TaskStackBuilder provide cross-version support for implementing the Android Design guidelines for navigating within your app including the action bar's "Up" button.
  • NotificationCompat.Builder provides a compatibility implementation of Android 3.0's Notification.Builder helper class for creating standardized system notifications.
  • A new Library Project adds support for GridLayout back to API level 7 and higher.

You can get more information about these changes in the SDK Tools Release Notes and ADT Release Notes.

Tuesday, March 13, 2012

Unifying Key Store Access in ICS

[This post is a group effort by Tony Chan, Fred Chung, Brian Carlstrom, and Kenny Root. — Tim Bray]

Android 4.0 (ICS) comes with a number of enhancements that make it easier for people to bring their personal Android devices to work. In this post, we’re going to have a look at the key store functionality.

Back in Android 1.6 (Donut), a system key store was added for use by VPN. Although this was later expanded to support WiFi authentication, applications weren’t able to access it.

In the past, it was common practice for apps to maintain their own key store if they needed to authenticate a secure SSL web server, or authenticate the user to a server via a client certificate. While this works, it can present manageability issues in an enterprise environment where multiple certificates may be shared across a number of apps such as Email and Browser.

New in ICS: KeyChain

To bridge the gap in ICS, there’s a new API named KeyChain that regulates application access to the system key store and allows users to grant application access to the credentials stored there. Additionally, this API enables applications to initiate installation of credentials from X.509 certificates and PKCS#12 key stores.

The KeyChain API is rather simple. To install a key store or a certificate, you retrieve an install intent, supply the raw bytes of the credentials, and use the intent to launch a system installation dialog. If it’s a keystore, as in the example below, you’ll need provide the data in PKCS#12 format, and the user will have to know the PKCS#12 password.

  byte[] keystore = . . (read from a PKCS#12 keystore)

Intent installIntent = KeyChain.createInstallIntent();
installIntent.putExtra(KeyChain.EXTRA_PKCS12, keystore);
startActivityForResult(installIntent, INSTALL_KEYSTORE_CODE);

The install intent launches a system dialog that prompts the user to enter the password for the keystore.

This can also be used for installing organizational CA certificates which will then be trusted by all applications to authenticate to non-public servers with certificates issued by the same CA.

In ICS, Android no longer requires a separate password to protect the system credential storage. Rather, it uses the screen lock password for this purpose, and the Android Device Administration API can be used for central policy enforcement. This means, for example, that the screen lock password can’t be removed as long as the secured credentials remain on the device.

Accessing System Key Store Credentials

Once the system key store is configured, the KeyChain API offers functions such as requesting a client certificate for authenticating with an SSL server. The first time an application requests access, the user is prompted with a list of available certificates and can select one to grant access to that certificate to the application. If the user chooses to allow access to a certificate, a string alias name for the certificate is returned to the application. The application can then use the alias to access the certificate in the future without further user involvement.

The code below illustrates how an application can prompt the user to select a credential alias and grant access to the application. KeyChain will remember this selection such that the same application can save the credential alias selection and have access to the same certificate in future. For example, the Email application for ICS has implemented this feature in its Server Settings screen.

  KeyChain.choosePrivateKeyAlias(this,
new KeyChainAliasCallback() {

public void alias(String alias) {
// Credential alias selected. Remember the alias selection for future use.
if (alias != null) saveAlias(alias);
}
},
new String[] {"RSA", "DSA"}, // List of acceptable key types. null for any
null, // issuer, null for any
"internal.example.com", // host name of server requesting the cert, null if unavailable
443, // port of server requesting the cert, -1 if unavailable
null); // alias to preselect, null if unavailable

Once an application has been granted access to the certificate, it can access the private key through the getPrivateKey() method. It is worth noting that as with any PrivateKey objects, the application should not make assumptions about the encoding. For example, on some implementations the PrivateKey object may just be an opaque representation of a key stored in a hardware key store.

Here’s a sample code snippet that demonstrates the use of private key retrieved from the key store for signing:

    PrivateKey privateKey = KeyChain.getPrivateKey(context, savedAlias);
if (privateKey != null) {
...
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(privateKey);
...
}

A common use of the private key is for SSL client authentication. This can be implemented by using an HttpsURLConnection with a custom X509KeyManager that returns the PrivateKey retrieved from the KeyChain API. The open source Email application for ICS uses KeyChain with an X509ExtendedKeyManager. To learn more, have a look at the source code (in SSLUtils.java).

This API provides a unified way to access the system key store credentials. If your application uses client certificates (take note: enterprise email client or web browser developers) you should definitely look into the KeyChain API for your next update!

Tuesday, March 6, 2012

Introducing Google Play



[This post is by Kenneth Lui, Android Developer Ecosystem. —Dirk Dougherty]

For more than a year we’ve been focused on expanding the reach, content, and monetization opportunities of Android Market. We started by extending the store to users on the web and then went on to add books, movies, and music. The number of people who have visited, registered, and downloaded from the store has been amazing.



Today we’re launching Google Play, an integrated destination for apps, books, movies, and music, accessible to users on Android devices and to anyone on the Web. As part of this launch, Google Play replaces and extends Android Market — users everywhere can now find their favorite apps and games in Google Play, with other digital content, all in one place.



We believe that with a strong brand, compelling offerings, and a seamless purchasing and consumption experience, Google Play will drive more traffic and revenue to the entire ecosystem.



We’ll be investing in the brand to bring Google Play to as many people as possible, and we’ll also invest in the latest digital content to keep Google Play fresh, relevant, and engaging. Apps and games remain the core of Google Play, so we’ll continue investing in new ways to connect users with their favorite apps, and developers with new customers.







As we grow and promote Google Play around the world, we’ll be marketing your apps and games at the same time. Our policies have not changed and our goal is still the same — to create a great, open marketplace for distributing Android apps.



Google Play is built on the same infrastructure as Android Market, so the transition for users and developers will be seamless. Users can sign into their existing accounts with the same credentials as before and purchase content using the same payment methods. As a developer, there’s no change needed to your published products and you can continue to use the same publishing tools to put your app in front of hundreds of millions of Android users. If your app was in Android Market yesterday, it’s in Google Play today.



We’ll be rolling out Google Play to devices in a phased OTA update, starting today and continuing over the days to come. With the update, the Android Market app will upgrade to the Play Store app and the Music, Videos, and Books apps will upgrade to Play Music, Play Movies, and Play Books. This update is for devices running Android 2.2 or higher, and users on other devices will continue to have the same access to your apps as before.



You can start sending customers to your products in Google Play right away. Check out the updated “Get it on Google Play” badges and look for an email with more details on the transition. In the meantime, you can check out the Google Play web site at the link below and join the discussion on +Android Developers.



http://play.google.com

Monday, March 5, 2012

Android Apps Break the 50MB Barrier

Android applications have historically been limited to a maximum size of 50MB. This works for most apps, and smaller is usually better — every megabyte you add makes it harder for your users to download and get started. However, some types of apps, like high-quality 3D interactive games, require more local resources.

So today, we’re expanding the Android app size limit to 4GB.

The size of your APK file will still be limited to 50MB to ensure secure on-device storage, but you can now attach expansion files to your APK.

  • Each app can have two expansion files, each one up to 2GB, in whatever format you choose.

  • Android Market will host the files to save you the hassle and cost of file serving.

  • Users will see the total size of your app and all of the downloads before they install/purchase.

On most newer devices, when users download your app from Android Market, the expansion files will be downloaded automatically, and the refund period won’t start until the expansion files are downloaded. On older devices, your app will download the expansion files the first time it runs, via a downloader library which we’ve provided below.

While you can use the two expansion files any way you wish, we recommend that one serve as the initial download and be rarely if ever updated; the second can be smaller and serve as a “patch carrier,” getting versioned with each major release.

Helpful Resources

In order to make expansion file downloading as easy as possible for developers, we're providing sample code and libraries in the Android SDK Manager.

  • In the Google Market Licensing package, an updated License Verification Library (LVL). This minor update mostly adds the ability to obtain expansion file details from the licensing server.

  • From the Google Market APK Expansion package, the downloader service example. The library makes it relatively simple to implement a downloader service in your application that follows many of our best practices, including resuming downloads and displaying a progress notification.

Because many developers may not be used to working with one or two large files for all of their secondary content, the example code also includes support for using a Zip file as the secondary file. The Zip example implements a reasonable patching strategy that allows for the main expansion file to “patch” the APK and the patch file to “patch” both the APK and the main expansion file by searching for asset files in all three places, in the order patch->main->APK.

Expansion File Basics

Expansion files have a specific naming convention and are located in a specific place for each app. As expansion files are uploaded to the publisher site, they are assigned a version code based upon the version of the APK that they are associated with. The naming convention and location are as follows:

Location: <shared-storage>/Android/obb/<package-name>/
Filename: [main|patch].<expansion-version>.<package-name>.obb
Example: /sdcard/Android/obb/com.example.myapp/main.5.com.example.myapp.obb

Expansion files are stored in shared storage. Unlike APK files, they can be read by any application.

Downloading and Using the Expansion Files

When the primary activity for the app is created, it should check to make sure the expansion files are available. The downloader library provides helper functions (for example the “Helpers” class in the code below) to make this easy.

boolean expansionFilesDelivered() {
// get filename where main == true and version == 3
String fileName = Helpers.getExpansionAPKFileName(this, true, 3);
// does the file exist with FILE_SIZE?
if (!Helpers.doesFileExist(this, fileName, FILE_SIZE, false)) {
return false;
}
return true;
}

If the file does not exist, fire up the downloader service with DownloaderClientMarshaller.startDownloadServiceIfRequired(). The downloader will perform an LVL check against the server. This check will deliver the names of the files, file sizes, and the file URLs.

Once that check has been completed, it will begin downloading the files. You don’t have to use our download solution, but you might want to because we:

  • Include a notification UI that provides progress and estimated completion time in layouts customized for ICS and pre-ICS devices

  • Resume large files safely

  • Handle redirection with appropriate limits

  • Run in the background as a service

  • Pause and resume downloads when WiFi is not available

Enjoy! We can’t wait to see what kinds of things developers do with this! For more information about how to use expansion files with your app, read the APK Expansion Files developer guide.

[This post wasn’t actually written by anyone, but bashed out by a posse of engineering and product-management people. Heavy bashers included Dan Galpin, Ilya Firman, Andy Stadler, Michael Siliski, and Ellie Powers.]

Wednesday, February 29, 2012

Android Design V2: Now with stencils

[This post is by Android designer Alex Faaborg, on behalf of the entire User Experience team. —Tim Bray]

When we initially released Android Design, by far the number one request we received was for us to release stencils as well. The fine folks on the Android User Experience team are pleased today to release some official Android Design stencils for your mockup-creating pleasure.

With these stencils you can now drag and drop your way to beautifully designed Ice Cream Sandwich (Android 4.0) applications, with grace and ease. The stencils feature the rich typography, colors, interactive controls, and icons found throughout Ice Cream Sandwich, along with some phone and tablet outlines to frame your meticulously crafted creations.

Currently we have stencils available for those venerable interactive design powerhouses Adobe® Fireworks®, and Omni® OmniGraffle® and we may expand to other applications® in the future. The source files for the various icons and controls are also available, created in Adobe® Photoshop®, and Adobe® Illustrator®. Here are the downloads.

We’ll be updating these stencils over time so, as always, please send in your feedback!

Happy mockup making,
— Your friendly Android Design Droids

Tuesday, February 28, 2012

New App Stats for Publishers on Android Market



If you've published an app on Android Market, you’ve probably used Application Statistics to help tune your development and marketing efforts. Application Statistics is a set of dashboards in the Developer Console that shows your app’s installation performance across key dimensions such as countries, platform versions, device models, and others. Today we are making Application Statistics even more powerful for publishers, adding new metrics, new ways to analyze your data, and a redesigned UI that’s much easier to use.

First, we are adding important new installation metrics to the dashboards. You can now see your installations measured by unique users, as well as by unique devices. For user installations, you can view active installs, total installs, and daily installs and uninstalls. For devices, you can see active installs as well as daily installs, uninstalls, and upgrades.



Along with the new metrics, we’re also introducing two new data dimensions — Carrier and App Version. You can use them to track your app’s installation trends across mobile operators or monitor the launch metrics of specific app updates.



To give you visibility over your installation data over time, we’re adding timeline charts for all metrics and dimensions. At a glance, these charts highlight your app’s installation peaks and longer-term trends, which you can correlate to promotions, app improvements, or other factors. You can even focus in on data inside a dimension by adding specific points (such as individual platform versions or languages) to the timeline.



Finally, we’re bringing you all of the new metrics, dimensions, and timelines in a completely redesigned UI that is faster, more compact, and easier to use. Each dimension is now displayed in dedicated tab, making it easier to click through your stats daily or as often as needed. If you track your stats in another tool, we’re also adding an export capability that lets you download your stats in a single CSV file.



Check out the new Application Statistics next time you visit the Android Market Developer Console. We hope they’ll give you new insight into your app’s user base and installation performance. Watch for related announcements soon — we are continuing to work on bringing you the reporting features you need to manage your products successfully on Android Market.



Please feel free to share any new insights or tips on +Android Developers!

Thursday, February 9, 2012

Share With Intents

[This post is by Alexander Lucas, an Android Developer Advocate bent on saving the world 5 minutes. —Tim Bray]

[Please join the discussion on Google+.]

Intents are awesome. They are my favorite feature of Android development. They make all sorts of stuff easier. Want to scan a barcode? In the olden platforms, if you were lucky, this involved time and effort finding and comparing barcode-scanning libraries that handled as much as possible of camera interaction, image processing, an internal database of barcode formats, and UI cues to the user of what was going on. If you weren’t lucky, it was a few months of research & haphazard coding to figure out how to do that yourself.

On Android, it’s a declaration to the system that you would like to scan a barcode.

public void scanSomething() {
// I need things done! Do I have any volunteers?
Intent intent = new Intent("com.google.zxing.client.android.SCAN");

// This flag clears the called app from the activity stack, so users arrive in the expected
// place next time this application is restarted.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
...
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// The Intents Fairy has delivered us some data!
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}

See that? That’s nothing. That’s 5 minutes of coding, 3 of which were just to look up the name of the result you wanted to pull. And that was made possible because the Barcode Scanner application is designed to be able to scan barcodes for whatever other applications may need it.

More important, our app is completely decoupled from the BarcodeScanner app. There’s no integration- in fact, neither application is checking to verify that the other exists. If the user preferred, they could remove “Barcode Scanner” and replace it with a competing app. As long as that app supported the same intent, functionality would remain the same. This decoupling is important. It’s the easy way. It’s the lazy way. It’s the Android way.

Sharing Data Using Intents

One of the most inherently useful Android intents is the Share intent. You can let the user share data to any service they want, without writing the sharing code yourself, simply by creating a share intent.

Intent intent=new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

// Add data to the intent, the receiving app will decide what to do with it.
intent.putExtra(Intent.EXTRA_SUBJECT, “Some Subject Line”);
intent.putExtra(Intent.EXTRA_TEXT, “Body of the message, woot!”);

... and starting it with a chooser:

startActivity(Intent.createChooser(intent, “How do you want to share?”));

With these 5 lines of code, you get to bypass authenticating, credential storage/management, web API interaction via http posts, all sorts of things. Where by “bypass”, I mean “have something else take care of.” Like the barcode scanning intent, all you really had to do was declare that you have something you’d like to share, and let the user choose from a list of takers. You’re not limited to sending text, either. Here’s how you’d create an intent to share an image:

private Intent createShareIntent() {
...
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("image/*");

// For a file in shared storage. For data in private storage, use a ContentProvider.
Uri uri = Uri.fromFile(getFileStreamPath(pathToImage));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
return shareIntent;
}

Note that just by using setType() to set a MIME type, you’ve filtered down the list of apps to those that will know what to do with an image file.

Intents over Integration

Think about this for a second. By making the simple assumption that any user of any service (Task Manager, Social Network, Photo sharing site) already has some app on their phone that can share to that service, you can leverage the code that they’ve already written. This has several awesome implications:

  • Less UI — You don’t have to clog up your UI with customized, clickable badges of services you support. Just add a “share” button. It’s okay, we’ve made sure all your users know what it does [insert smiley here].

  • Leveraged UI — You can bet that every high-quality web service out there has spent serious time on the UI of their Android app’s “share” activity. Don’t reinvent the wheel! Just grab a couple and go for a ride.

  • Filtered for the user — If I don’t have a Foo-posting app on my phone, there’s a good chance I don’t care about posting to Foo. Now I won’t see Foo icons everywhere that are useless to me.

  • Client App Ecosystem — Much like an email client, anyone can write a client for any service. Users will use the ones they want, uninstall the ones they don’t. Your app supports them all.

  • Forward Compatible with new services — If some swanky new service springs up out of nowhere with an Android Application, as long as that application knows how to receive the share intent, you already support it. You don’t spend time in meetings discussing whether or not to wedge support for the new service into your impending Next Release(tm), you don’t burn engineering resources on implementing support as fast as possible, you don’t even upload a new version of anything to Android Market. Above all, you don’t do any of that again next week, when another new service launches and the whole process threatens to repeat itself. You just hang back and let your users download an application that makes yours even more useful.

Avoid One-Off Integrations

For each pro of the Intent approach, integrating support to post to these services one-at-a-time has a corresponding con.

  • Bad for UI — If your photo-sharing app has a Foo icon, what you might not immediately understand is that while you’re trying to tell the user “We post to Foo!” what you’re really saying is “We don’t post to Bar, Baz, or let you send the photo over email, sms, or bluetooth. If we did, there would be icons. In fact, we probably axed those features because of the space the icons would take on our home screen. Oh, and we’ll probably use some weird custom UI and make you authenticate through a browser, instead of the Foo client you already have installed.” I’m not going to name names, but a lot of you are guilty of this. It’s time to stop. (I mean it. Stop.)

  • Potentially wasted effort — Let’s say you chose one service, and integrated it into your UI perfectly. Through weeks of back-and-forth with Foo’s staff, you’ve got the API and authentication mechanisms down pat, the flow is seamless, everything’s great. Only problem is that you just wasted all that effort, because none of your user-base particularly cares for Foo. Ouch!

  • Not forward compatible for existing services — Any breaking changes in the API are your responsibility to fix, quickly, and that fix won’t be active until your users download a newer version of your app.

  • Won’t detect new services — This one really hurts. If a brand new service Baz comes out, and you’ve actually got the engineering cycles to burn, you need to get the SDK, work out the bugs, develop a sharing UI, have an artist draw up your own “edgy” (ugh) but legally distinct version of the app’s logo so you can plaster it on your home screen, work out all the bugs, and launch.

You will be judged harshly by your users. And deservedly so.

Ice Cream Sandwich makes it even easier

With the release of ICS, a useful tool for sharing called ShareActionProvider was added to the framework, making the sharing of data across Android applications even easier. ShareActionProviders let you populate lists of custom views representing ACTION_SEND targets, facilitating (for instance) adding a “share” menu to the ActionBar, and connecting it to whatever data the user might want to send.

Doing so is pretty easy. Configure the menu items in your Activity’s onCreateOptionsMenu method, like so:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Get the menu item.
MenuItem menuItem = menu.findItem(R.id.menu_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) menuItem.getActionProvider();

// Attach an intent to this ShareActionProvider. You can update this at any time,
// like when the user selects a new piece of data they might like to share.
mShareActionProvider.setShareIntent(yourCreateShareIntentMethod());

// This line chooses a custom shared history xml file. Omit the line if using
// the default share history file is desired.
mShareActionProvider.setShareHistoryFileName("custom_share_history.xml");
. . .
}

Note that you can specify a history file, which will adapt the ordering of share targets based on past user choices. One shared history file can be used throughout an application, or different history files can be used within the same application, if you want to use a separate history based on what kind of data the user wants to share. In the above example, a custom history file is used. If you wish to use the default history for the application, you can omit that line entirely.

This will help optimize for an important feature of the ShareActionProvider: The user’s most common ways to share float to the top of the drop-down, with the least used ones disappearing below the fold of the “See More” button. The most commonly selected app will even become a shortcut right next to the dropdown, for easy one-click access!

You’ll also need to define a custom menu item in XML. Here’s an example from the ActionBar Dev Guide.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_share"
android:title="@string/share"
android:showAsAction="ifRoom"
android:actionProviderClass="android.widget.ShareActionProvider" />
</menu>

And with that, you can have an easy sharing dropdown that will look like the screenshot here. Note that you get the nice standard three-dots-two-lines “Share” glyph for free.

Remember: Smart and Easy

The share intent is the preferred method of sharing throughout the Android ecosystem. It’s how you share images from Gallery, links from the browser, and apps from Android Market. Intents are the easiest path to writing flexible applications that can participate in a rapidly expanding ecosystem, but they’re also the smart path to writing applications that will stay relevant to your users, letting them share their data to any service they want, no matter how often their preferences change over time. So take a step back and stop worrying about if your user wants to tweet, digg, post, email, im, mms, bluetooth, NFC, foo, bar or baz something. Just remember that they want to share it. Android can take it from there.

Thursday, February 2, 2012

Android Security Update

Recently, there’s been a lot of news coverage of malware in the mobile space. Over on our Mobile blog, Hiroshi Lockheimer, VP of Android engineering, has posted Android and Security. We think most Android developers will find it interesting reading.

New Social APIs in Android ICS

[This post is by Daniel Lehmann, Tech Lead on the Android Apps team. — Tim Bray]

[We’re trying something new; There’s a post over on Google+ where we’ll host a discussion of this article. Daniel Lehmann has agreed to drop by and participate. Come on over and join in!]

With Android Ice Cream Sandwich, we set out to build software that supports emotional connections between humans and the devices they carry. We wanted to build the most personal device that the user has ever owned.

The first ingredient in our recipe is to show users the people that they care about most in a magazine-like way. High-resolution photos replace simple lists of text.

The second ingredient is to more prominently visualize their friends’ activities. We show updates from multiple sources wherever a contact is displayed, without the need to open each social networking app individually.

Android is an open platform, and in Ice Cream Sandwich we provide a rich new API to allow any social networking application to integrate with the system. This post explains how apps like Google+ use these APIs, and how other social networks can do the same.

A few basics

Since Eclair (Android 2.0), the system has been able to join contacts from different sources. Android can notice if you are connected to the same person and different networks, and join those into aggregate contacts.

Essential terms to understand throughout the remainder of this post are:

  • RawContact is a contact as it exists in one source, for example a friend in Skype.

  • Data rows exists for each piece of information that the raw contact contains (name, phone number, email address, etc.).

  • A Contact joins multiple raw contacts into one aggregate. This is what the user perceives as a real contact in the People and Phone apps.

  • A sync adapter synchronizes its raw contacts with its cloud source. It can be bundled with a Market application (examples: Skype, Twitter, Google+).

While users deal with contacts, sync adapters work with their raw contact rows. They own the data inside a raw contact, but by design it is left up to Android to properly join raw contact rows with others.

Contacts sync adapters have a special xml file that describes their content, which is documented in the Android SDK. In the following paragraphs, we’ll assume this file is named contacts.xml.

The Android SDK also contains the application SampleSyncAdapter (and its source code) that implements everything mentioned in here in an easy to understand way.

High resolution photos

In Android versions prior to Honeycomb (3.0), contact photos used to be 96x96. Starting with ICS, they now have a thumbnail (which is the 96x96 version) and a display photo. The display photo’s maximum size can vary from device to device (On Galaxy Nexus and Nexus S, it is currently configured to be 256x256, but expect this to vary with future devices). The size as configured can be queried like this:

private static int getPhotoPickSize(Context context) {
// Note that this URI is safe to call on the UI thread.
Cursor c = context.getContentResolver().query(DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI,
new String[]{ DisplayPhoto.DISPLAY_MAX_DIM }, null, null, null);
try {
c.moveToFirst();
return c.getInt(0);
} finally {
c.close();
}
}

This value is useful if you need to query the picture from the server (as you can specify the right size for the download). If you already have a high resolution picture, there is no need for any resizing on your side; if it is too big, the contacts provider will downsample it automatically.

Up until now, pictures were written using a ContentValues object, just like all the other data rows of the raw contact. While this approach is still supported, it might fail when used with bigger pictures, as there is a size limit when sending ContentValues across process boundaries. The prefered way now is to use an AssetFileDescriptor and write them using a FileOutputStream instead:

private static void saveBitmapToRawContact(Context context, long rawContactId, byte[] photo) throws IOException {
Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
Uri outputFileUri =
Uri.withAppendedPath(rawContactUri, RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
AssetFileDescriptor descriptor = context.getContentResolver().openAssetFileDescriptor(
outputFileUri, "rw");
FileOutputStream stream = descriptor.createOutputStream();
try {
stream.write(photo);
} finally {
stream.close();
descriptor.close();
}
}

For best results, store uncompressed square photos and let the contacts provider take care of compressing the photo. It will create both a thumbnail and a display photo as necessary.

This API is available on API version 14+. For older versions, we recommend to fallback to the old method using ContentValues and assuming a constant size of 96x96.

Update streams

The API for update streams is the biggest new addition for contacts in Ice Cream Sandwich. Sync adapters can now enrich their contact data by providing a social stream that includes text and photos.

This API is intended to provide an entry point into your social app to increase user engagement. We chose to only surface the most recent few stream items, as we believe that your social app will always be the best way to interact with posts on your network.

StreamItems rows are associated with a raw contact row. They contain the newest updates of that raw contact, along with text, time stamp and comments. They can also have pictures, which are stored in StreamItemPhotos. The number of stream items per raw contact has a limit, which on the current Nexus devices is set to 5, but expect this number to change with future devices. The limit can be queried like this:

private static int getStreamItemLimit(Context context) {
// Note that this URI is safe to call on the UI thread.
Cursor c = context.getContentResolver().query(StreamItems.CONTENT_LIMIT_URI,
new String[]{ StreamItems.MAX_ITEMS }, null, null, null);
try {
c.moveToFirst();
return c.getInt(0);
} finally {
c.close();
}
}

When displayed in the People app, stream items from all participating raw contacts will be intermixed and shown chronologically.

The following function shows how to add a stream item to an existing raw contact:

private static void addContactStreamItem(Context context, long rawContactId, String text,
String comments, long timestamp, String accountName, String accountType){
ContentValues values = new ContentValues();
values.put(StreamItems.RAW_CONTACT_ID, rawContactId);
values.put(StreamItems.TEXT, "Breakfasted at Tiffanys");
values.put(StreamItems.TIMESTAMP, timestamp);
values.put(StreamItems.COMMENTS, comments);
values.put(StreamItems.ACCOUNT_NAME, accountName);
values.put(StreamItems.ACCOUNT_TYPE, accountType);
context.getContentResolver().insert(StreamItems.CONTENT_URI, values);
}

You can also specify an action that should be executed when a stream item or one of its photos is tapped. To achieve this, specify the receiving Activities in your contacts.xml using the tags viewStreamItemActivity and viewStreamItemPhotoActivity:

<ContactsAccountType
xmlns:android="http://schemas.android.com/apk/res/android"
viewStreamItemActivity="com.example.activities.ViewStreamItemActivity”
viewStreamItemPhotoActivity="com.example.activities.ViewStreamItemPhotoActivity">
<!-- Description of your data types -->
</ContactsAccountType>

Update streams are available on API version 15+ and are intended to replace the StatusUpdate API. For previous versions, we recommend that you fall back to the StatusUpdates API, which only shows a single text item and no pictures.

“Me” profile

Ice Cream Sandwich is the first version of Android that supports the “Me” contact, which is prominently shown at the top of the list of the new People app. This simplifies use-cases that used to be a multi-tap process in previous versions — for example, sharing personal contact data with another person or “navigating home” in a navigation app. Also it allows applications to directly address the user by name and show their photo.

The “Me” profile is protected by the new permissions READ_PROFILE and WRITE_PROFILE. The new functionality is powerful; READ_PROFILE lets developers access users’ personally identifying information. Please make sure to inform the user on why you require this permission.

The entry point to the new API is ContactsContract.Profile and is available on API version 14+.

Add connection

Previously, connecting with users on a social network involved opening the respective social networking app, searching for the person and then connecting (“Friend”, “Follow” etc.). Ice Cream Sandwich has a much slicker approach: When looking at an existing contact in the People application, the user can decide to add this person to another network as well. For example, the user might want to follow a person on Google+ that they already have as a contact in Gmail.

Once the user taps one of the “Add connection” commands, the app is launched and can look for the person using the information that is already in the contact. Search criteria are up to the app, but good candidates are name, email address or phone number.

To specify your “Add connection” menu item, use the attributes inviteContactActivity and inviteContactActionLabel in your contacts.xml:

<ContactsAccountType
xmlns:android="http://schemas.android.com/apk/res/android"
inviteContactActivity="com.example.activities.InviteContactActivity"
inviteContactActionLabel="@string/invite_action_label">
<!-- Description of your data types -->
</ContactsAccountType>

Be sure to use the same verb as you typically use for adding connections, so that in combination with your app icon the user understands which application is about to be launched.

The “Add connection” functionality is available on API version 14+.

Contact-view notification

High-resolution pictures need a lot of space, and social streams quickly become outdated. It is therefore not a good idea to keep the whole contacts database completely in sync with the social network. A well-written sync adapter should take importance of contacts into account; as an example, starred contacts are shown with big pictures, so high-resolution pictures are more important. Your network might also have its own metrics that can help to identify important contacts.

For all other contacts, you can register to receive a notification which is sent by the People app to all sync adapters that contribute to a contact whenever the contact’s detail page is opened. At that point, you can provide additional information. As an example, when the Google+ sync adapter receives this notification, it pulls in the high-resolution photo and most recent social stream posts for that user and writes them to the contacts provider. This can be achieved by adding the viewContactNotifyService attribute to contacts.xml:

<ContactsAccountType
xmlns:android="http://schemas.android.com/apk/res/android"
viewContactNotifyService="com.example.notifier.NotifierService">
<!-- Description of your data types -->
</ContactsAccountType>

When this Intent is launched, its data field will point to the URI of the raw contact that was opened.

These notifications are available with API version 14+.

Summary

With Ice Cream Sandwich, we improved key areas around high resolution photos and update streams, and simplified the creation of new connections.

Everything outlined in here is done using open APIs that can be implemented by any network that wants to participate. We’re excited to see how developers take advantage of these new features!

Monday, January 30, 2012

Android Developers on Google+

[This post is by Reto Meier, Android Developer Relations Tech Lead. — Tim Bray]

I’ve been fortunate enough to be involved with Android since the 0.9 preview SDK was released to developers back in 2007. A lot has changed since then, but one thing that hasn’t is the rapid pace at which new tools, resources, and information have become available for us Android developers. Just look at the last few months.

In December Android Training launched, with its first set of classes designed to demonstrate the best practices behind building great Android Apps.

Earlier this month, the Android design site went live — offering a place to learn about the principles, building blocks, and patterns you need to make good design decisions when creating your Android app interfaces.

We’ve got a lot more planned in the coming year, so to help you keep abreast of all the latest Android developer news we’re launching the +Android Developers page on Google+!

One of my favourite things about Google+ is the quality of conversation around posts, so +Android Developers will focus on being a place for the people behind the Android developer experience, and Android developers all around the world, to meet and discuss the latest in Android app development.

We’ll be posting development tips, discussing updates to the SDK and developer tools, highlighting new Android training classes, and posting video and pics from Android developer events around the world.

We’ll also be using Google+ Hangouts to help us all interact even more closely. Starting with weekly broadcast office-hours on Hangouts On Air to answer Android development questions. These will happen every Wednesday at 2pm Pacific Time (10pm UTS) in Mountain View—expect to see these hangouts in more time zones as our teams in London, Sydney, and Tokyo get involved. Each hangout will be recorded for YouTube, so if you can’t join us live you won’t miss out.

It turns out that hangouts are a lot of fun, so we’ll be doing more of these that feature interviews with Google engineers and 3rd party Android app developers willing to share their tips and experiences.

We’re looking forward to interacting with you even more closely, so add us to your circles, join the conversation by commenting on posts, and join the hangouts. We can't wait to hear what you have to say.

Thursday, January 26, 2012

Say Goodbye to the Menu Button

[This post is by Scott Main, lead tech writer for developer.android.com. — Tim Bray]

Before Android 3.0 (Honeycomb), all Android-powered devices included a dedicated Menu button. As a developer, you could use the Menu button to display whatever options were relevant to the user, often using the activity’s built-in options menu. Honeycomb removed the reliance on physical buttons, and introduced the ActionBar class as the standard solution to make actions from the user options immediately visible and quick to invoke. In order to provide the most intuitive and consistent user experience in your apps, you should migrate your designs away from using the Menu button and toward using the action bar. This isn’t a new concept — the action bar pattern has been around on Android even before Honeycomb — but as Ice Cream Sandwich rolls out to more devices, it’s important that you begin to migrate your designs to the action bar in order to promote a consistent Android user experience.

You might worry that it’s too much work to begin using the action bar, because you need to support versions of Android older than Honeycomb. However, it’s quite simple for most apps because you can continue to support the Menu button on pre-Honeycomb devices, but also provide the action bar on newer devices with only a few lines of code changes.

If I had to put this whole post into one sentence, it’d be: Set targetSdkVersion to 14 and, if you use the options menu, surface a few actions in the action bar with showAsAction="ifRoom".

Don’t call it a menu

Not only should your apps stop relying on the hardware Menu button, but you should stop thinking about your activities using a “menu button” at all. Your activities should provide buttons for important user actions directly in the action bar (or elsewhere on screen). Those that can’t fit in the action bar end up in the action overflow.

In the screenshot here, you can see an action button for Search and the action overflow on the right side of the action bar.

Even if your app is built to support versions of Android older than 3.0 (in which apps traditionally use the options menu panel to display user options/actions), when it runs on Android 3.0 and beyond, there’s no Menu button. The button that appears in the system/navigation bar represents the action overflow for legacy apps, which reveals actions and user options that have “overflowed off the screen.”

This might seem like splitting hairs over terminology, but the name action overflow promotes a different way of thinking. Instead of thinking about a menu that serves as a catch-all for various user options, you should think more about which user options you want to display on the screen as actions. Those that don't need to be on the screen can overflow off the screen. Users can reveal the overflow and other options by touching an overflow button that appears alongside the on-screen action buttons.

Action overflow button for legacy apps

If you’ve already developed an app to support Android 2.3 and lower, then you might have noticed that when it runs on a device without a hardware Menu button (such as a Honeycomb tablet or Galaxy Nexus), the system adds the action overflow button beside the system navigation.

This is a compatibility behavior for legacy apps designed to ensure that apps built to expect a Menu button remain functional. However, this button doesn’t provide an ideal user experience. In fact, in apps that don’t use an options menu anyway, this action overflow button does nothing and creates user confusion. So you should update your legacy apps to remove the action overflow from the navigation bar when running on Android 3.0+ and begin using the action bar if necessary. You can do so all while remaining backward compatible with the devices your apps currently support.

If your app runs on a device without a dedicated Menu button, the system decides whether to add the action overflow to the navigation bar based on which API levels you declare to support in the <uses-sdk> manifest element. The logic boils down to:

  • If you set either minSdkVersion or targetSdkVersion to 11 or higher, the system will not add the legacy overflow button.

  • Otherwise, the system will add the legacy overflow button when running on Android 3.0 or higher.

  • The only exception is that if you set minSdkVersion to 10 or lower, set targetSdkVersion to 11, 12, or 13, and you do not use ActionBar, the system will add the legacy overflow button when running your app on a handset with Android 4.0 or higher.

That exception might be a bit confusing, but it’s based on the belief that if you designed your app to support pre-Honeycomb handsets and Honeycomb tablets, it probably expects handset devices to include a Menu button (but it supports tablets that don’t have one).

So, to ensure that the overflow action button never appears beside the system navigation, you should set the targetSdkVersion to 14. (You can leave minSdkVersion at something much lower to continue supporting older devices.)

Migrating to the action bar

If you have activities that use the options menu (they implement onCreateOptionsMenu()), then once the legacy overflow button disappears from the system/navigation bar (because you’ve set targetSdkVersion to 14), you need to provide an alternative means for the user to access the activity’s actions and other options. Fortunately, the system provides such a means by default: the action bar.

Add showAsAction="ifRoom" to the <item> elements representing the activity’s most important actions to show them in the action bar when space is available. For help deciding how to prioritize which actions should appear in the action bar, see Android Design’s Action Bar guide.

To further provide a consistent user experience in the action bar, we suggest that you use action icons designed by the Android UX Team where appropriate. The available icons support common user actions such as Refresh, Delete, Attach, Star, Share and more, and are designed for the light and dark Holo themes; they’re available on the Android Design downloads page.

If these icons don’t accommodate your needs and you need to create your own, you should follow the Iconography design guide.

Removing the action bar

If you don’t need the action bar, you can remove it from your entire app or from individual activities. This is appropriate for apps that never used the options menu or for apps in which the action bar doesn’t meet design needs (such as games). You can remove the action bar using a theme such as Theme.Holo.NoActionBar or Theme.DeviceDefault.NoActionBar.

In order to use such a theme and remain backward compatible, you can use Android’s resource system to define different themes for different platform versions, as described by Adam Powell’s post, Holo Everywhere. All you need is your own theme, which you define to inherit different platform themes depending on the current platform version.

For example, here’s how you can declare a custom theme for your application:

<application android:theme="@style/NoActionBar">

Or you can instead declare the theme for individual <activity> elements.

For pre-Honeycomb devices, include the following theme in res/values/themes.xml that inherits the standard platform theme:

<resources>
<style name="NoActionBar" parent="@android:style/Theme">
<!-- Inherits the default theme for pre-HC (no action bar) -->
</style>
</resources>

For Honeycomb and beyond, include the following theme in res/values-v11/themes.xml that inherits a NoActionBar theme:

<resources>
<style name="NoActionBar" parent="@android:style/Theme.Holo.NoActionBar">
<!-- Inherits the Holo theme with no action bar; no other styles needed. -->
</style>
</resources>

At runtime, the system applies the appropriate version of the NoActionBar theme based on the system’s API version.

Summary

  • Android no longer requires a dedicated Menu button, some devices don’t have one, and you should migrate away from using it.

  • Set targetSdkVersion to 14, then test your app on Android 4.0.

  • Add showAsAction="ifRoom" to menu items you’d like to surface in the action bar.

  • If the ActionBar doesn’t work for your app, you can remove it with Theme.Holo.NoActionBar or Theme.DeviceDefault.NoActionBar.

For information about how you should design your action bar, see Android Design’s Action Bar guide. More information about implementing the action bar is also available in the Action Bar developer guide.