06 Feb 2012

feedAndroid Forums

Hawaii Five-0(2010) Season 2 Episode 15

Hey Guys are you ready to watch Hawaii Five-0 (2010) Season 2 Episode 15...

06 Feb 2012 12:10pm GMT

Rupaul's Drag Race Season 4 Episode 2

Get ready to watch new upcoming RuPaul's Drag Race Season 4 Episode 2...

06 Feb 2012 12:06pm GMT

Mike & Molly Season 2 Episode 14

All TV show lovers, Get ready to enjoyed interesting series with Mike & Molly Season 2 Episode 14...

06 Feb 2012 12:02pm GMT

Hart of Dixie Season 1 Episode 13

So, Guys, Are you ready to Hart of Dixie Episode 13 (http://www.eranostra.com/2012/02/06/watch-hart-of-dixie-episode-13-online-streaming/) which is...

06 Feb 2012 11:58am GMT

Kickin It Season 1 Episode 16

Get ready to watch Kickin it Episode 16...

06 Feb 2012 11:54am GMT

Alarm Clock Snooze Problem

just need to know if there's ant way to change the settings on the alarm clock to lock the touch screen after touching it to "snooze". I'm paranoid...

06 Feb 2012 11:14am GMT

My pet paragraphist is Anton Pavlovich Chekhov. In my way of thinking

, he is the greatest Russian screenwriter áåñïëàòíî ñêà÷àòü (http://megaline-warez.ru/) and short-story writer. I'm never tired of reading and...

06 Feb 2012 8:50am GMT

How dispach app from PC to Samsung Galaxy S II

Good morning from Spain, I am developer of Android and have just finished one application with environment ECLIPSE. The trouble is can't dispach...

06 Feb 2012 8:14am GMT

Pokemon game app!?

I was thinking of how much fun i had playing Pokemon when i was a kid and thought, what if there was an *app for Pokemon.* Everything exactly the...

06 Feb 2012 6:31am GMT

i need help

why i can't play my games in my galaxy mini? it's stated wen i upgrade it to gingerbread.. wat should i do to fix it? plzzzz i need help..tanx

06 Feb 2012 6:12am GMT

feedAndroid News, Rumours, and Updates

Check Out the 90 Second Galaxy Note Commercial Complete With The Darkness!

While Samsung hinted at something awesome with its 45 second teaser nothing says amazing like the full version. In case you missed our reminder earlier today in regards to the Galaxy Note and you even missed the full commercial itself in the fourth quarter of Super Bowl XLVI, worry not, we have it here for you in all [...]


Visit TalkAndroid for Android news, Android guides, and much more!

06 Feb 2012 2:55am GMT

Here’s My Perfect Android Smartphone, What’s Yours?

Everyone has an idea of what their perfect android phone would be. While I would say that the Galaxy Nexus running Codename: Android would be as close to a perfect Android experience yet; I have found that I am wanting and missing various aspects that other Android phones have or need. I often contemplate what [...]


Visit TalkAndroid for Android news, Android guides, and much more!

06 Feb 2012 12:39am GMT

05 Feb 2012

feedAndroid News, Rumours, and Updates

AT&T Samsung Galaxy Note Officially Available for Pre-Order, Delivers on February 17th

For those of you in the US who have been dying to get your hands on the awesome Samsung Galaxy Note, well you can officially place your pre-order today. Assuming you're OK with service from AT&T, you can now spend $299 to get one set aside for you and should arrive on your doorstep on [...]


Visit TalkAndroid for Android news, Android guides, and much more!

05 Feb 2012 9:58pm GMT

Review: World of Goo sticks your fingers to the screen

If you could sum up World of Goo in one word - and you didn't want to use awesome, magnificent or fantastic - magical would work just fine. The developers at 2D Boy, a team of two (that's right, two!) ex-Electronic Arts employees working out of San Francisco, have brought us an incredible world to [...]


Visit TalkAndroid for Android news, Android guides, and much more!

05 Feb 2012 9:06pm GMT

AT&T Beefs up Indianapolis Wireless Coverage in Preparation for Super Bowl XLVI

The year's biggest sports event takes place today and apparently Verizon isn't the only carrier willing to beef up wireless coverage to keep the fans happy. AT&T has also rolled out a bunch of new equipment and decided to let the public know just exactly how they planned to implement the upgrade. According to the [...]


Visit TalkAndroid for Android news, Android guides, and much more!

05 Feb 2012 7:35pm GMT

Reminder: Official Galaxy Note Commercial Airs Tonight During Super Bowl XLVI

The big day for football fans has finally arrived, but we're excited for more reasons than just watching the New England Patriots collide with the New York Giants. AT&T is releasing the Samsung Galaxy Note on February 19th and we don't want you to forget to look for the first ever Samsung Super Bowl commercial during [...]


Visit TalkAndroid for Android news, Android guides, and much more!

05 Feb 2012 5:42pm GMT

Tasks N Todos – Track Your Tasks With Style

Ever since I got my first handheld device (hello, Palm Pilot) I've been trying out different methods of keeping myself organized. It all boils down to choosing one platform to manage your To Do list, whether it's Microsoft Outlook, Remember the Milk, or Google Tasks. Since switching to Android, I've wanted to try using Google [...]


Visit TalkAndroid for Android news, Android guides, and much more!

05 Feb 2012 2:18pm GMT

Quick Rant: Why I Love My Motorola Xoom Wifi Tablet And Don’t Plan On Upgrading Anytime Soon

What does a tablet mean to you? To most, it's something that lets you have productivity on the go- emails, social communication, reading articles and e-books, etc. Of course consumers realize it's possible to do all that with a notebook computer or netbook. However, it's no secret that notebooks are losing in popularity because [...]


Visit TalkAndroid for Android news, Android guides, and much more!

05 Feb 2012 2:02am GMT

Verizon Galaxy Nexus Android 4.0.4 OTA Package Unofficially Available

A user over at Android Central received an OTA notification on his Verizon Galaxy Nexus, and managed to pull the file and make it available for download. Apparently the update contains Android 4.0.4 IMM30B. This seems to be a limited release, most likely for internal testing, so if you decide to flash this, don't be [...]


Visit TalkAndroid for Android news, Android guides, and much more!

05 Feb 2012 2:00am GMT

Mystery Device From Google Stops By The FCC

An FCC application filed by Google, Inc. suggests the possibility of a Google entertainment device is in the works. The application requests permission for a six month window in which this mystery device can be tested at the Google HQ as well as in Google employees' homes in four different cities: Mountain View CA, Los [...]


Visit TalkAndroid for Android news, Android guides, and much more!

05 Feb 2012 1:46am GMT

02 Feb 2012

feedAndroid Developers Blog

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.

02 Feb 2012 8:31pm GMT

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:

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!

02 Feb 2012 4:30pm GMT

30 Jan 2012

feedAndroid Developers Blog

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.

30 Jan 2012 6:00pm GMT

26 Jan 2012

feedAndroid Developers Blog

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:

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. Here they are!

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

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.

26 Jan 2012 8:10pm GMT

16 Jan 2012

feedAndroid Developers Blog

Southern-hemisphere Developer Labs

We've just scheduled Android Developer Labs for Melbourne (January 31), Sydney (February 3), and Auckland (February 8). The material is not introductory; it's aimed at people with existing apps who want to make them better in the era of Ice Cream Sandwich and tablets. You'll want to show up with the SDK installed, and a couple of devices.

If this describes you, drop by the ADL page and sign up. You should hurry, because these are not large-scale events and there are more qualified people than there are seats.

16 Jan 2012 11:37pm GMT

12 Jan 2012

feedAndroid Developers Blog

Introducing the Android Design site

[This post is by Christian Robertson, who leads the Android visual design group. He is also the designer of the Roboto font family. -Tim Bray]

Ice Cream Sandwich (Android 4.0) is our biggest redesign yet - both for users and developers. We've enhanced the UI framework with new interactions and styles that will let you create Android apps that are simpler and more beautiful than ever before.

To help you in that mission, we're introducing Android Design: the place to learn about principles, building blocks, and patterns for creating world-class Android user interfaces. Whether you're a UI professional or a developer playing that role, these docs show you how to make good design decisions, big and small.

The Android User Experience Team is committed to helping you design amazing apps that people love, and this is just the beginning. In the coming months, we'll expand Android Design with more in-depth content. And watch this blog for a series of posts about design, and invitations to Google+ hangouts on the topics you care about most.

So head on over to Android Design, and make something amazing!

12 Jan 2012 9:00pm GMT

10 Jan 2012

feedAndroid Developers Blog

Levels in Renderscript

[This post is by R. Jason Sams, an Android Framework engineer who specializes in graphics, performance tuning, and software architecture. -Tim Bray]

For ICS, Renderscript (RS) has been updated with several new features to simplify adding compute acceleration to your application. RS is interesting for compute acceleration when you have large buffers of data on which you need to do significant processing. In this example we will look at applying a levels/saturation operation on a bitmap.

In this case, saturation is implemented by multiplying every pixel by a color matrix Levels are typically implemented with several operations.

  1. Input levels are adjusted.

  2. Gamma correction.

  3. Output levels are adjusted.

  4. Clamp to the valid range.

A simple implementation of this might look like:

for (int i=0; i < mInPixels.length; i++) {
    float r = (float)(mInPixels[i] & 0xff);
    float g = (float)((mInPixels[i] >> 8) & 0xff);
    float b = (float)((mInPixels[i] >> 16) & 0xff);

    float tr = r * m[0] + g * m[3] + b * m[6];
    float tg = r * m[1] + g * m[4] + b * m[7];
    float tb = r * m[2] + g * m[5] + b * m[8];
    r = tr;
    g = tg;
    b = tb;

    if (r < 0.f) r = 0.f;
    if (r > 255.f) r = 255.f;
    if (g < 0.f) g = 0.f;
    if (g > 255.f) g = 255.f;
    if (b < 0.f) b = 0.f;
    if (b > 255.f) b = 255.f;

    r = (r - mInBlack) * mOverInWMinInB;
    g = (g - mInBlack) * mOverInWMinInB;
    b = (b - mInBlack) * mOverInWMinInB;

    if (mGamma != 1.0f) {
        r = (float)java.lang.Math.pow(r, mGamma);
        g = (float)java.lang.Math.pow(g, mGamma);
        b = (float)java.lang.Math.pow(b, mGamma);
    }

    r = (r * mOutWMinOutB) + mOutBlack;
    g = (g * mOutWMinOutB) + mOutBlack;
    b = (b * mOutWMinOutB) + mOutBlack;

    if (r < 0.f) r = 0.f;
    if (r > 255.f) r = 255.f;
    if (g < 0.f) g = 0.f;
    if (g > 255.f) g = 255.f;
    if (b < 0.f) b = 0.f;
    if (b > 255.f) b = 255.f;

    mOutPixels[i] = ((int)r) + (((int)g) << 8) + (((int)b) << 16)
                    + (mInPixels[i] & 0xff000000);
}

This code assumes a bitmap has been loaded and transferred to an integer array for processing. Assuming the bitmaps are already loaded, this is simple.

        mInPixels = new int[mBitmapIn.getHeight() * mBitmapIn.getWidth()];
        mOutPixels = new int[mBitmapOut.getHeight() * mBitmapOut.getWidth()];
        mBitmapIn.getPixels(mInPixels, 0, mBitmapIn.getWidth(), 0, 0,
                            mBitmapIn.getWidth(), mBitmapIn.getHeight());

Once the data is processed with the loop, putting it back into the bitmap to draw is simple.

        mBitmapOut.setPixels(mOutPixels, 0, mBitmapOut.getWidth(), 0, 0,
                             mBitmapOut.getWidth(), mBitmapOut.getHeight());

The full code of the application is around 232 lines when you include code to compute the constants for the filter kernel, manage the controls, and display the image. On the devices I have laying around this takes about 140-180ms to process an 800x423 image.

What if that is not fast enough?

Porting the kernel of this image processing to RS (available at android-renderscript-samples) is quite simple. The pixel processing kernel above, reimplemented for RS looks like:

void root(const uchar4 *in, uchar4 *out, uint32_t x, uint32_t y) {
    float3 pixel = convert_float4(in[0]).rgb;
    pixel = rsMatrixMultiply(&colorMat, pixel);
    pixel = clamp(pixel, 0.f, 255.f);
    pixel = (pixel - inBlack) * overInWMinInB;
    if (gamma != 1.0f)
        pixel = pow(pixel, (float3)gamma);
    pixel = pixel * outWMinOutB + outBlack;
    pixel = clamp(pixel, 0.f, 255.f);
    out->xyz = convert_uchar3(pixel);
}

It takes far fewer lines of code because of the built-in support for vectors of floats, matrix operations, and format conversions. Also note that there is no loop present.

The setup code is slightly more complex because you also need to load the script.

        mRS = RenderScript.create(this);
        mInPixelsAllocation = Allocation.createFromBitmap(mRS, mBitmapIn,
                                                          Allocation.MipmapControl.MIPMAP_NONE,
                                                          Allocation.USAGE_SCRIPT);
        mOutPixelsAllocation = Allocation.createFromBitmap(mRS, mBitmapOut,
                                                           Allocation.MipmapControl.MIPMAP_NONE,
                                                           Allocation.USAGE_SCRIPT);
        mScript = new ScriptC_levels(mRS, getResources(), R.raw.levels);

This code creates the RS context. It then uses this context to create two memory allocations to hold the RS copy of the bitmap data. Last, it loads the script to process the data.

Also in the source there are a few small blocks of code to copy the computed constants to the script when they change. Because we reflect the globals from the script this is easy.

        mScript.set_inBlack(mInBlack);
        mScript.set_outBlack(mOutBlack);
        mScript.set_inWMinInB(mInWMinInB);
        mScript.set_outWMinOutB(mOutWMinOutB);
        mScript.set_overInWMinInB(mOverInWMinInB);

Earlier we noted that there was no loop to process all the pixels. The RS code that processes the bitmap data and copies the result back looks like this:

        mScript.forEach_root(mInPixelsAllocation, mOutPixelsAllocation);
        mOutPixelsAllocation.copyTo(mBitmapOut);

The first line takes the script and processes the input allocation and places the result in the output allocation. It does this by calling the natively compiled version of the script above once for each pixel in the allocation. However, unlike the dalvik implementation, the primitives will automatically launch extra threads to do the work. This, combined with the performance of native code can produce large performance gains. I'll show the results with and without the gamma function working because it adds a lot of cost.

800x423 image

Device Dalvik RS Gain
Xoom 174ms 39ms 4.5x
Galaxy Nexus 139ms 30ms 4.6x
Tegra 30 device 136ms 19ms 7.2x

800x423 image with gamma correction

Device Dalvik RS Gain
Xoom 994ms 259ms 3.8x
Galaxy Nexus 787ms 213ms 3.7x
Tegra 30 device 783ms 104ms 7.5x

These large gains represent a large return on the simple coding investment shown above.

10 Jan 2012 9:43pm GMT

03 Jan 2012

feedAndroid Developers Blog

Holo Everywhere

[This post is by Adam Powell, an Android Framework engineer who cares about style. -Tim Bray]

Android 4.0 showcases the Holo theme family, further refined since its debut in Android 3.0. But as most developers know, a new system theme for some Android devices isn't a new or uncommon event. For developers new system themes mean more design targets for their apps. Using system themes means developers can take advantage of a user's existing expectations and it can save a lot of production time, but only if an app designer can reliably predict the results. Before Android 4.0 the variance in system themes from device to device could make it difficult to design an app with a single predictable look and feel. We set out to improve this situation for the developer community in Ice Cream Sandwich and beyond.

Theme.Holo

If you're not already familiar with Android's style and theme system, you should read Styles and Themes before continuing.

Compatibility Standard

In Android 4.0, Holo is different. We've made the inclusion of the unmodified Holo theme family a compatibility requirement for devices running Android 4.0 and forward. If the device has Android Market it will have the Holo themes as they were originally designed.

This standardization goes for all of the public Holo widget styles as well. The Widget.Holo styles will be stable from device to device, safe for use as parent styles for incremental customizations within your app.

The Holo theme family in Android 4.0 consists of the themes Theme.Holo, Theme.Holo.Light, and Theme.Holo.Light.DarkActionBar. Examples of these themes in action are shown in the screenshots lining this post.

To use a Holo theme, explicitly request one from your manifest on your activity or application element, e.g. android:theme="@android:style/Theme.Holo". Your app will be displayed using the unmodified theme on all compatible Android 4.0 devices. The Holo themes may also be used as stable parent themes for app-level theme customizations.

What about device themes?

We have no desire to restrict manufacturers from building their own themed experience across their devices. In fact we've gone further to make this even easier. In Android 4.0's API (level 14) we've added a new public theme family to complement the Holo family introduced in Android 3.0: DeviceDefault. DeviceDefault themes are aliases for the device's native look and feel. The DeviceDefault theme family and widget style family offer ways for developers to target the device's native theme with all customizations intact.

Theme.Holo.Light

Formally separating these theme families will also make future merges easier for manufacturers updating to a new platform version, helping more devices update more quickly. Google's Nexus devices alias DeviceDefault to the unmodified Holo themes.

Making use of your chosen theme

We've added a number of theme attributes to report common metrics and color palette info to apps that want to fit in with a theme. These include highlight colors, default padding and margins for common UI elements such as list items, and more. Apps that wish to integrate with their chosen theme (both Holo and DeviceDefault included) can refer to these theme attributes as in the examples below:

Sample button with system-supplied touch highlight:

<ImageButton android:id="@+id/my_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/button_icon"
    android:background="?android:attr/selectableItemBackground" />

Sample widget with a custom pressedHighlightColor attribute, value retrieved from the system theme:

<MyWidget android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    myapp:pressedHighlightColor="?android:attr/colorPressedHighlight" />

Sample list item layout using system-supplied metrics and text appearance:

<LinearLayout android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
    android:paddingRight="?android:attr/listPreferredItemPaddingRight">
    <TextView android:id="@+id/text"
        android:textAppearance="?android:attr/textAppearanceListItem" />
    <!-- Other views here -->
</LinearLayout>

Theme.Holo.Light.DarkActionBar
(Available in API level 14 and above)

Defaults for Older Apps

If an app does not explicitly request a theme in its manifest, Android 4.0 will determine the default theme based on the app's targetSdkVersion to maintain the app's original expectations: For values less than 11, @android:style/Theme; between 11 and 13 @android:style/Theme.Holo; and for 14 and higher @android:style/Theme.DeviceDefault.

Using Holo while supporting Android 2.x

Most Android developers will still want to support 2.x devices for a while as updates and new devices continue to roll out. This doesn't stop you from taking advantage of newer themes on devices that support them though. Using Android's resource system you can define themes for your app that are selected automatically based on the platform version of the device it's running on.

Theme.Holo and Theme.Holo.Light have been available since API level 11, but Theme.Holo.Light.DarkActionBar is new in API level 14.

res/values/themes.xml:

<resources>
    <style name="MyTheme" parent="@android:style/Theme">
        <!-- Any customizations for your app running on pre-3.0 devices here -->
    </style>
</resources>

res/values-v11/themes.xml:

<resources>
    <style name="MyTheme" parent="@android:style/Theme.Holo">
        <!-- Any customizations for your app running on devices with Theme.Holo here -->
    </style>
</resources>

Finally, in AndroidManifest.xml:

<!-- [...] -->
    <application android:name="MyApplication"
            android:label="@string/application_label"
            android:icon="@drawable/app_icon"
            android:hardwareAccelerated="true"
            android:theme="@style/MyTheme">
<!-- [...] -->

You can go as far with this idea as you like, up to and including defining your own theme attributes with different values across configurations for use in your other resources. To learn more about Android's resource system, see Application Resources.

Final Thoughts

Android apps running on 4.0 and forward can use the Holo themes and be assured that their look and feel will not change when running on a device with a custom skin. Apps that wish to use the device's default styling can do so using the DeviceDefault themes that are now in the public API. These changes let you spend more time on your design and less time worrying about what will be different from one device to another. Finally, Android's resource system allows you to support features from the latest platform version while offering graceful fallback on older devices.

03 Jan 2012 9:35pm GMT

19 Dec 2011

feedAndroid Developers Blog

Watch out for XmlPullParser.nextText()

Jesse Wilson

[This post is by Jesse Wilson from the Dalvik team. -Tim Bray]

Using XmlPullParser is an efficient and maintainable way to parse XML on Android. Historically Android has had two implementations of this interface:

The implementation from Xml.newPullParser() had a bug where calls to nextText() didn't always advance to the END_TAG as the documentation promised it would. As a consequence, some apps may be working around the bug with extra calls to next() or nextTag():

    public void parseXml(Reader reader)
            throws XmlPullParserException, IOException {
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(reader);

        parser.nextTag();
        parser.require(XmlPullParser.START_TAG, null, "menu");
        while (parser.nextTag() == XmlPullParser.START_TAG) {
            parser.require(XmlPullParser.START_TAG, null, "item");
            String itemText = parser.nextText();
            parser.nextTag(); // this call shouldn't be necessary!
            parser.require(XmlPullParser.END_TAG, null, "item");
            System.out.println("menu option: " + itemText);
        }
        parser.require(XmlPullParser.END_TAG, null, "menu");
    }

    public static void main(String[] args) throws Exception {
        new Menu().parseXml(new StringReader("<?xml version='1.0'?>"
                + "<menu>"
                + "  <item>Waffles</item>"
                + "  <item>Coffee</item>"
                + "</menu>"));
    }

In Ice Cream Sandwich we changed Xml.newPullParser() to return a KxmlParser and deleted our ExpatPullParser class. This fixes the nextTag() bug. Unfortunately, apps that currently work around the bug may crash under Ice Cream Sandwich:

org.xmlpull.v1.XmlPullParserException: expected: END_TAG {null}item (position:START_TAG <item>@1:37 in java.io.StringReader@40442fa8) 
     at org.kxml2.io.KXmlParser.require(KXmlParser.java:2046)
     at com.publicobject.waffles.Menu.parseXml(Menu.java:25)
 at com.publicobject.waffles.Menu.main(Menu.java:32)

The fix is to call nextTag() after a call to nextText() only if the current position is not an END_TAG:

  while (parser.nextTag() == XmlPullParser.START_TAG) {
      parser.require(XmlPullParser.START_TAG, null, "item");
      String itemText = parser.nextText();
      if (parser.getEventType() != XmlPullParser.END_TAG) {
          parser.nextTag();
      }
      parser.require(XmlPullParser.END_TAG, null, "item");
      System.out.println("menu option: " + itemText);
  }

The code above will parse XML correctly on all releases. If your application uses nextText() extensively, use this helper method in place of calls to nextText():

  private String safeNextText(XmlPullParser parser)
          throws XmlPullParserException, IOException {
      String result = parser.nextText();
      if (parser.getEventType() != XmlPullParser.END_TAG) {
          parser.nextTag();
      }
      return result;
  }

Moving to a single XmlPullParser simplifies maintenance and allows us to spend more energy on improving system performance.

19 Dec 2011 6:55pm GMT

16 Dec 2011

feedAndroid Developers Blog

Android 4.0.3 Platform and Updated SDK tools

Today we are announcing Android 4.0.3, an incremental release of the Android 4.0 (Ice Cream Sandwich) platform. The new release includes a variety of optimizations and bug fixes for phones and tablets, as well as a small number of new APIs for developers. The new API level is 15.

Some of the new APIs in Android 4.0.3 include:

Social stream API in Contacts provider: Applications that use social stream data such as status updates and check-ins can now sync that data with each of the user's contacts, providing items in a stream along with photos for each. This new API lets apps show users what the people they know are doing or saying, in addition to their photos and contact information.

Calendar provider enhancements. Apps can now add color to events, for easier tracking, and new attendee types and states are now available.

New camera capabilities. Apps can now check and manage video stabilization and use QVGA resolution profiles where needed.

Accessibility refinements. Improved content access for screen readers and new status and error reporting for text-to-speech engines.

Incremental improvements in graphics, database, spell-checking, Bluetooth, and more.

For a complete overview of what's new in the platform, see the Android 4.0.3 API Overview.

Going forward, we'll be focusing our partners on Android 4.0.3 as the base version of Ice Cream Sandwich. The new platform will be rolling out to production phones and tablets in the weeks ahead, so we strongly encourage you to test your applications on Android 4.0.3 as soon as possible.

We would also like to remind developers that we recently released new version of the SDK Tools (r16) and of the Eclipse plug-in (ADT 16.0.1). We have also updated the NDK to r7.

Visit the Android Developers site for more information about Android 4.0.3 and other platform versions. To get started developing or testing on the new platform, you can download it into your SDK using the Android SDK Manager.

16 Dec 2011 7:00pm GMT

Introducing Android Training

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

Today I'm thrilled to announce the beta launch of Android Training - a collection of classes that we hope will help you to build better Android apps.

From designing effective navigation, to managing audio playback, to optimizing battery life, these classes are designed to demonstrate best practices for solving common Android development problems.

Each class explains the steps required to solve a problem, or implement a feature, with plenty of code snippets and sample code for you to use within your own apps.

We're starting small and this is just the beginning for Android Training. Over the coming months we will be increasing the number of classes available, as well as introducing over-arching courses and sample apps to further help your development experience.

Helping developers build great apps is what the Android Developer Relations team is all about, so we're excited to see how you use these classes to make your apps even better.

We'd love to know what you think of these classes, and what classes you'd like to see next.

16 Dec 2011 4:00am GMT

14 Dec 2011

feedAndroid Developers Blog

More Android Games that Play Nice

[This post is by Dan Galpin, who lives the Android Games lifestyle every day. - Tim Bray]

Making a game on Android is easy. Making a great game for a mobile, multitasking, often multi-core, multi-purpose system like Android is trickier. Even the best developers frequently make mistakes in the way they interact with the Android system and with other applications - mistakes that don't affect the quality of gameplay, but which affect the quality of the user's experience in other ways.

A truly great Android game knows how to play nice: how to fit seamlessly into the system of apps, services, and UI features that run on Android devices. In this multi-part series of posts, Android Developer Relations engineers who specialize in games explain what it takes to make your game play nice.

II: Navigation and Lifecycle

Android users get used to using the back key. We expect the volume keys to work in some intuitive fashion. We expect that the home key behaves in a manner consistent with the Android navigation paradigm. Sometimes we even expect the menu key to do something.

1. Problem: There's no place like [Home]

I'm playing [insert favorite game here] and I accidentally hit the [Home] key or the [Back] key. This is probably happening because I'm furiously using the touchscreen to actually play the game. Whether I've been cutting ropes, controlling aircraft, cleaving fruit, or flinging birds, I'm almost certainly angry if I've suddenly lost all of my game progress.

What went wrong?

Lots of developers assume that pressing the Home key exits a game. Perhaps this is because on some mobile devices the Home key is a somewhat-difficult-to-press physical button. Depending on the device and Android release, it might be a physical, capacitive, or soft button. This means that it is relatively easy to hit accidentally. Having progress lost by such an event as an incoming call is even worse.

How to avoid Angry Users

  1. Save as much about the status of the game into the Bundle in onSaveInstanceState() as you can. This helper function will get called whenever your application receives an onPause() callback. Note that you can save byte arrays into that bundle, so it can easily be used for raw data.

  2. If your game takes lots of native system resources, consider dumping large textures (or all textures and geometry) during onPause() or onStop(). (GLSurfaceView will do this automatically unless you tell it not to - at least you can tell it not to do so starting in API level 11). This will help your title continue to reside in memory, which will typically speed task-switching back to your game for very large titles that might otherwise be swapped out of memory, but may slow things down for smaller titles that can more efficiently multitask if they don't bother to do this.

  3. When your game resumes, restore the state from the bundle in onRestoreInstanceState(). If there is any sort of time-consuming loading that has to be done, make sure that you notify the user of what is happening to give them the best possible experience.

  4. Test thoroughly!

2. Problem: [Back] I say!

I'm in the middle of playing a game and I hit the back key. One of several bad things can happen here:

  1. The game exits immediately, losing all state and leading to Angry User Syndrome. (see Problem 1).

  2. The game does nothing.

What went wrong?

We already know what is wrong with scenario 1. It's essentially a data loss scenario, and it's worse than pigs stealing your eggs. What is wrong with scenario 2?

The [Back] key is an essential part of the Android navigation paradigm. If the back key doesn't return to the previous screen in the activity stack (or in the game hierarchy) there better be a very good reason, such as an active document with no capability to save a draft.

What to do about it

If the user is in the middle of gameplay It is customary to display some sort of dialog asking the user if they intended the action:

"Are you sure you wish to exit now? That monster looks hungry."

In an extreme action game, you might also wish to do something similar to what Replica Island (RI) did. RI assumed that any [Back] keypress that happened within 200ms of another touch event was invalid in order to make it a bit more challenging to accidentally press the key.

At the Main Menu of the game, you can decide whether it makes sense to prompt the user or not. If your game has very long load times, you might want to prompt the user.

3. Problem: Quiet [Down]!

There's nothing worse than wanting to settle down for a good session of [insert favorite game here] in some sort of public place with your volume turned up. Suddenly everyone has learned that you prefer pummelling produce to predicting present progressions and that's practically profane in your profession.

What went wrong?

By default, volume keys in most Android devices will control the ringer volume, and your application must pass the volume keys through to the super class so this continues to work.

What to do about it

In order to make these keys control the music volume (which is the channel that your game will be using), you need to call setVolumeControlStream(AudioManager.STREAM_MUSIC). As stated previously, all you need to do is pass these keys through to the framework and you'll get control of the audio in the standard and proper way. Do it as early as possible so a user can start changing the volume far before you begin playing anything.

14 Dec 2011 10:36pm GMT

12 Dec 2011

feedAndroid Developers Blog

Add Voice Typing To Your IME

[This post is by Luca Zanolin, an Android engineer who works on voice typing. - Tim Bray]

A new feature available in Android 4.0 is voice typing: the difference for users is that the recognition results appear in the text box while they are still speaking. If you are an IME developer, you can easily integrate with voice typing.

To simplify the integration, if you download this library and modify your IME as described below, everything will work smoothly on any device with Android 2.2 or later. On 4.0+, users will get voice typing, and earlier versions will use standard voice recognition; the difference is illustrated below.

To see how to integrate voice typing you can take a look at this sample IME. The IME is really simple and contains only one button: a microphone. By pressing the microphone, the user triggers voice recognition.

Here are the steps that you need to follow to integrate voice recognition into your IME.

Download the library

Download this library and add it to your IME APK.

Create the voice recognition trigger

The library contains the VoiceRecognitionTrigger helper class. Create an instance of it inside the InputMethodService#onCreate method in your IME.

public void onCreate() {
    super.onCreate();
    ...
    mVoiceRecognitionTrigger = new VoiceRecognitionTrigger(this);
}

Add the microphone icon to your IME

You need to modify the UI of your IME, add a microphone icon, and register an OnClickListener to trigger voice recognition. You can find the assets inside the sample IME. The microphone icon should be displayed only if voice recognition is installed; use VoiceRecognitionTrigger#isInstalled().

public View onCreateInputView() {
  LayoutInflater inflater = (LayoutInflater) getSystemService(
      Service.LAYOUT_INFLATER_SERVICE);
  mView = inflater.inflate(R.layout.ime, null);
  ...
  mButton = (ImageButton) mView.findViewById(R.id.mic_button);
  if (mVoiceRecognitionTrigger.isInstalled()) {
    mButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        mVoiceRecognitionTrigger.startVoiceRecognition();
      }
    });
    mButton.setVisibility(View.VISIBLE);
  } else {
    mButton.setVisibility(View.GONE);
  }
  return mView;
}

