Android MobileApplication Developmentfrom   A to Z                          ®          an                  Developer eBook
Contents…            Android Mobile Application             Development from A to Z                 This content was adapt...
Android Mobile Application                                                 Development from A to Z      The Android Mobile...
Android Mobile Application                                                Development from A to Zacquisition of device har...
Android Mobile Application                                                 Development from A to Zapplications, enabling h...
Android Mobile Application                                               Development from A to Z Android SDK and operating...
Android Mobile Application                                               Development from A to Z     Top 10 Features for D...
Android Mobile Application                                                  Development from A to Zsecure device managemen...
Android Mobile Application                                                 Development from A to ZAnd let’s not forget tha...
Android Mobile Application                                                  Development from A to Z Building Your First PH...
Android Mobile Application                                               Development from A to Zfull documentation for thi...
Android Mobile Application                                                 Development from A to Zthe Yahoo stock service....
Android Mobile Application                                                 Development from A to Z	         $droid->dialog...
Android Mobile Application                                               Development from A to Z    Building Killer Androi...
Android Mobile Application                                                  Development from A to Zthere was really only o...
Android Mobile Application                                               Development from A to Z                          ...
Android Mobile Application                                                Development from A to Z8.	 When it’s created, la...
Upcoming SlideShare
Loading in …5

