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!