If your IME supports multiple languages, you can specify in which language recognition should be done as a parameter of startVoiceRecognition().

Notify the trigger when your IME starts

When your IME starts, you need to notify the trigger, so it can insert into the text view any pending recognition results.

@Override
public void onStartInputView(EditorInfo info, boolean restarting) {
  super.onStartInputView(info, restarting);
  if (mVoiceRecognitionTrigger != null) {
    mVoiceRecognitionTrigger.onStartInputView();
  }
}

Modify your AndroidManifest

In order to start a voice recognition through the Intent API, the library uses a service and an activity, and you need to add them into your manifest.

<manifest ... >
  <application ...>
    ...
    <service android:name="com.google.android.voiceime.ServiceHelper" />
    <activity
        android:name="com.google.android.voiceime.ActivityHelper"
        android:theme="@android:style/Theme.Translucent.NoTitleBar"
        android:excludeFromRecents="true"
        android:windowSoftInputMode="stateAlwaysHidden"
        android:finishOnTaskLaunch="true"
        android:configChanges="keyboard|keyboardHidden|navigation
                               |orientation"/>
  </application>
</manifest>

Update the microphone icon dynamically (optional)

This step is optional, but you should implement it if possible as it will improve the user experience. Voice recognition requires network access, and if there is no network, your IME should notify the user that voice recognition is currently disabled. To achieve this, you need to register the VoiceRecognitionTrigger.Listener and enable/disable the microphone accordingly.

