Pages

Ads 468x60px

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.

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.

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.

Wednesday, December 14, 2011

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.

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.

Saturday, December 10, 2011

WebOS Future is Open Source -HP makes code available to developers

Today, HP concluded months of deliberation, u-turns and negotiations with the announcement that it will open source WebOS instead of keeping it in-house or selling it off to suitors like Amazon.

This is good news because it ends months of uncertainty which have severely tested the patience of developers and undermined businesses that had already committed to WebOS. The fact that no hardware plans have been announced is perhaps not as big an issue as it seems -if the open sourcing of the code works, then the hardware is likely to follow.

It still remains unlikely that WebOS will, at least in its current state, pose any real challenge to Windows or Android. Though sometimes, the power of the community in open-source environments can make the difference, so it is too early to write it off altogether.

Key to the future is not only the development of the code base and the hardware available to run it, but also the distribution for the software or apps developed in WebOS. With over 100 sizeable App Stores out there, the App Catalog needs some attention as well. Hopefully HP will, as part as its committment to continue investing in WebOS, not forget this, and give the WebOS App Catalog a long needed update to keep its appeal. 

Get 50GB FREE Online Storage on Box.net! [How to]







Box.net are offering 50GB online Storage (normally 5GB) to anyone with an LG or Sony Ericsson Xperia phone. If you don't have any of these phones you can still benifit from this offer by quickly editing your "build.prop"

What you need:
Rooted Android phone
A way to edit your "build.prop" (build.prop editor, root explorer, etc.)

First open your "build.prop" (located at /system) using your prefered method and edit these two lines (Make a backup first!!!):




ro.product.manufacturer=YOUR DEVICE BRAND (ex. Samsung, HTC, Motorola, etc.)
ro.product.model=YOUR DEVICE MODEL (ex. Galaxy S II, Sensation, Droid)




Replace Brand & Model to look like this:


ro.product.manufacturer=LGE
ro.product.model=VS910 4G


All you have to do is insert  "LGE" as Brand and "VS910 4G" as model.

Save and reboot.

After reboot, open the Box.net App and register for a new account and you should receive a 50GB account.

This offer ends on the 31st December 2011!

PS: Don't forget to restore your original "build.prop" after registring and reboot again.



Adrian


Don't forget to share and like this Page on Facebook!

Friday, December 9, 2011

Next Level Android on Google Currents!

You can now add Next Level Android to your Google Currents Library!


Just tap on "Add" and search for "Next Level Android". 



Adrian

Thursday, December 8, 2011

Google Currents [APK Download, works in all countries!]


Google has just released their new services called "Google Currents", but only for People in the USA.

 

If you're not living in the USA you can download it here.



Adrian


PS: Don't forget to share and like this Site on Facebook!


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








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.

Mobile World Congress 2012 -WIP Jam and Party






BARCELONA- With Christmas less than three weeks away, it can be easy to forget that the Mobile World Congress, the world´s largest trade event for the mobile sector, is also round the corner.

For the joy of mobile app developers everywhere, WIP is organizing the WIP Jam event for developers within the grounds of the Fira complex on the 1st March 2012 (in Auditorium A, to be precise). This will be preceded by the WIP Party the previous evening at the Rock Museum in the Richard Rogers-designed Las Arenas (upstairs in the Rock Museum venue).

Both events are NOT TO BE MISSED. The WIP Jam event will have the successful formula of short presentations and many breakout sessions to talk about topical issues in mobile, facilitated by familiar faces in mobile development. The WIP Party will have free food and drinks and a Jameoke (for those up for some singing).

You can sign up to the WIP Party by clicking here  

Saturday, December 3, 2011

NFS Hot Pursuit for Galaxy Ace and other HVGA Devices




Feel the rush of the escape and the thrill of the takedown!
Outrun the law as a Racer in supercars like the Pagani Zonda Cinque – or stop racers cold as a Cop in high-speed police interceptors like the Lamborghini Reventon. Experience pulse-pounding action as you make the escape – or make the bust – with Need for Speed Hot Pursuit™ on Android.
**GAME ALERT** Play the Tetris® game – for FREE! Loved by hundreds of millions of players worldwide, this all-time blockbuster is an absolute essential: goo.gl/ZhfmV
CHASE ACHIEVEMENTS
Drive up to 20 precision-performance cars in adrenaline-fueled showdowns across 24 day-and-night tracks. Take it to the limit in 48 total Cop and Racer Career Events, collect bounty, and rise to the top of the ranks.
DUEL IT OUT ON THE ROAD
As a Cop, lay down the law with roadblocks and spike strips – or fry the Racer’s electrical system with an EMP lock. As a Racer, make the getaway with overdrive, jamming, and oil slicks. Duel it out on the road!
From the #1 interactive racing franchise, bring the heat with Need for Speed Hot Pursuit!
Discover more games from EA like Tetris® free and SimCity™ Deluxe, and THE GAME OF LIFE. See all our games for Android now! 
GAME PLAY ON GALAXY ACE
Download :

