Monday, December 19, 2011

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.

You have read this article with the title December 2011. You can bookmark this page URL http://azaquery.blogspot.com/2011/12/watch-out-for-xmlpullparsernexttext_19.html. Thanks!
Friday, December 16, 2011

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.

You have read this article with the title December 2011. You can bookmark this page URL http://azaquery.blogspot.com/2011/12/android-403-platform-and-updated-sdk_16.html. Thanks!
Thursday, December 15, 2011

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.

You have read this article with the title December 2011. You can bookmark this page URL http://azaquery.blogspot.com/2011/12/introducing-android-training_15.html. Thanks!
Wednesday, December 14, 2011

Pros and Cons: Moving from Nokia to Android

After about 15 years of using Nokia phones, I will be moving to a Samsung Galaxy S II Google Android handset.

This is a bittersweet decision, because I rate Nokia handsets as some of the most durable phones on the market. If only Nokia decided to push forward with MeeGo, or became a handset OEM like HTC, I might not be writing this entry.

I currently own a Nokia N8, which in today's handset marketplace has an inadequate processor, RAM, and arguably OS in comparison with the Dual Core 1GB RAM Android handsets.  The N8 has one feature I rate incredibly highly on a Phone however: the camera. The N8 sports a 12MP Carl Zeiss CCD. At the time of writing this, there is simply no better camera hardware on a smart phone out there. Fact.

I'm of the "one device to rule them all" mindset, so having a great camera at my fingertips is something I rate highly. The amount of times I have been able to capture critical family moments, or capture something unique and beautiful while I'm out and about have made the Nokia N8 worth every single cent.

For me, camera quality has made the transition over to Android very difficult. There are plenty of Android handsets out there with Dual Cores and 1GB RAM, but the Achilles heel of every handset I've researched is the camera. While Android phones like the Sony Ericsson Xperia Arc have probably the best camera optics out there, their overall processor and RAM specifications are, well, not up to spec.

From my research, I've come to accept there is currently no Android phone out there with the right combination of specifications for me:

  • 12MP, quality camera 
  • a Xenon flash 
  • minimum 1.2 GHz dual cores 
  • minimum 1GB RAM. 
At best, handsets have dual LED flash. Most have single LED.

I know I'm taking a downgrade in camera features, but here's how I see the losses and gains from moving from Nokia Symbian 3 to Android (in my case Gingerbread):

Nokia Losses:
  • Best of breed Carl Zeiss camera phone technology. Android OEMs: get with the program here.
  • Great handset build quality.
  • Interface familiarity.
  • Gravity Social Media client. Probably the best twitter client invented, and constantly requested by Nokia deserters using iOS and Android.
Android Gains (with Nokia N8 Symbian 3 comparisons):
  • Device specifications that are not redundant before they are even released. 
    • Nokia are only just releasing 1Ghz processor phones to the market. 
  • Rapidly evolving OS, with a reliable release cadence.
    • Symbian 3 Anna (PR2.0) worldwide deployment was delayed at least 6 months later than promised at launch. Why is this such a big deal? This update introduced a PORTRAIT QWERTY keyboard. Yes, this was not shipped by default with the original PR1.0
    • When Nokia did release PR2.0, Australia was last on the list.
    • Symbian 3 Belle (PR3.0), the next major cosmetic interface change has already slipped into next year. 
    • Android users will be amazed to hear that PR3.0 gives Symbian users a pull-down NOTIFICATIONS TRAY. Better late than never, I guess...
  • App ecosystem that has much wider commercial uptake and support. 
    • Developers rarely port apps to Symbian 3. Too much trouble for too little return.
  • Open content-rich web pages quickly and reliably. 
    • Try to open complex pages on Symbian 3 N8, and you can almost bet you'll get the "Out Of Memory" error pop up. It's embarrassing. 256MB RAM is simply not enough.
    • I recently learned that the separate GPU in the Nokia N8 is allocated a measly 32Mb. This will make it even harder for game developers to make titles backwards compatible for older devices. Makes navigation choppy, and gaming limited.
  • Having application choices for basic user tasks. 
    • Symbian 3 makes it really difficult to specify any base application that isn't core. 
    • Music Player default is basically hard-coded.
    • Camera button will only open the Symbian 3 camera interface. 
    • You can select a default browser other than the WebKit Nokia browser, which was (and still is) utter rubbish. However for native Symbian apps, the WebKit browser is loaded anyhow, totally ignoring your preferences. Grrr!
  • Google integration natively supported. 
    • On Symbian 3, I have to shoehorn in Google services. It is not natively offered.
      • GoogaSync for *multiple* Google Calendars. 
      • SyncML to get my Google contacts. 
    • The only natively-supported way to import basic Google contacts and your primary calendar is to use the single Mail for Exchange profile available. If you need that single MfE account for your work emails, you're out of luck, sport!