The listener is registered in InputMethodService#onCreate, and you have to unregister it in InputMethodService#onDestroy, otherwise you will leak the listener.

@Override
public void onCreate() {
  super.onCreate();
  ... 
  mVoiceRecognitionTrigger = new VoiceRecognitionTrigger(this);
  mVoiceRecognitionTrigger.register(new VoiceRecognitionTrigger.Listener() {
    @Override
    public void onVoiceImeEnabledStatusChange() {
      updateVoiceImeStatus();
    }
  });
}

...
@Override
public void onDestroy() {
  ...
  if (mVoiceRecognitionTrigger != null) {
    mVoiceRecognitionTrigger.unregister(this);
  }
  super.onDestroy();
}

private void updateVoiceImeStatus() {
  if (mVoiceRecognitionTrigger.isInstalled()) {
    mButton.setVisibility(View.VISIBLE);
    if (mVoiceRecognitionTrigger.isEnabled()) {
      mButton.setEnabled(true);
    } else {
      mButton.setEnabled(false);
    }
  } else {
    mButton.setVisibility(View.GONE);
  }
  mView.invalidate();
}

And add this permission into your manifest:

<manifest ... >
  ...
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  ...
</manifest>

That's all there is to it

Voice recognition makes it easy for users to do more with their Android devices, so we appreciate your support in adding it to your IMEs.