APK          : Download Now
SD DATA  : Download Now

Thursday, December 1, 2011

Integrating NFC in mobile apps – implementation costs




In this guest post by Magnus Jern, he sums up the current opportunities and challenges of implementing NFC mobile solutions.
NFC has been around since 2003 but it´s not until now that technology and adoption are ready for commercial deployment. It is embedded in the latest Android handsets, including the Nexus S. RIM are including it in all their new devices and Apple want to equip the iPhone 5 with an NFC chip, despite rumours they would not. Nokia is launching a series of devices including NFC, starting with the C7 and most other handset manufacturers will include NFC in their devices within the next 2 years.
According to Wikipedia: “Near field communication, or NFC, is a set of short-range wireless technologies, typically requiring a distance of 4 cm or less. (…) This enables NFC targets to take very simple form factors such as tags, stickers, key fobs, or cards that do not require batteries. NFC peer-to-peer communication is also possible, where both devices are powered.”
The technology is enabling new and exciting mobile interactions such as loyalty cards,  identification, travel tickets and micro-payments.
What is the cost of implementing NFC in your mobile applications?
The implementation of writing and reading data on the application side is fairly straight forward, just a few API calls that most developers will already be familiar with.
So the cost of implementing NFC in an application is very small compared to the cost of setting up the backend infrastructure that may be required to support it.  A typical NFC application, which reads an NFC chip once to authenticate that the user has been in a certain store or redeemed a voucher, could cost as little as 10-20.000 euros to implement, but NFC itself can be added to existing applications very cheaply.
So what’s next?
During the coming years we will see thousands of different applications including NFC. Some of those will be ground-breaking and others will quickly be forgotten. Banks, retailers, transportation businesses, fast food restaurants and events companies will all be experimenting with the possibilities. Watch this space.

Monday, November 28, 2011

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!

Tuesday, November 22, 2011

Making Android Games that Play Nice