I won't list the different types of Nokia handsets I've owned over my lifetime as a mobile phone consumer. Most of them were revolutionary at the time, and I still have fond memories of them. I will have fond memories of the Nokia N8, but sometimes you have to realise that vendor loyalty is not a reason to stick with something.

Hopefully I won't live to regret it.



You have read this article android / nokia / Nokia N8 / Pros and Cons with the title December 2011. You can bookmark this page URL http://azaquery.blogspot.com/2011/12/pros-and-cons-moving-from-nokia-to.html. Thanks!

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.

You have read this article Games / Media and Camera with the title December 2011. You can bookmark this page URL http://azaquery.blogspot.com/2011/12/more-android-games-that-play-nice_14.html. Thanks!
Monday, December 12, 2011

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.

You have read this article IME / Text and Input with the title December 2011. You can bookmark this page URL http://azaquery.blogspot.com/2011/12/add-voice-typing-to-your-ime_12.html. Thanks!
Thursday, December 8, 2011

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...








You have read this article Android Market with the title December 2011. You can bookmark this page URL http://azaquery.blogspot.com/2011/12/a-closer-look-at-10-billion-downloads_8.html. Thanks!
Tuesday, December 6, 2011

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.
You have read this article with the title December 2011. You can bookmark this page URL http://azaquery.blogspot.com/2011/12/10-billion-android-market-downloads-and_6.html. Thanks!
Thursday, December 1, 2011

The Scourge of Christmas Past, Present, and Future

MULTI-STRAND INCANDESCENT CHRISTMAS LIGHTS. WHAT CIRCLE OF HELL DID THESE COME FROM.

<Breathe, J-man, Breathe>

OK. So last night I had the most unpleasant job of untangling a 300 string set of these Christmas Lights. Being the smart geek, I had wound them around a large postage tube to try and keep them from getting untangled, but even that didn't help.

To cut a long story short, after a lot of violent shaking, and spaghetti maze solving, I untangled the string.

After hanging the damn things, half of the string just did not work. At all. What a soul destroying waste of time. Never again.

We did purchase an LED set of lights, but it was a 100 string. We really needed a 300 string. My better half just would not put them up on the tree, saying they would look ridiculous. They probably would.

So, being the geek that I am, I got thinking about the problem and have come up with a Christmas Lights product that makes all the terrible design elements of Christmas Lights a thing of Christmas Past.

The Pitch

Modular Christmas Lights, with the following features:

  • Green (or white), flat, flexible, cable. 
  • Colour switching LEDs so you do not have to have one colour per strand. 
  • Each light string is 1m long, and has keyed connectors.
    • 20 individual LEDs per strand (a bulb every 5 cm)
    • This would give excellent light output.
  • Usable in 100, 150, 200, 250, or 300 bulb lengths:
    • Connect how ever many you need.
    • Never have the problem with trying to wrap the excess bulb length around the bottom of the tree.
  • LED bulb is mounted in a neat, terminal block style housing. 
    • One light in center of cable, but connected internally to the correct cable will look a lot better than a LED that is protruding from the cable.
    • No protruding bulbs means no tangle.
Bulb Controller, with the following features:
  • Seven modes, similar to what most offer now.
  • Music Response mode. Responds to bass frequencies to control the light pulse.
  • Each mode cycles through with a single push button (like most on market now).
  • LED 'mode' indicator built in, so you know exactly what mode is running.
  • No bulky wall plug: normal corded wall plug, with unit sitting on the floor.
  • Auto detects the modular length connected based on pre-set resistance, and adjusts light intensity accordingly.
  • Set the light intensity: soft or bright.
Packages Available:
  • 300 bulb length, for big trees.
  • 150 bulb length for small trees.
  • Other lengths sold separately, for an affordable price.
  • 150 bulb length pack controller can be expanded up to 300 bulbs with separately purchased lengths.
Pack Includes:
  • Selected bulb length.
  • Bulb Controller
  • Soft bag for lineal storage of string lengths, and all accessories
So who wants to put up some venture capital and we get these puppies onto the market for Christmas next year?






You have read this article Christmas / Geek / LED with the title December 2011. You can bookmark this page URL http://azaquery.blogspot.com/2011/12/the-scourge-of-christmas-past-present.html. Thanks!