12 Dec 2011 9:40pm GMT

08 Dec 2011

feedAndroid Developers Blog

A Closer Look at 10 Billion Downloads


[This post is by Eric Chu, Android Developer Ecosystem. -Dirk Dougherty]

On Tuesday, we announced that Android Market passed 10 Billion app downloads. We wanted to look a little deeper at that huge number. First question: which app was lucky number 10 billion? Photobucket Mobile. They'll be getting a great prize package, including tickets to next year's Google I/O developer conference.

Remember we still have 8 days left to celebrate 10 billion downloads with 10-cent apps on Android Market. You can follow which apps are promoted each day on +Android, our Google+ page.

Here's a graphical deep dive into 10 billion downloads...




08 Dec 2011 6:46pm GMT

06 Dec 2011

feedAndroid Developers Blog

10 Billion Android Market Downloads and Counting


[This post is by Eric Chu, Android Developer Ecosystem. -Dirk Dougherty]


One billion is a pretty big number by any measurement. However, when it's describing the speed at which something is growing, it's simply amazing. This past weekend, thanks to Android users around the world, Android Market exceeded 10 billion app downloads-with a growth rate of one billion app downloads per month. We can't wait to see where this accelerating growth takes us in 2012.


To celebrate this milestone, we partnered with some of the Android developers who contributed to this milestone to make a bunch of great Android apps available at an amazing price. Starting today for the next 10 days, we'll have a new set of awesome apps available each day for only 10 cents each. Today, we are starting with Asphalt 6 HD, Color & Draw for Kids, Endomondo Sports Tracker Pro, Fieldrunners HD, Great Little War Game, Minecraft, Paper Camera, Sketchbook Mobile, Soundhound Infinity and Swiftkey X.