[This post is by Ian Ni-Lewis, a Developer Advocate who devotes most of his time to making Android games more awesome. — 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.

I: The Audio Lifecycle (or, why is there music coming from my pants?)

One of the most awesome things about Android is that it can do so much stuff in the background. But when apps aren’t careful about their background behaviors, it can get annoying. Take my own personal pet peeve: game audio that doesn’t know when to quit.

The problem

I’m on the bus to work, passing the time with a great Android game. I’m completely entranced by whatever combination of birds, ropes, and ninjas is popular this week. Suddenly I panic: I’ve almost missed my stop! I leap up, quickly locking my phone as I shove it into a pocket.

I arrive breathless at my first meeting of the day. The boss, perhaps sensing my vulnerability, asks me a tough question. Not tough enough to stump me, though — I’ve got the answer to that right here on my Android phone! I whip out my phone and press the unlock button... and the room dissolves in laughter as a certain well-known game ditty blares out from the device.

The initial embarrassment is bad enough, but what’s this? I can’t even mute the thing! The phone is showing the lock screen and the volume buttons are inactive. My stress level is climbing and it takes me three tries to successfully type in my unlock code. Finally I get the thing unlocked, jam my finger on the home button and breathe a sigh of relief as the music stops. But the damage is done — my boss is glowering and for the rest of the week my co-workers make video game noises whenever they pass my desk.

What went wrong?

It’s a common mistake: the developer of the game assumed that if the game received an onResume() message, it was safe to resume audio. The problem is that onResume() doesn’t necessarily mean your app is visible — only that it’s active. In the case of a locked phone, onResume() is sent as soon as the screen turns on, even though the phone’s display is on the lock screen and the volume buttons aren’t enabled.

Fixing this is trickier than it sounds. Some games wait for onWindowFocusChanged() instead of onResume(), which works pretty well on Gingerbread. But on Honeycomb and higher, onWindowFocusChanged() is sent when certain foreground windows — like, ironically, the volume control display window — take focus. The result is that when the user changes the volume, all of the sound is muted. Not the developer’s original intent!

Waiting for onResume() and onFocusChanged() seems like a possible fix, and it works pretty well in a large number of cases. But even this approach has its Achilles’ heel. If the device falls asleep on its own, or if the user locks the phone and then immediately unlocks it, your app may not receive any focus changed messages at all.

What to do about it

Here’s the easy two-step way to avoid user embarrassment:

  1. Pause the game (and all sound effects) whenever you receive an onPause() message. When gameplay is interrupted — whether because the phone is locked, or the user received a call, or for some other reason — the game should be paused.


  2. After the game is paused, require user input to continue. The biggest mistake most game developers make is to automatically restart gameplay and audio as soon as the user returns to the game. This isn’t just a question of solving the “music over lock screen” issue. Users like to come back to a paused game. It’s no fun to switch back to a game, only to realize you’re about to die because gameplay has resumed before you expected it.


Some game designers don’t like the idea of pausing the background music when the game is paused. If you absolutely must resume music as soon as your game regains focus, then you should do the following:

  1. Pause playback when you receive onPause().


  2. When you receive onResume():

    1. If you have previously received an onFocusChanged(false) message, wait for an onFocusChanged(true) message to arrive before resuming playback.


    2. If you have not previously received an onFocusChanged(false) message, then resume audio immediately.



  3. Test thoroughly!


Fixing audio embarrassments is almost always a quick and easy process. Take the time to do it right, and your users will thank you.

Thursday, November 17, 2011

Kindle Fire UI v2.0 [UPDATE 04/December/2011]

This is a small update of my Kindle Fire UI.


Changelog:

- 3 New Backgrounds (Main, Bookshelf, Blank)
- "Recent" Apps are smaller
- Changed Facebook Messenger icon to Camera

Setup is the same as on Version 1.0

Files: click!

UPDATE:

The XDA User "nozerogravity" has created a Kindle Fire Lockscreen Theme for Widgetlocker!
Here's how you get it: Kindle Fire WL



Adrian



Friday, November 11, 2011

Updated NDK for Android 4.0

Today we are releasing an updated version of the Android NDK, now in revision 7. The updated NDK lets developers who are using native code get started with the new native APIs available in Android 4.0.

Android NDK r7 includes a number of build system improvements and bug fixes, but most importantly it gives you access to two new sets of APIs:

Low-level streaming multimedia: A new API based on Khronos OpenMAX AL 1.0.1 provides a direct, efficient path for low-level streaming multimedia. The new path is ideal for applications that need to maintain complete control over media data before passing it to the platform for presentation. For example, media applications can now retrieve data from any source, apply proprietary encryption/decryption, and then send the data to the platform for display.

Audio decoding into PCM: Extensions to the existing native audio API based on Khronos OpenSL ES let native apps decode compressed audio assets to PCM format.

For detailed information about how to use these new APIs, please see the documentation included with the Android NDK r7 package. To read about the build system improvements and bug fixes included in this release, check out the release notes.

Thursday, November 10, 2011

New Layout Widgets: Space and GridLayout

[This post is by Philip Milne, who is part of the Android framework team. — Tim Bray]

Ice Cream Sandwich (ICS) sports two new widgets that have been designed to support the richer user interfaces made possible by larger displays: Space and GridLayout.

The most commonly used class for layout in Android is LinearLayout, which allows its children to be aligned in the usual ways: along either the horizontal or vertical axes. It’s often possible to take a complicated layout and break it down into a set of nested linear layouts and, provided this nesting doesn’t get too deep, this is still a good choice for many simple layouts.

A number of posts and articles (e.g. Android Layout Tricks #1, Flattening The Stack) have highlighted drawbacks of nested layouts; which fall into three basic categories:

  • Inability to control alignment along both axes simultaneously


  • Performance problems in hierarchies that are too deep


  • Unsuitability for design tools that support free-form editing


A simple example of the first problem is the following form:

As the font and the text of the “Email address” label change, we want the label to remain aligned with the baseline of the component to its right, and aligned with the right edge of the label below it. It’s not possible to do this with nested LinearLayouts because the label needs to be aligned with other components both horizontally and vertically.

These problems aren’t new to Android, or UI toolkits in general, but we’ve used them to drive our work in enriching platform support for flatter hierarchies.

GridLayout

To provide better support for layouts like these we have added a new layout to the Android framework: GridLayout, which can be used to solve the above problems by dividing the container’s real estate into rows and columns:

Now the “Email address” label can belong both to a row that is baseline-aligned, and a column that is right-aligned.

GridLayout uses a grid of infinitely-thin lines to separate its drawing area into: rows, columns, and cells. It supports both row and column spanning, which together allow a widget to occupy a rectangular range of cells that are next to each other. We’ll use the words row, column, and cell in the text below as shorthand for row group, column group and cell group respectively, where groups have one or more contiguous elements.

Similarities with LinearLayout

Wherever possible, GridLayout uses the same conventions as LinearLayout for all its XML API — so it should be easy to start using GridLayout if you’ve already used LinearLayout. In fact, the APIs are so similar that changing a tag name from LinearLayout to GridLayout in an XML file that uses LinearLayout will often produce a similar UI without requiring any other changes. When it doesn’t, you’ll still generally end up with a good starting point for a two-dimensional layout.

Getting Started

Two examples in the samples area of the Android 4.0 SDK show typical use of the programmatic and XML APIs respectively:

[Both examples produce the same UI.]

Here’s a slightly simpler version of the above XML layout.

<?xml version="1.0" encoding="utf-8"?>
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"
android:layout_height="match_parent"

android:useDefaultMargins="true"
android:alignmentMode="alignBounds"
android:columnOrderPreserved="false"

android:columnCount="4"
>

<TextView
android:text="Email setup"
android:textSize="32dip"

android:layout_columnSpan="4"
android:layout_gravity="center_horizontal"
/>

<TextView
android:text="You can configure email in just a few steps:"
android:textSize="16dip"

android:layout_columnSpan="4"
android:layout_gravity="left"
/>

<TextView
android:text="Email address:"

android:layout_gravity="right"
/>

<EditText
android:ems="10"
/>

<TextView
android:text="Password:"

android:layout_column="0"
android:layout_gravity="right"
/>

<EditText
android:ems="8"
/>

<Space
android:layout_row="4"
android:layout_column="0"
android:layout_columnSpan="3"
android:layout_gravity="fill"
/>

<Button
android:text="Next"

android:layout_row="5"
android:layout_column="3"
/>
</GridLayout>

The first difference you’ll notice in these examples is the absence of the WRAP_CONTENT and MATCH_PARENT constants that normally adorn Android layout resources. You don’t normally need to use these with GridLayout, for reasons that are described in the API doc for GridLayout.LayoutParams.

Row and Column Indices

The second thing you may notice in the XML resources is that widgets don’t always explicitly define which cells they are to be placed in. Each widget’s layout parameters have row and column indices that together define where the widget should be placed but when either or both of these values are not specified, GridLayout supplies default values rather than throwing an exception.

Automatic Index Allocation

As children are added to a GridLayout, it maintains a cursor position and a “high-water mark” that it uses to place widgets in cells that don’t yet have anything in them.

When GridLayout’s orientation property is horizontal and a columnCount has been set (to 8 in this example) the high-water mark (shown above in red) is maintained as a separate height value for each column. When indices need to be created, GridLayout first determines the size of the cell group (by looking at the rowSpan and columnSpan parameters of the new widget) and then, starting at the cursor, goes through the available locations from: left to right, top to bottom, so as to find the row and column indices of the first location that’s free.

When GridLayout’s orientation is vertical, all of the same principles apply, except that the roles of the horizontal and vertical axes are exchanged.

If you want multiple views to be placed in the same cell, you have to define the indices explicitly, as the default allocation procedure above is designed to place widgets in separate cells.

Sizes, Margins and Alignment/Gravity

In GridLayout, specifying sizes and margins is done just as with a LinearLayout. Alignment/gravity also works just like gravity in LinearLayout and uses the same constants: left, top, right, bottom, center_horizontal, center_vertical, center, fill_horizontal, fill_vertical and fill.

Flexibility

Unlike most grids in other toolkits, GridLayout does not associate data with rows or columns. Instead, everything to do with alignment and flexibility is associated with the components themselves. GridLayout departs from the norm here to provide a more general system that allows subtle relationships between ancestors in deeply nested layouts to be accommodated in a single layout configuration.

The flexibility of columns is inferred from the gravity of the components inside the column. If every component defines a gravity, the column is taken as flexible, otherwise the column is considered inflexible. Full details are in GridLayout’s API docs.

Emulating Features from other Layouts

GridLayout does not incorporate all of the features of every layout in the Android platform but it has a rich enough feature set that idiomatic use of other layouts can normally be emulated from inside a single GridLayout.

Although LinearLayout can be considered a special case of a GridLayout, for the degenerate case when a set of views are aligned in a single row or column, LinearLayout is the better choice when this is all that is required as it clarifies the purpose of the container and may have some (relatively small) performance advantages.

TableLayout configurations are normally straightforward to accommodate, as GridLayout supports both row and column spanning. TableRows can be removed, as they are not required by GridLayout. For the same UI, a GridLayout will generally be faster and take less memory than than a TableLayout.

Simple RelativeLayout configurations can be written as grids simply by grouping the views that are related to each other into rows and columns. Unlike conventional grids, GridLayout uses a constraints solver to do the heavy lifting of the layout operation. By using GridLayout’s rowOrderPreserved and columnOrderPreserved properties it’s possible to free GridLayout from the confines of traditional grid systems and support the majority of RelativeLayout configurations — even ones that require grid lines to pass over each other as children change size.

Simple FrameLayout configurations can be accommodated within the cells of a GridLayout because a single cell can contain multiple views. To switch between two views, place them both in the same cell and use the visibility constant GONE to switch from one to the other from code. As with the LinearLayout case above, if all you need is the functionality described above, FrameLayout is the better choice and may have some small performance advantages.

One key feature that GridLayout lacks is the ability to distribute excess space between rows or columns in specified proportions — a feature that LinearLayout provides by supporting the principle of weight. This omission and possible ways around it are discussed in GridLayout’s API docs.

The Phases of the Layout Operation

It’s useful to distinguish the allocation phase for cell indices discussed above from the layout operation itself. Normally the phase that allocates indices happens once, if at all, when a UI is initialized. The index-allocation phase only applies when indices have been left unspecified, and is responsible for ensuring that all views have a defined set of cells in which they are to be placed at layout time.

The layout operation happens after this and is recalculated each time a view changes size. GridLayout measures the size of each child during the layout operation so it can calcuate the heights and widths of the rows and columns in the grid. The layout phase completes by using gravity to place each of the components in its cell.

Although index allocation normally only happens once, GridLayout is technically a dynamic layout, meaning that if you change its orientation property or add or remove children after components have been laid out, GridLayout will repeat the above procedure to reallocate indices in a way that is right for the new configuration.

From a performance standpoint, it is worth knowing that the GridLayout implementation has been optimized for the common case, when initialization happens once and layout happens frequently. As a result, the initialization step sets up internal data structures so that the layout operation can complete quickly and without allocating memory. Put another way, changes either to GridLayout’s orientation or the number of children it has are much more expensive than an ordinary layout operation.

Conclusion

GridLayout’s feature set incorporates much of the functionality of the Android framework’s existing general-purpose layouts: LinearLayout, FrameLayout, TableLayout and RelativeLayout. As such, it provides a way to replace many deeply nested view hierarchies with a single highly optimized layout implementation.

If you are starting a UI from scratch and are not familiar with Android layouts, use a GridLayout — it supports most of the features of the other layouts and has a simpler and more general API than either TableLayout or RelativeLayout.

We anticipate that the combination of FrameLayout, LinearLayout and GridLayout together will provide a feature set that’s rich enough to allow most layout problems to be solved without writing layout code by hand. It’s worth spending some time deciding which of these layouts is right for the top of your tree; a good choice will minimize the need for intermediate containers and result in a user interface that is faster and uses less memory.

Wednesday, November 9, 2011

Kindle Fire Setup


What you need for this:
-Android Phone
-ADW Launcher EX
-MultiPicture Livewallpaper
-Desktop Visualizer
-Kindle Fire Setup files (Click)

Setup:

ADW Launcher EX:
 Gridsize 5x7, hide icon text, transition "slide", dock disabled, 3 Homescreens, infiniti scroll.

MultiPicture Livewallpaper:
3 Custom Screens, set backgrounds from the Kindle Fire Setup files (they're numbered), transition "none".

Homescreens:
Set the Phone, SMS, Email, Gamesfolder, Launcher icons on the menubar and make them transparent by using the "transparent.png" from the Kindle Fire Setup files.
Place some Desktopvisualizer widgets over the big icons in the center and make them transparent, too.
Now put some of your favorites Apps on the bottom two lines (Maybe with an icon theme, I'm using "Suave HD"  icons)
Do this for the next 2 Screens and you're done!

Enjoy!



Adrian





Tuesday, November 8, 2011

More Android Developer Labs in Asia

A couple of months ago, we kicked off a series of Android Developer Labs in Asia, North America and Europe. To wrap up the 2011 series, we now have opened registration for 2 more locations in Asia.

  • Taipei — December 2, 2011

  • Hong Kong — December 6, 2011

Remember, this ADL series isn’t another set of introduction-to-Android sessions, nor any other kind of general overview. It's specifically aimed at optimizing Android apps for tablets, in particular creating high-quality tablet apps with an emphasis on polish and user experience.

Registration is a two-step process. Anyone can register, but we can only accommodate a relatively small number of attendees from among the registrants, based on whether they already have an Android app with the potential to be a top-tier tablet app in terms of quality, fit, and finish. The goal is to bring your app to the ADL, and leave equipped to make it into one that makes Android tablet users smile.

Related Posts Plugin for WordPress, Blogger...