Thursday, February 19, 2009

Faster screen orientation change

Android is a mobile operating system meant to be run on a wide array of devices, with very different hardware configurations. Some devices, like the T-Mobile G1, can change their hardware configuration at runtime. For instance, when you open the keyboard, the screen change from the portrait orientation to the landscape orientation. To make Android applications development easier, the OS automatically handles configuration changes and restart the current activity with the new configuration. This is the default behavior that lets you declare resources like layouts and drawables based on the orientation, screen size, locale, etc. If you are not familiar with the way Android handles resources, I highly suggest you to read the official documentation on resources.

While this behavior is really powerful, since your application adapts automatically to the device's configuration at runtime, it is sometimes confusing for new Android developers who wonder why their activity is destroyed and recreated. Facing this "issue," some developers choose to handle configuration changes themselves which is, in my opinion, a short-term solution that will complicate their life when other devices come out or when the application becomes more complex. The automatic resource handling is a very efficient and easy way to adapt your application's user interface to various devices and devices configurations. It sometimes comes at a price though.

When your application displays a lot of data, or data that is expensive to fetch, the automatic destruction/creation of the activities can be lead to a painful user experience. Take the example of Photostream, a simple Flickr browsing application I wrote for the release of Android 1.0. After you launch the application and choose a Flickr account, the application downloads a set of 6 photos (on a T-Mobile G1) from the Flickr servers and displays them on screen. To improve the user experience, I also use slightly different layouts and drawables in portrait and landscape, and this is what the result looks like:


Media_http1bpblogspot_fogdd


Media_http2bpblogspot_fdfra