Android mobile-app-development-from-a-to-z-ebook-no-ads-2010-developer


Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Android mobile-app-development-from-a-to-z-ebook-no-ads-2010-developer

  1. 1. Android MobileApplication Developmentfrom A to Z ® an Developer eBook
  2. 2. Contents… Android Mobile Application Development from A to Z This content was adapted from’s website. Contributors: Shane Conder, Lauren Darcey and Keith Vance.2 2 The Android Mobile Development Platform: A Reference Guide 6 Top 10 Features for Developers in Android 2.26 9 9 Building Your First PHP for Android Application 13 Building Killer Android Tablet Apps: Design and Development Tips13
  3. 3. Android Mobile Application Development from A to Z The Android Mobile Development Platform: A Reference Guide By Shane Conder and Lauren Darcey A ndroid, an open source mobile platform Android applications can be developed on a with no upfront fees, has emerged as a new variety of operating systems, including: mobile development option that offers many • Windows XP (32-bit), Vista (32-bit or 64-bit), and benefits over competing platforms. But is it Windows 7 (32-bit and 64-bit)right for your project? In this reference guide, you’ll learnall the nitty-gritty details you need to know to evaluate • Mac OS X 10.5.8 or later (x86 only)Android, including the tools andtechnologies for developing • Linux (tested on Linux Ubuntuon the platform as well as the 8.04 LTS, Hardy Heron)required costs. Armed with thisinformation, you can make an The Android SDK andinformed decision as to whether development tools are freelyor not Android is the right fit available on the Androidfor your particular organization developer site, where developersor development project. can download the SDK after agreeing to the terms of theAndroid Programming Android SDK License Agreement.Languages Developers must also have JDK 5.0 or JDK 6 (freely available).Native Android applications arewritten in Java. Applications In terms of integratedrequiring existing C/ development environmentsC++ libraries can take (IDEs), developers have a numberadvantage of the Android of choices. Eclipse is the mostNative Development Kit (NDK). popular IDE for Android development because it offers a handy Android Development Tools (ADT) plugin. At theIn addition to native Android applications written time of writing, the ADT plugin supported both Eclipsein Java, Adobe Flash and Adobe AIR support 3.4 and 3.5. Developers can use other IDEs if they desire;were added in Android 2.2, enabling a whole new the command-line tools that come with the Android SDKgroup of developers to target Android devices. facilitate Android development and provide many of the features available within the Eclipse ADT plugin (e.g.Development Tools and Setup Costs creating projects, packaging resources and generating Android package files for deployment to devices, etc.).Unlike many mobile development platforms, Androidis open and freely available. There are no developer Android Devices: Features, Functions andfees or screening processes, nor must developers Availabilitypurchase expensive compilers or limit themselves toone specific operating system for development. The only real cost for Android developers is the 2 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  4. 4. Android Mobile Application Development from A to Zacquisition of device hardware. Although the Android Android Development Framework and APIsteam has insisted that testing within the Androidemulator is generally sufficient for most development, The Android application framework includes familiarwe feel that emulators are no real substitute for programming constructs, such as threads andtesting on (at least some) target devices. processes and specially designed data structures to encapsulate objects used by the Android operatingFortunately (and unfortunately), many Android devices system. With Android, developers use familiar classare available on the global market today. Consumers libraries exposed through Android’s Java packageshave an unprecedented number of choices in terms to perform common tasks such as graphics, databaseof distinctive devices, carriers, and payment plans. access, network access, secure communications andAccording to the official Google Blog, as of mid-2010, utilities. In addition to these familiar Java class libraries,more than 60 Android handsets shipped from 21 different such as, developers can also rely on specialtymanufacturers. These Android devices are available on 59 libraries using well-defined open standards likecarriers in 48 countries. In June 2010, Google announced OpenGL Embedded Systems (OpenGL ES), SQLite, andthat more than 160,000 Android devices are being WebKit. The Android packages include support for:activated each day (a rate of nearly 60 million devicesannually). • User interface controls (Buttons, Dropdowns, Text Input, Grids, Tabs, Gallery)Most Android devices are considered smartphones, with • Flexible user interface design and layoutall the goodies one would expect (e.g. fast processors, (programmatically or via XML)touch screens, high-megapixel cameras, LBS services, • Secure networking and Web-browsing featuresaccelerometers and so on). That said, other devices also (SSL, WebKit, XML parsing)run on the Android platform, including Internet tablets, • Structured storage and relational databases (SQLite)e-book readers, TV boxes and others. It is certainly • Powerful 2D and 3D graphics (including OpenGL ES 2.0feasible to create a single application that can run • Enhanced support for audio, still images, and videosmoothly across all these devices. However, developers media in many formats, “ducking,” etc.will still need to identify and understand their target users • Access to underlying hardware sensor data, theand devices. Luckily, the Android platform and tools are camera, accelerometer, etc.designed to ensure maximum compatibility and to make • Access to underlying services like location-basedcompatibility a (relatively) straightforward matter for services (LBS), Wi-Fi, Bluetooth, etc.developers. • A robust unit testing framework for automated testing of Android appsIf you’re unsure which Android devices to acquire fordevelopment purposes, consider one of the Android Dev One of the Android platform’s most compelling featuresphones, ADP1 or ADP2, which are available for purchase is well-designed application integration. Developersif you sign up as a developer to publish on Google’s can write applications that integrate seamlessly withAndroid Market. The Android Dev phones are SIM- other Android applications, including core platformunlocked and therefore usable on any GSM network; they applications such as the Browser, Maps, Contacts,feature a bootloader that allows you to flash the device Messaging and Email.with different system images (helpful for mimickingvarious device platforms on a single device). Another On the Android platform, all apps are created equal.SIM-unlocked handset is the Google Nexus One. There is no distinction between native and third-party 3 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  5. 5. Android Mobile Application Development from A to Zapplications, enabling healthy competition among platform has been gaining ground steadily at the expenseapplication developers. All Android applications use the of its competitors, yet the market could potentiallysame libraries and have access to the same permissions accommodate substantially more growth by the platform.options and functionality. Android applications havedirect access to the underlying hardware, allowing Android applications have none of the costly and time-developers to write much more powerful applications. intensive testing and certification programs required by other platforms. Android developers are free to chooseThe Android SDK also comes with extensive developer any kind of revenue model they want. They can developdocumentation. Developers can also find the complete freeware, shareware or trial-ware, ad-driven applications,documentation online with videos, the official Android and paid applications. With Android, developers candeveloper blog and an active Android development write and publish any kind of application. Developers cancommunity. tailor applications to small demographics, instead of just the large-scale money-making ones often insisted uponPublication Opportunities and Target Audience by mobile operators. Vertical market applications can be deployed to specific, targeted users.In terms of market share, the Android platform has beengaining ground steadily against competitive platforms Because Android developers have a variety of application-such as the Apple iPhone, RIM BlackBerry and Windows distribution mechanisms to choose from, they can pickMobile (all of which have been around considerably the methods that work for them instead of being forcedlonger). The latest numbers from The Nielsen Company to play by others’ rules. Android developers can distribute(as of Summer 2010) show BlackBerry in the lead with 35% their applications to users in a variety of ways. The mostof the smartphone market, and declining. Trailing close popular distribution mechanism is Google’s Androidbehind and gaining is Apple’s iPhone at 28% and Microsoft Market. The Android Market is a generic applicationWindows Mobile is declining with a 19% showing. Android store with a revenue-sharing model. As of July 2010,is trailing with 9%, but its growth numbers are accelerating more than 90,000 applications were available in therapidly and according to some sources Android devices Android Market. Many other Android applications haveare selling faster than most, if not all, competing platforms. been sold through other publication channels. MoreIf you look back over the past 18 months since Android than 180,000 Android developers have downloaded thefirst became available to consumers, you can see that the Android SDK and developed Android applications. Pros Cons Apps written in Java, which is an easy, commonly If you don’t like Java, you’re out of luck. understood programming language Very low barrier to entry. No vetting of developers Developer expertise and application quality will vary to determine whether they are worthy of developing greatly. Neither apps nor developers are “curated” apps. No fees to join development community. as they sometimes are on other platforms, but technically, malicious developers exist on all platforms. Freely available development tools are popular, Like all mobile platforms, developers are powerful and generally well designed. In fact, the reliant on the platform and tool developers Android development tools are impressive compared to address tool defects and limitations. to others provided for other mobile platforms. Continued to next page... 4 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  6. 6. Android Mobile Application Development from A to Z Android SDK and operating system is powerful, With this power comes greater developer responsibility full of features, and easy to use. There is no to design stable, responsive applications. distinction between developer apps and native apps. Developers have unprecedented access to underlying hardware on device in a safe and secure manner. Many publication channels available, including When developers choose to publish through third- publishing through consolidated app markets as party app markets, they often must give up a portion well as self publication. Suitable for mass market, of their profits. Because there are many publication enterprise development and everything else. channels, software piracy becomes a bigger concern. Vast variety of devices available throughout Device variety (aka fragmentation) makes compatibility the world, on many carriers, with many plans, something that developers must address (various including many with unlimited data. screen sizes, optional hardware features, etc.). Rapidly growing market share. There’s still room Still smaller market share than more mature mobile for lots of growth. Applications can still distinguish platforms such as BlackBerry and iPhone. themselves, and killer apps are developed all the time. Free, open platform allows any hardware manufacturer The freedom to grab the open source Android to build devices based on the open platform. platform and place it on any device -- without anyone’s permission -- can lead to incompatible devices, confusion among users, and proliferation of platform devices and distribution mechanisms for developers to support.SummaryAndroid developers enjoy many benefits over competing mobile platforms. Android is relatively new to the mobile scene,offering a distinctly different approach: it’s open and free with robust access to the underlying device hardware. Designedin Java, Android applications can be created on a variety of operating systems with free and readily available tools.Getting started with writing mobile applications has never been so easy or affordable. And after you’ve created thoseapps, you can rest assured that there are millions of Android users all over the world who are ready to use them. 5 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  7. 7. Android Mobile Application Development from A to Z Top 10 Features for Developers in Android 2.2 By Shane Conder and Lauren Darcey A ndroid 2.2 (codename: Froyo) was a minor native Android app version? Well, there certainly are valid SDK release, but it still packed some punch, reasons, but we think a lot of companies would need to providing both developers and users with be convinced when native apps require them to target some much-anticipated features. After multiple platforms to reach their customers. Maybe Flashattending the Google I/O 2010 conference in May and apps will help weed out the weak and badly writtenwitnessing the Froyo announcement, here are the top native Android app competition, but will it strengthen10 features (in no particular the Android developmentorder) that we think developers community as a whole? We’llwill benefit from most. have to wait and see.1. Flash 10.1 and AIR 2. Push MessagingSupport Developers can now leverageThere may be some another of Google’s services,disagreement about the viability the Android Cloud to Deviceof Flash on mobile, but it’s Messaging (C2DM) framework.coming to Android phones. This framework provides aWhether or not Flash is the service for enabling limitedfuture is really not the question; push functionality to Androidfor now, Flash is pretty pervasive devices through Google services,on the Web, so cutting it out is which handle the queuing andin effect cutting out many of the secure delivery of lightweightdynamic Web apps users already messages to the device. Whileenjoy. the framework is getting ironed out, developers can sign up at the Google Labs website. Google apps, such asBeginning with the Froyo release, Android users will the Android Market for the Web, will soon be using thisbe able to download the open beta version of Flash feature to push Android applications purchased via the10.1 as well as AIR support (in the form of an Android Web to the phone over the air. This technology shouldapplication) from the Android Market. This decision help resolve some of the crazy polling traffic causedsubstantially expands the number of Web applications by Android applications at the moment (resulting inand sites accessible to Android users and widens the reduced battery life, performance reductions, etc.).development community for Android substantially. 3. New Enterprise FeaturesThis may become a double-edged sword for Androiddevelopers, however. How will this change the content Android is finally positioning itself for some seriousof the Android Market? With boatloads of Flash apps enterprise use. The Android 2.2 SDK includes new Deviceout there, why would anyone want to bother creating a Administration APIs ( for remote and 6 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  8. 8. Android Mobile Application Development from A to Zsecure device management. Here you’ll find APIs for to pause and resume all streams so an applicationmanaging device security, including password policy no longer needs to keep track of each nor do theseenforcement and the ability to remotely lock and wipe the actions on each individual stream. These improvementsdevice. For example, if an employee lost his or her device ease implementation and enhance efficiency.with its sensitive data and credentials, it could quickly belocked and wiped of that data. 6. Across-the-Board SDK EnhancementsFroyo also introduces more robust Microsoft Exchange Numerous Android APIs were added as part of the 2.2support (see No. 9). We also heard some murmurs release. Graphics and game developers will welcome theabout Android Market-like deployment solutions for the support for OpenGL ES 2.0 and ETC1 texture-compressionenterprise, but these will likely come later (but not in Froyo). support. Services like speech recognition (android.speech) received substantial upgrades and peripheral APIs such as4. Performance Improvements those that support the Camera and Camcorder have been greatly improved. A new UI Mode Manager ( and users benefit from Froyo’s vast and UIModeManager) service adjusts the device configurationdeep performance improvements. It seems some of for night mode, car mode, and desk mode (docking state).Google’s most bloodthirsty quality and performancegeeks combed the platform for “jankiness” (a term As of Android 2.2, applications are not limited toheard often from Googlers that means uneven installation paths on the main device, but can also beperformance and responsiveness) and built in a lot installed on external storage such as an SD card. Theremore instrumentation and benchmarking behind the is also a new generic data backup service Androidscenes. This much-needed performance overhaul applications can use to allow users to transition seamlesslyresulted in a smoother, leaner platform that hums — between Android devices.and a plan to keep it lean and speedy in the future. In terms of sensible but frustrating API changes,This is partly due to the inclusion of a just-in-time the layout attribute fill_parent has been renamed(JIT) compiler for the Dalvik VM. According to the to match_parent (no, it won’t break your old appsGoogle Android team, Froyo runtime performance is — yet). Even debugging got an enhancement with2 to 5x faster than previous versions of the Android a blob-based “logcat” style queue of data in theplatform. You can disable JIT optimization within form of DropBoxManager. The list goes on.the application’s Android Manifest file. The Androidbrowser is also noticeably faster due to its V8 JavaScript 7. Android Market Updatesengine, resulting in a 2 to 3x boost in performancecompared to Android 2.1’s browser (also see No. 10). There are quite a few updates to the Android Market coming with the Froyo release. One of the most useful5. Audio and Media API Improvements new features for publishers is built-in error reporting. If your application crashes on a user’s phone, the userA number of problems and logistical issues with the will have the option to send the error report back toAndroid media APIs have been addressed with the the specific publisher through the Android Market. ThisFroyo release. For example, an Audio Focus API has enables a full-circle, user-developer feedback loop,been added for managing audio playing etiquette allowing publishers to address problems (and receiveamongst competing applications. The SoundPool valuable crash diagnostic information, such as the deviceAPI was also updated to include a callback for when configuration and stack trace) and avoid ratings item has completed loading, as well as the ability 7 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  9. 9. Android Mobile Application Development from A to ZAnd let’s not forget that Android developers are also Android 2.2 includes lots of new MicrosoftAndroid users. In addition to the expected performance Exchange features, such as:improvements and “Chrome” added for the Froyoplatform release, there are a number of compelling • Improved security features allowing administrators toconsumer features delivered in Froyo, such as: enforce password policies • For Exchange administrators, remote wiping of a device8. Tethering and the Portable Hotspot if it is lost or stolen • Exchange calendar support now compatible with theFroyo delivers USB tethering and the ability to turn Android Calendar appyour Android device into a portable Wi-Fi hotspot. This • Auto-discovery for easy account setup and syncingis a an awesome feature, but we wonder how many • Android email support for auto-completion of recipientoperators/carriers are going to hide and/or disable it, names and addresses using Microsoft Exchange Globalas some have done with similar features on competing Address Listsplatforms. If we had to guess, we’d say that this is one ofthose compelling features that might improve Android 10. “The World’s Fastest Mobile Browser”adoption (although at 100,000 device activations aday, Android isn’t doing too badly) but also is most In the Google I/O keynote, Google VP of Engineeringlikely to frustrate these same people when they cannot Vic Gundotra made the claim that the Android 2.2get that feature on a shipping phone. We’ll see. release includes the world’s fastest mobile browser. He illustrated this claim by basically “lapping” the iPad9. Microsoft Exchange Support browser (even after giving it a head start) in a little race based upon SunSpider JavaScript benchmarks. WhetherNobody likes juggling devices based on whether or not the demonstration was a fair apples-to-applesthey’re using it for work or personal reasons, and there’s comparison, the point got across: the performancea pretty substantial class of users out there who are improvements made to the Froyo browser made itgreatly limited in their choice of mobile devices based wicked fast. Android browser performance makesupon their corporate IT requirements — notably, everyone happy (OK, maybe not competitors …) andsupport for Microsoft Exchange. (Frankly, it seems will surely be appreciated as HTML5 grows up.crazy to us to call anything a “smartphone” if it doesn’tsupport Microsoft Exchange, but that’s just us.) 8 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  10. 10. Android Mobile Application Development from A to Z Building Your First PHP for Android Application By Keith Vance G oogle’s open source Android mobile Setting Up the PHP for Android Development operating system is taking the smartphone Environment market by storm. Unlike Apple, which has stringent guidelines and requirements for If you installed PHP for Android, theoretically, youdevelopers who want to offer their applications on can write PHP Android applications with your phone.the iPhone App Store, Google has left the Android But for all practical purposes, that doesn’t work veryplatform wide open. You can well. What you should do iseven write Android applications download the Android SDK,in PHP now. The folks at set up an emulator and writeIrontech have created a PHP code using your favorite editor.port to run on Android, andwith the Scripting Layer for After you’ve downloaded theAndroid (SL4A), you can build SDK, extract it in a directory ofPHP Android applications. your choosing, run the Android application located in theIn this article, I’ll explain how to tools directory, and set up aninstall, set up and use PHP for emulator. From the AndroidAndroid and SL4A, I’ll present SDK and AVD Manager menu,a demo application as an select Virtual Devices and clickexample, and I’ll give a first- the New button. Name yourhand account of the PHP for new emulator (e.g. “Droid2”)Android developer experience. and select Android 2.2 as the target. Enter 10 MiB for SD CardInstalling PHP for Android size and click Create AVD.To install PHP for Android, you have to have a phone Now that you’ve got the Droid emulator set up, clickor emulator running Android version 1.5 or higher and the Start button. Here’s where things get a little tricky,you must enable “Unknown Sources” under Application because you can’t just copy files to the virtual devicesettings. After you have that set, you simply install the you just set up. You have to set up port forwardingSL4A environment and the PHP for Android APK. and push your PHP script to the virtual device using a program called adb, which is part of the AndroidInstalling the SL4A is straightforward, but after you SDK. It is located in the tools directory too.install the PHP for Android application, you needthen click “install” again for it to be fully installed and Next, you will start a server on the virtual device.functioning. If you have trouble with the installation, You will connect with this server to send yourthere’s a handy video demonstration available scripts. The following steps will get you up andon Vimeo to walk you through the process. running as quickly as possible (you can read the 9 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  11. 11. Android Mobile Application Development from A to Zfull documentation for this process at What SL4A does provide are “facades” to a subset of thecom/p/android-scripting/wiki/RemoteControl). Android APIs. (A complete listing of all of the methods available via the SL4A is available at With your new virtual device running, go to the android-scripting/wiki/ApiReference.) But what’s fun Applications screen and click SL4A. about PHP for Android is that you can quickly prototype2. In the SL4A screen, click the Menu button, select View an application and see it in action with just a few lines and choose Interpreters. of code. I’ll demonstrate this with an application for3. Click Menu again, select Start Server and choose checking stock quotes that’s less than 60 lines of code. Private.4. Drag the Android notification bar down and you Copy and paste the code in Code listing 1 at the end of should see SL4A Service. (Click the service and note this article into your editor and save it as quoter4android. the port number your server is listening on, e.g. php and upload it to your emulator. If your emulator 47000.) isn’t running, fire it up, configure your port forwarding5. Open up a shell or command prompt and set up port and upload the quoter4android.php file with the adb forwarding using the adb tool. For example, enter the application included in the Android SDK tools directory. command adb forward tcp:9999 tcp:47000, replacing 47000 with your port number. To run the application in your emulator, go to the6. Set up the AP_PORT environment variable. On UNIX Applications screen, click the SL4A icon and click the or Mac, run export AP_PORT=9999. On Windows, quoter4android.php option. type set AP_PORT=9999.7. To test your script with your emulator, just run To install quoter4android.php on your phone, you adb push my_script.php /sdcard/sl4a/scripts, can set up port forwarding. But it’s easier to just replacing my_script.php with the script you wrote. plug the phone into your computer via USB and copy the script into the sl4a/scripts directory. However,You can also set this up to work with an actual phone. to run scripts on your phone, you have to unplug itJust follow all of the steps you did with your emulator from your computer or else you won’t see any of theon your phone. To make things easier, you also installed scripts when you click on the SL4A icon.should set up an ANDROID_HOME environmentalvariable that points to your Android SDK location You’ll notice that the first line of this applicationand add the tools subdirectory to your path. sets up a constant QUOTE_SERVER. If you’re used to building traditional PHP Web applications, youBuilding an Android Application with PHP don’t have to worry about distributing your code and making changes to it in the future -- that’s not howWriting a PHP application to run on Android is really it works with Android. You have to distribute yourpretty simple after you set up your development actual PHP code. So if you decide to put your PHPenvironment. One thing you’ll notice is that the version Android application in the Android Market and youof PHP included with PHP for Android is an extremely hardcode a Web address in it that you don’t control,stripped down build. You basically have the core PHP your application could break down the road.functions and JSON support — that’s about it. And ifyou’re an Android developer who’s familiar with the For example, this stock quote application actuallyJava framework, you’ll notice that the Scripting Layer for pulls the stock information from a Yahoo Web service.Android doesn’t provide access to all of the components But rather than hardcoding direct access to Yahooyou’re used to having when building a full-blown Android into the Android application, I created a simple Webapplication with Java. service as a link between the Android application and 10 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  12. 12. Android Mobile Application Development from A to Zthe Yahoo stock service. So now if Yahoo decides to Conclusionstop offering this service, or if they change the way it’saccessed, I can just update my Web service located at There’s a lot you can do with the SL4A and PHP The Android code doesn’t need to Android; this article only scratches the surface of what’schange, and nobody’s walking around with a broken possible. While both projects are very young — in fact,application on their phone. Also, by leveraging a Web a new version of SL4A dropped while I was writing thisservice, I was able to take some of the complexity out story (feel free to run the newest version) — as theyof the Android application and move it to my Web mature, more possibilities will present themselves. In anyservice, where I have access to full-blown languages case, keep your Android applications small, tight andand not just a stripped down version of PHP. In this, I wrote the Web service in Perl using mod_perl.Code Listing 1. quoter4android.php<?phpdefine(‘QUOTE_SERVER’ ‘’); ,require_once(“Android.php”);$droid = new Android();$action = ‘get_tickers’;$tickers = ‘’;while (TRUE) { switch ($action) { case ‘quote’: $droid->dialogCreateSpinnerProgress(“Querying stock information server ...”, “Please wait”); $droid->dialogShow(); $quotes = @array_slice(json_decode(file_get_contents(sprintf(QUOTE_SERVER, $tickers))), 0, 3); $droid->vibrate(); $droid->dialogDismiss(); // Possible data points. // “SYMBOL”,”NAME”,”LAST_TRADE”,”MORE_INFO”,”LAST_TRADE_DATE”,”LAST_TRADE_TIME”,”OPEN”,”DAYS_HIGH”,”DAYS_LOW”,”DIVIDEND_SHARE”,”PE_RATIO”,”52_WEEK_LOW”,”52_WEEK_HIGH”,”VOLUME” $output = ‘’; for ($i = 0, $cnt = count($quotes); $i < $cnt; $i++) { $output .= “Company: “ . $quotes[$i]->NAME .”n”; $output .= “Ticker: “ . $quotes[$i]->SYMBOL . “n”; $output .= “Last trade: $” . $quotes[$i]->LAST_TRADE . “n”; $output .= “n”; } $output = html_entity_decode($output, ENT_QUOTES, “UTF-8”); // Something is wrong with &apos; $output = str_replace(“&apos;”, “’”, $output); $droid->dialogCreateAlert(“Your stock quotes”, $output); 11 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  13. 13. Android Mobile Application Development from A to Z $droid->dialogSetPositiveButtonText(“Get new quote”); $droid->dialogSetNegativeButtonText(“Exit”); $droid->dialogShow(); $response = $droid->dialogGetResponse(); if ($response[‘result’]->which == ‘negative’) { $action = “exit”; } else { $action = ‘get_tickers’; } break; case ‘get_tickers’: $response = $droid->getInput(“Stock Tickers (max. 3)”, “Enter Tickers.nSeparate withspaces.”); $tickers = str_replace(‘ ‘, ‘+’ $response[‘result’]); , // print_r($response); //$tickers = $response[‘result’]; // print_r($tickers); $droid->vibrate(); $action = ‘quote’; break; case ‘exit’: $droid->exit(); exit(); break; }}?> 12 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  14. 14. Android Mobile Application Development from A to Z Building Killer Android Tablet Apps: Design and Development Tips By Shane Conder and Lauren Darcey D evice manufacturers are ramping up an these devices run a modified version of the Android OS exciting new line of Android devices: tablets. that has been tuned for the tablet device. Until now, The success of the Apple iPad has proven tablets have been something of a gray market, but that’s that consumers are ready for these devices, about to change.which make consuming media content like video andaudio a rich and enjoyable experience. But there’s Until recently, Google and the Open Handset Alliance havea catch: until now, Android not approved any Android tabletsdevelopers have made certain for use with Google proprietaryassumptions about the target applications such as Gmail, Mapsdevices their apps run on — and most importantly the Androidassumptions like “the device is a Market. This will change with thephone,” “the device has a small next wave of Android tablets;screen” and “the device includes Google has acknowledged thatthe Google app experience.” tablets and other devices will beThese assumptions will not recognized and incorporated intoalways hold true for tablets the Android platform in futureand other types of Android- versions of the Android SDK andpowered devices. In this article, the Android Market. Now, there’swe offer some tips and tricks for a wave of new Android-poweredramping up your skills to design devices slated to hit the shelvesand develop killer apps for the late this year and early nextAndroid devices of the future. year from the likes of Acer, Dell, Samsung, Toshiba, Viewsonic,Android Supports Tablets? Archos and more.Yes, and no. You may be aware that Android has Developers are eager to write apps for these excitingbeen ported to many kinds of devices, including new devices and ensure that their existing apps willphones, toasters, microwaves and laptops. However, run smoothly. The question is: how? Google has madejust because Android runs on these devices doesn’t a statement to the effect that the current version ofmean the user experience is great or the device is Android (2.2, or Froyo) is not designed for tablets. Theofficially recognized by the Android community. next version of Android (Gingerbread) is likely to address some of these issues, but developers need not wait toSo what about the Android tablets that are already in start preparing for the onslaught of Android tablets.users’ hands? Well, the Android operating system is openand free. Manufacturers can put Android on whatever Application Design for Android Tabletsdevices they want to, and many have. Archos has beenmaking Android tablets for quite some time. However, Lazy development assumptions may have worked when 13 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  15. 15. Android Mobile Application Development from A to Zthere was really only one type of device (a phone), some tips for designing user interfaces for tablet devices:but these bad habits may come back and bite youwhen your app is deployed on a device like a tablet. • Keep screens streamlined and uncluttered and ensureReconsider previous design decisions now and update touch controls such as buttons are of adequate size.your applications to make them compliant with the latest • Use flexible layout controls such as LinearLayoutconfiguration options available on the Android platform and RelativeLayout as opposed to pixel-to help ensure that your application is ready for the perfect ones such as AbsoluteLayout.future. • Use flexible dimension values like dp and sp instead ofThe good news is that developing for new Android px or pt.devices isn’t going to be that different from developing • Use alternative resources such as graphic andfor existing ones. Most existing apps will run well dimension resources to provide specialized resourcesenough, provided they’ve been designed prudently, by for different screen sizes, aspect ratios, pixel densitieswhich we mean: and touchscreen types.• The app properly identifies its application hardware • Use alternative resources such as layout and graphic and software requirements using the Android resources to provide specialized resources for Manifest file tags such as supports-screen, uses- landscape and portrait modes. configuration, uses-feature and uses-permission. Testing Apps for Android Tablet Compatibility• The app code checks for hardware, services and optional APIs before attempting to use them. Although few tablets have been released yet, nothing is• The app designers minimized the assumptions about stopping you from beginning to test your existing apps which exact devices or hardware the application and ironing out the obvious issues. Here are some tips would run on. to keep in mind when testing for tablet compatibility:Just as not all Android devices support Bluetooth • Testing on the actual devices (as opposed to theor WiFi, there are — and will continue to be — new emulator) will be critical to ensuring your applicationoptional APIs for working with specific devices, behaves as expected. Some devices, such asincluding tablets. Some of these APIs may be baked into Samsung’s Galaxy Tab, have reported their hardwarefuture versions of the Android SDK (like Gingerbread) characteristics differently than expected. For example,while others may be third-party add-ons available despite having a medium-density screen, Samsungfrom manufacturers. These may be similar to such chose to have its new tablet report as a high-densityadd-ons available for current handsets; the SenseUI screen because it looks better (see Figure 1).is available for some but not all HTC devices, or • Some tablets may not include the GoogleMotoBlur on some but not all Motorola devices. “experience,” so make sure you also test with Android Virtual Devices (AVDs) that do not include the GoogleUser Interface Design for Tablets add-ons.When it comes to designing user interfaces for tablets, • Tablets, among other devices, are beginning toit’s best to stick with flexible layout designs that will scale take a landscape-first approach to the screen. Makewell to various screen sizes, resolutions and orientations. sure your app displays properly in both orientationsThis way, users will find the experience familiar, and handles orientation changes correctly.regardless of what type of device they use. Here are 14 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  16. 16. Android Mobile Application Development from A to Z Figure 1. Android App Mimicking a Tablet on a Custom AVDFinally, one of the best things you can do right now to 5. For the Skin section, choose Resolution and enterensure your app is tablet compliant is load your app “1024” and “600” into the appropriate boxes. If youinto the emulator with a tablet-style AVD configuration enter 1024 then 600, the device will start in landscapeand see how it behaves. For example, use the following mode. If you enter 600 then 1024, it will start insteps to create an AVD configuration that mimics how portrait mode.your application would display on a tablet much like theupcoming Galaxy Tab: 6. For the Abstracted LCD Density, any value will work (although the values 120, 160 and 240 are suggested).1. Launch the Android SDK and AVD Manager. To mimic the actual screen density of the Galaxy2. Press the New… button. Tab, enter 170. The device will be treated as a medium-density display. To mimic the reported3. Enter a name for the tablet (e.g. “Tablet Emu”) and screen density, enter 240. The device will be treated choose an appropriate SDK version, such as Android as having a high-density display. 2.2.4. Create an SD card (we use between 32MB and 512MB). 7. Choose Create AVD. 15 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.
  17. 17. Android Mobile Application Development from A to Z8. When it’s created, launch it with the Start… button. application permissions (as defined in the Android Manifest file using the tag) may be used by the Android9. As the display size is rather large, you may wish to Market to filter apps for devices in the future. scale it down using the launch parameters.Figure 1 illustrates how an application might appear on a In that future, Android-powered devices will likely comecustom AVD to mimic a tablet. It also demonstrates the in many forms: phones, PDAs, music players, tablets anddifference between a medium-density display with the toasters. For now, one of the best things you can do as asame pixel resolution as a high-density display. Because developer is start to think along these lines. Be mindfulthe density is different, the buttons on each screen of the assumptions you make when developing youractually draw at the same size. The medium-density apps, and consider how they will restrict or allow yourdisplay, however, shows a lot of wasted screen space. This apps to run on different types of devices. Review yournot only demonstrates one example of why Android isn’t existing apps and update them with more flexible userquite ready for larger screen tablets, but also shows why interfaces and prudent assertions on device features anda manufacturer might want to report a different value. characteristics.If the rumors are true, the next major release of the With the introduction of Android tablets, developersAndroid SDK (Gingerbread) will begin to address now have a whole new range of devices to targetsome of the device differences in some official manner. with their applications. Android tablets are likely toExpect to see changes such as additional APIs for boast larger and higher-resolution touchscreens,optional hardware, updates to the Android Manifest video output options, front-facing cameras and otherconfiguration options available for targeting specific optional hardware features — at very reasonable prices.device characteristics and perhaps new controls These features enable developers to write new kindsand screen layout options. We are also likely to see of applications and enter new markets. Developingchanges to the Android Market to reflect the plethora Android apps for tablets requires some forethought, butof devices about to reach consumers’ hands. For many of the design principles for writing great Androidexample, sources at Google have implied that certain apps for tablets really apply to all device targets. 16 Back to Contents Android Mobile Application Development from A to Z an Developer eBook. © 2010,, a division of QuinStreet, Inc.