Of course, none of these apps would have existed if it weren't for the developers who created them. Every day, these developers continue to push the limits on what's possible and delight us in the process. For that, we thank them.

Please join us in this 10-day celebration and check in every day to see what new apps our developer partners are making available on Android Market-for only a dime.

06 Dec 2011 6:05pm GMT

29 Nov 2011

feedAndroid Developers Blog

Games Coming to Android Market in Korea


[This post is by Eric Chu, Android Developer Ecosystem. -Dirk Dougherty]

In the 24 months since the first Android device became available locally, Korea has quickly become one of the top countries in Android device activations. In parallel, we've also seen tremendous growth in app downloads from Android Market. Korea is now the second-largest consumer of apps worldwide. Today we are adding to this momentum by bringing games to Android Market in Korea.

Starting right away, Android users in Korea can explore the many thousands of popular game titles available in Android Market and download them onto their devices. For paid games, purchasing is fast and convenient through direct carrier billing, which lets users in Korea easily charge their purchases to their monthly mobile operator bills.

If you are a game developer, now is the time to localize your game resources, app descriptions, and marketing assets to take advantage of this new opportunity. When you are ready, please visit the Android Market developer console to target your app for distribution in South Korea and set prices in Korean Won (KRW). If you don't want to distribute to Korea right away, you can also exclude it.

With the huge popularity of games on Android and the convenience of direct carrier billing in Korea, we expect to see a jump in game purchases and downloads in the weeks ahead. For game developers worldwide, it's "game on" in Korea!

29 Nov 2011 2:15am GMT