Photostream lets Android take care of the configuration change when the screen is rotated. However, can you imagine how painful it would be for the user to see all the images being downloaded again? The obvious solution to this problem is to temporarily cache the images. They could be cached on the SD card (if there's one), in the Application object, in a static field, etc. None of these techniques is adapted to the current situation: why should we bother caching the images when the screen is not rotated? Fortunately for us, Android offers a great API exactly for that purpose.

The Activity class has a special method called onRetainNonConfigurationInstance(). This method can be used to pass an arbitrary object your future self and Android is smart enough to call this method only when needed. In the case of Photostream, I used this method to pass the downloaded images to the future activity on orientation change. The implementation can be summarized like so:


@Override
public Object onRetainNonConfigurationInstance() {
final LoadedPhoto[] list = new LoadedPhoto[numberOfPhotos];
keepPhotos(list);
return list;
}


In the new activity, in onCreate(), all you have to do to get your object back is to call getLastNonConfigurationInstance(). In Photostream, this method is invoked and if the returned value is not null, the grid is loaded with the list of photos from the previous activity:


private void loadPhotos() {
final Object data = getLastNonConfigurationInstance();

// The activity is starting for the first time, load the photos from Flickr
if (data == null) {
mTask = new GetPhotoListTask().execute(mCurrentPage);
} else {
// The activity was destroyed/created automatically, populate the grid
// of photos with the images loaded by the previous activity
final LoadedPhoto[] photos = (LoadedPhoto[]) data;
for (LoadedPhoto photo : photos) {
addPhoto(photo);
}
}
}


Be very careful with the object you pass through onRetainNonConfigurationChange() though. If the object you pass is for some reason tied to the Activity/Context, you will leak all the views and resources of the activity. This means you should never pass a View, a Drawable, an Adapter, etc. Photostream for instance extracts the bitmaps from the drawables and pass the bitmaps only, not the drawables. Finally, remember that onRetainNonConfigurationChange() should be used only to retain data that is expensive to load. Otherwise, keep it simple and let Android do everything.

Friday, February 13, 2009

Android Market update: support for priced applications


Media_http2bpblogspot_yazlt

I'm pleased to announce that Android Market is now accepting priced applications from US and UK developers. Developers from these countries can go to the publisher website at http://market.android.com/publish to upload their application(s) along with end user pricing for the apps. Initially, priced applications will be available to end users in the US starting mid next week. We will add end user support for additional countries in the coming months.

We will also enable developers in Germany, Austria, Netherlands, France, and Spain to offer priced applications later this quarter. By the end of Q1 2009, we will announce support for developers in additional countries. Developers can find more information about priced applications in Android Market at http://market.android.com/support/

Google Checkout will serve as the payment and billing mechanism for Android Market. Developers who do not already have a Google Checkout merchant account can easily sign up for one via the publisher website.

Also, Android Market for free applications will become available to users in Australia starting February 15th Pacific Time and in Singapore in the coming weeks. Developers can now make their applications available in these countries via the publisher website at http://market.android.com/publish.

We look forward to seeing more great applications on Android Market.

Thursday, February 12, 2009

Track memory allocations

Despite the impressive hardware of the first Android phones (T-Mobile G1 and ADP1) writing efficient mobile applications is not always straightforward. Android applications rely on automatic memory management handled by Dalvik's garbage collector which can sometimes cause performance issues if you are not careful with memory allocations.

In a performance sensitive code path, like the layout or drawing method of a view or the logic code of a game, any allocation comes at a price. After too many allocations, the garbage collector will kick in and stop your application to let it free some memory. Most of the time, garbage collections happen fast enough for you not to notice. However, if a collection happens while you are scrolling through a list of items or while you are trying to defeat a foe in a game, you may suddenly see a drop in performance/responsiveness of the application. It's not unusual for a garbage collection to take 100 to 200 ms. For comparison, a smooth animation needs to draw each frame in 16 to 33 ms. If the animation is suddenly interrupted for 10 frames, you can be certain that your users will notice.

Most of the time, garbage collection occurs because of tons of small, short-lived objects and some garbage collectors, like generational garbage collectors, can optimize the collection of these objects so that the application does not get interrupted too often. The Android garbage collector is unfortunately not able to perform such optimizations and the creation of short-lived objects in performance critical code paths is thus very costly for your application.

To help you avoid frequent garbage collections, the Android SDK ships with a very useful tool called allocation tracker. This tool is part of DDMS, which you must have already used for debugging purposes. To start using the allocation tracker, you must first launch the standalone version of DDMS, which can be found in the tools/ directory of the SDK. The version of DDMS included in the Eclipse plugin does not offer you ability to use the allocation tracker yet.

Once DDMS is running, simply select your application process and then click the Allocation Tracker tab. In the new view, click Start Tracking and then use your application to make it execute the code paths you want to analyze. When you are ready, click Get Allocations. A list of allocated objects will be shown in the first table. By clicking on a line you can see, in the second table, the stack trace that led to the allocation. Not only you will know what type of object was allocated, but also in which thread, in which class, in which file and at which line. The following screenshot shows the allocations performed by Shelves while scrolling a ListView.


Media_http2bpblogspot_jhefk

Even though it is not necessary, or sometimes not possible, to remove all allocations for your performance critical code paths. the allocation tracker will help you identify important issues in your code. For instance, a common mistake I have seen in many applications is to create a new Paint object on every draw. Moving the paint into an instance field is a simple fix that helps performance a lot. I highly encourage you to peruse the Android source code to see how we reduce allocations in performance critical code paths. You will also thus discover the APIs Android provide to help you reuse objects.

Note: this article was originally posted on my personal blog.

Wednesday, February 11, 2009

Apps that work together

Android applications can easily be linked together using intents. One example of this involves Shazam, MySpace, and the Amazon MP3 Store. Once Shazam has identified a song, you can also search for the artist's official MySpace profile page or buy the song via via the Amazon MP3 app. Here, the three developers behind these apps talk about how they accomplished this:

To hear more about how the MySpace app for Android was built and lessons learned, watch Matt Kanninen:

http://www.youtube.com/p/3A4E4D83B9614552

Tomasz Zawada of Shazam also talks about his opinions on the Android platform and has some tips for developers building Android apps:

http://www.youtube.com/p/A131466774A03834

These and the other Android app developer videos can be found here.

Monday, February 9, 2009

Android 1.1 SDK, release 1 Now Available

Hello, developers! As you may have heard by now, users around the world have started to receive updates to their Android devices that provide new features and functionality. You may also have noticed that the new update reports as "Android 1.1". Applications written with the 1.0_r1 and 1.0_r2 SDKs will continue to work just fine on Android 1.1. But if you want to take advantage of the new APIs in 1.1, you'll need an updated SDK.

That's why I'm pleased to let you know that the Android 1.1 SDK, release 1 is now available. As you'll quickly see from the release notes, the actual API changes are quite minor, but useful. This new SDK has all the new APIs, as well as a new emulator image to let you test your applications. If you have a retail device running Android, contact your operator for the update schedule. An updated v1.1 system image for the Android Developer Phone 1 will be coming soon.

In addition to the new APIs, the emulator also contains improved ability to test localizations to the German language. Localizations for other languages will be added in future SDK releases.

You can download the updated SDK using the links above. Happy coding!

Sunday, February 8, 2009

Kampanye Damai Pemilu Indonesia 2009


Kampanye Damai Pemilu Indonesia 2009 sudah memasukin minggu kedua, fluktuasi rangking yang terjadi cukup menegangkan karena silih bergantinya posisi puncan di kontes seo ini. Para master yang tadinya tiarap sudah mulai memuntahkan amunisinya perlahan-lahan. bahkan beberapa veteran Busby SEO Test sepertinya ikut meramaikan kontes seo lokal ini.

Posisi 10 besar masih dikuasai blogger-blogger dari Indonesia ... he he he .. emang penyelenggaraannya di Indonesia, akan tetapi ada beberapa peserta kontes yang sekarang sedang berdomisili di Hongkong. Kampanye Damai Pemilu Indonesia 2009 ini tidak hanya digembar-gemborkan oleh para blogger Indonesia, ternyata blogger Hongkong yang berasal dari Indonesia juga ikut meramaikan arena Kampanye Damai.

Blog ini tidak berniat ikut partisipasi dalam kontes Kampanye Damai Pemilu akan tetapi ikut nyundul posisi blog utama agar mempunyai balok-balok yang kuat. Mudah-mudahan blog yang masih ber PR o dan baru dibuat beberapa minggu yang lalu ini dapat mengoptimasi blog utama di kontes seo dengan kata Kunci Kampanye Damai Pemilu di Pemilu Indonesia 2009 ini.



Posisi puncak sampai dengan sore ini sepertinya diduduki oleh salah satu master seo, karena postngan di blognya baru ada satu tapi bisa melejit ke posisi no 1, ini menandakan sokongan dan dukungan dari blog-blog pendukungnya lumayan kuat dan membuat posisinya mantap di no.1, kita sama-sama menunggu apakah akan ada perubahan rangking lagi malam ini.

Selamat berlomba para peserta Kampanye Pemilu Indonesia 2009.



Thursday, February 5, 2009

SEO company optimized a client's site

As you know from the section of the course that discussed the history of search engines and optimization, there was a time when the optimization process was simple and involved little more that tweaking meta tags and repeating keywords within the content of a page. As such, there were a limited number of SEO companies.
Today the industry and contestan seo is highly competitive. Worldwide, there are now thousands of search engine optimization companies. There is also an ever increasing number of websites and many of them are already well optimized, making the competition much worse. In the past, when an SEO company optimized a client's site, most other sites in direct competition were poorly optimized or not optimized at all; the game was easier. But now, almost every competitor of yours is using the services of some SEO to optimize their site for keyword Kampanye Damai Pemilu Indonesia 2009 in contest seo local indonesian.


As you can guess, this makes the game really tough. Also, this leads up to half of the SEO / SEM companies into considering unethical and illegal strategies in order to get their customers to the top of search engine result pages.
Nevertheless, this rarely gives these companies any competitive advantage as most solid and respectable companies seeking SEO services now recognize that guarantees of top-10 rankings sound, at the very least, suspicious. Let's imagine a company called pencuridompetibu-ibusegarcompany LTD has a website that offers some products. Except product advertising, this site does not contain any valuable information for visitors so the search engines do not rank it high. So, pencuridompetibu-ibusegarcompany hires SEO expert to help them with rankings because claims he can get any site into the Top-10 for keyword Kampanye Damai Pemilu Indonesia 2009.
What this SEO expert does is stuff the company pages with irrelevant keywords, creating a link system with thousands of hidden links and then implements some advanced spamming techniques like dynamic page generation and cloaking.
As a result, the rankings of the page are initially boosted. pencuridompetibu-ibusegarcompany is happy and pays the fee to Mr.blablamadeinmatre. Still, visitors coming to the site see even more of a mess than before the "optimization" and they are still unable to find any valuable content. Since they find the pencuridompetibu-ibusegarcompany's site for the irrelevant keywords, that is, not for those they are primarily seeking, the conversion of visitors into customers is very low. As a result, customers are unsatisfied and pencuridompetibu-ibusegarcompany receives huge bills for traffic which hasn't been converted and hasn't brought any real profit.
The search engine which allowed for the spammer's site on top of its listings is also unsatisfied since it's losing its popularity among Web surfers because they are serving irrelevant pages. So it invests money into developing a more advanced spider that finally cracks tricks and the positions of pencuridompetibu-ibusegarcompany fall down. Eventually, pencuridompetibu-ibusegarcompany is excluded from the search engine index entirely because an unsatisfied visitor or a competitor reported to the search engine that pencuridompetibu-ibusegarcompany is using spam methods. Of course, pencuridompetibu-ibusegarcompany is unsatisfied with this situation to get their money refunded. Mr.blablamadeinmatreis unwilling to cooperate or perhaps even managed to escape before all this mess started. The best case scenario is that pencuridompetibu-ibusegarcompany gets its money back but is never able to restore its rankings and has to invest in a new website.
Nobody is satisfied in this story, however such things do happen now and again, even in today's more sophisticated SEO environment. Unfortunately, there's no solution for such cases except abandoning spam techniques entirely and following a Code of Ethics for all Search Engine Optimizers which maintains their good reputation and withstand crowds of unethical SEO companies that wave the banner of illegal yet "effective" promotion strategies. Adhering to a Code of Ethics (or Code of Conduct), if presented properly, may serve as an effective competitive advantage.