Monday, October 17, 2011

Few Basic things every android developer need to know

This post describe the things you should keep in mind when you starting development of Android Apps.


Beginners and old pros together both need to know where to get help on occasion. All development systems have some kind of support, it’s just that some are better than others. Because Android is open, the development community is infused with the same kind of natural, from-the-gut passionwhich created Linux in the first place. You’ll find these developers the most friendly, helpful bunch you’ll encounter.

The number one destination for all Android development support issues is the Google Android groups. This is where actual Google Android employees hang out. Their contributions are seriously helpful – these guys and gals aren’t just paying lip service because it’s their job. Amongst the groups are:

The Google Android documentation isn’t to be sniffed at either; neither are the numerous samples and examples supplied with each SDK, so be sure to check those out. We are really talking live support here, the stuff that involves real humans, and as stated it’s there in spades from Google.

Its all visual now.
The SDK certainly doesn’t mandate any particular IDE, in fact it goes out of its way to show you how to develop Android apps without one. This isn’t just for diehard console jockeys by the way; as your projects get bigger and more complex, automated build and test tools become more necessary. However, for the majority of Android developers an IDE is pretty much essential.
Now for some flamebait – which one? Eclipse is the one which seems to have the largest number of users, and if you read between the lines and watch the Google training videos you’ll get the impression it’s the favoured one by them too, but I’m sure that’s something they will remain impartial about. The point here is you need one, and if you are familiar with any of the biggies you’ll find it will work the way you are used to anyway. Here are the main contenders:
The current version of Idea is commercial, but the older ones are free and they recently announced a free edition is forthcoming – check here for more info.

It doesn’t get any easier than this.
In the olden days, programmers using C and C++ to develop their apps used to spend up to 80% of their time on memory management issues. They were so complex that crazy little workarounds had to be implemented to fix things Java has been able to sail through from the start – like cleaning up memory after an exception, for example. Even multithreading was done differently according to which flavour of library you used because it wasn’t core to the language. For system code, doing your own memory management gives a higher level of optimisation and control so has its place, but for Apps with the massive performance increases in the JVM and ultra-efficient auto garbage collection, it just seems so ’90′s to have to spend any time doing it yourself.
As far as writing apps on smartphones goes, Java is the slam dunk no-brainer when it comes to ease of use. Just to be clear, we are talking the flavour of Java which Android has implemented, aka “Dalvik”. Don’t let that name worry you though, it’s totally compatible and most definitely not the abomination known as J2ME – a version of Java cut down so severely it was practically useless.
Not only is it as easy as it gets, but this harks back to the support point mentioned earlier. There is literally well over a decade of expertise out there, from best practices to optimisation to reusable libraries.
You have to know Java, sure, but this is nothing like the pain of the alternatives.

Polish, polish, polish.
Android is the canvas, you are the artist. Whilst you don’t have to be the digital equivalent of Michaelangelo just ask yourself when was the last time you saw a best selling app which was butt ugly? Being on at least “crop to size” terms with a decent graphics package will stop you being relegated to the “works but lousy UI” department, and unfortunately that is the reality of the game we are in now. If you don’t have the composition skills, you might want to seriously consider investing time getting some, or find someone who has and get them to do them for you. If you have the luxury of working in a team with dedicated graphic designers, well whoopie doo for you ;-) The emphasis in Android is on PNG files as they have terrific support for layers and transparency, so you can choose from the multitude of open source or commercial offerings as long as they handle this format well.
Popular choices:
Once upon a time, a young programmer was struggling to make a certain feature work. As hisfamous boss realised it wasn’t going to make it, he came out with the line “if you can’t make it work, at least make it look good”. This dubious advice did contain a germ of sense – UI hits the users first on such a basic level that it almost becomes more important than the app itself. Put it another way: you will almost certainly be facing some kind of competition, if not when you launch then afterwards when the other guys realise you have something they can copy. Assuming these apps do pretty much the same things, what’s left to differentiate them if not the UI?

Separate UI from code.
The technology behind webpages is what drove the explosive growth of the internet from the start. All that was sent from the server to the browser were the instructions needed to recreate the page, not the page itself. Not only did this minimise bandwidth, it also allowed the layouts to be marked up with additional data describing the pages themselves. XML is now ubiquitous in computing. Android took XML and used it as a way to describe the physical layout of its UI components in a way similar to HTML for the web. The huge advantage this gives is the separation of the apps logic from its presentation. This is an idea you encounter over and over again, especially in server based webapps, but it’s never been widespread on mobile phone development before.
The old way was to entrench the layout instructions directly in the code, so this made changes very cumbersome and error-prone. Some other benefits arise nicely too – internationalisation, for example, is now a breeze as you can ship different versions of the XML layout without changing the code that uses them.
Android allows you to mix and match these approaches. You can still get at the contents of the layouts in code, once loaded from XML, for any run time tweaks you need, you can stick to the XML-only approach or indeed you can ignore XML completely and do it all manually..
The reason this is an important Android skill to know is because once familiar with them you can rapidly create, or prototype, complex UIs which behave they way the final app should. There are only a few to deal with, and their use is demonstrated in the source of the sample apps which ship with the SDK and online. They include:
Knowing the UI architecture – the View hierarchy in particular – is also pretty much essential to successful Android app development, but you soon get that “aha!” moment after working with it for a while, when everything slots into place.

There’s more than one!
When your hear Android is open it means much more than just the OS source. The Market is too. Within 5 minutes of uploading your app it’s usually available. Closed ones mean you have to deal with all sorts of crap, and even if nanny does decide to let your app grace its stores presence, it can withdraw it at any point in the future for any reason – including the fact it is about to release a competing one of its own! Ugh – nasty. It’s like 1984 with a huge screen showing a black turtle necked big brother glaring down at rows and rows of slave coders, and Android is the girl who runs in and throws a hammer up, freeing everyone.
It’s useful to understand exactly how the Android Market works, as this will benefit you when it comes to planning distribution channels for your app. First off, you can stick your apps anywhere and any Android device that can access them (e.g. a website, email attachment, bluetooth etc) can install them. Straight away that’s blown away the closed guys. Next it’s important to realize that the term “Android Market”, strictly speaking, refers to the system which the app available on “comes with Google” devices can talk to – which to date has been all handsets.
We know core Android is open source and free, but the extras which Google bundles up to the handset manufacturers, like Email, Google Maps and as mentioned the Android Market, are not. Think of the situation if, say, Windows were free – Microsoft would still sell Office separately. This means device manufacturers who use Android but don’t “come with Google” don’t have access to the Android Market, so usually end up building their own parallel app store – I’m looking at you, Archos. It’s also possible for the carriers to lock down access to appstores too. For the developer, this is a great opportunity. Say you’ve released an app to the Android Market. You can now decide if, and how, you want to release it on any of these alternate ones, perhaps using a different charging model or customising it further.
The charging mechanism you use will limit your distribution method. You wouldn’t stick a paid app on an unrestricted download site, although you might if it was service based where the user paid when the service was activated via a remote server. Also, this is a rapidly advancing field. Currently, to buy from the Android store users must have a Google Checkout account. T-Mobile, however, have just announced plans to support integrated billing, where the users purchases appear on their monthly phone bill. Many Android developers are welcoming this news as they feel that the lack of such a service has been holding back takeup of their apps. In the future there also may well be a web or desktop app which lets users buy apps directly, then have them appear on their handsets. Unofficial ones do currently exist, but all that’s just rumour right now…

Tame that fragmentation beast.
J2ME was touted as Java in every handset – and that’s pretty much what it became in the end. To achieve this across such a diverse range of devices, compromises had to be made. Most now accept those compromises were too limiting, meaning you had built a car with 1 gear, only available in black with 1 seat which could onlfy travel on the freeway. Manufacturers wanted to sell more handsets ;-) They “enhanced” the standard J2ME with their own extensions, which was great for them but very, very bad for the ecosystem as a whole. Apps which used proprietary extensions were not compatible, resulting in its ultimate demise.
Android is so much richer than J2ME it’s off the scale, but those pesky manufacturers will insist on trying to differentiate their products. There’s a risk that this fragmentation could happen again, and we could end up in the nightmare situation of having to develop and market apps for each Android device. To be fair, the closed guys have their faults but this isn’t one of them. Heres Googles take on the issue:
So what can Android developers do about it? As it happens, it’s nothing like as bad as J2ME. When you think of different form factors you have the obvious one, with or without a keyboard, and then the usual culprits such as screen pixel density, memory capability, cpu power, sensor support and so on. There are some obvious pitfalls to avoid, like hardcoding absolute values in your XML layouts, and some rules to stick by such as always using density-independent pixels (“dip” or “dp”) and scale-independent values (“sip” or “sp”).
There are really only 3 screen size to sizes to target, and support is built in as explained here. Basically, your code can interrogate its environment at start-up to detect the presence/absence of essential hardware features, so your GPS app should fail gracefully with an error message if location isn’t supported, and that’s all done in one app.

Moving targets can be challenging.
Google has minimised the disruption caused by API changes across Android releases, and documented them very well, but there are still a few things you need to be aware of. The SDK lets you test your app on multiple platforms with its AVD (Android Virtual Device) support. You can also specify the minimum version to allow in your app descriptor file, AndroidManifest.xml. This means that when a user attempts to install your app on a device with a lower version than that which it was targeted for, they will be told immediately and they won’t be able to. This is preferable to running apps on unsupported platforms as it could fail in unpredictable ways.
Android releases are named after desserts, so we had Cupcake (1.5), Donut (1.6) and Eclair (2.0), the next two are rumoured to be Flan and Gateaux – in case you hadn’t spotted it, there’s an alphabetic progression there ;-)
The usual rules regarding writing code for undocumented features apply, and this is much easier to do when you are dealing with a full open source system as you can see exactly what those functions are and do. Basically – avoid them! Quite a few folk got their fingers burnt when apps out there in the market targeting 1.5 started failing when the 1.6 release was rolled out to end users. There are similar reports for Droid too, which runs Android 2.0. On that point developers can fairly cry foul as none had access to Android 2.0, so there is nothing for it but to rebuild and release – but pay careful attention to those deprecation warnings.

Never forget it’s a phone!
Your app is entering into a pretty harsh environment – it can be subjected to all manner of external prods, kicks and pokes like running out of memory, running out of power or losing a signal. Oh, and a call might come in ;-) To support all this, the Android designers implemented a powerful lifecycle support mechanism, all aimed at preserving the integrity of your app no matter what manner of nasties it gets subjected to. Your app will receive callbacks, these are hooks in your code which you implement as methods with fixed names such as onPause() and onRestart(). This way, when these events occur, your code executes, giving you the chance to handle things in a controlled way, such as preserving data to storage when the app quits and so on.
Here’s the Google diagram:
This is documented here. Seeing this for the first time might seem initimidating, but it’s not really when you think of how the phone can be used. Say that call does come in – your app will be paused and sent to the background whilst the call is dealt with in the foreground. Your app’s onPause()handler will be called. Then, after the call, the user may switch back to your app and so theonResume() method is invoked. Understanding the app lifecycle allows you to play nice with the rest of the handset and makes sure your users get no nasty surprises when using your app in their phone as a whole.

The icing on the developers’ cake – we are spoilt rotten by this awesome tool.
Never before in the field of mobile development have you been able to control your device with such power. DDMS stands for Dalvik Debug Monitor Server and is the interactive tool which ships with the SDK. Veteran mobile developers will tell you that the biggest problem with handset development is knowing what the device is doing at any moment. Emulators can go so far but often don’t cut the mustard when it comes to behaving exactly as if it’s a real world device. DDMS talks to both the emulator and the real hardware. All Android devices have support for a comms system called the ADB, short for Android Debugging Bridge. When you run up the DDMS you get a visual representation in your IDE of what the code in the connected system (emulator / hardware / both) is doing via the ADB, and you can interact with it.
The DDMS is documented here, and here’s what it’s like in action:


The great thing about the DDMS is that it really doesn’t know if it’s dealing with a physical device or the software emulator – and that’s exactly what you want because neither does your code. As you can see above, you can monitor the processes, data storage (push and pull files to and from its sdcard for example) but the best feature is the LogCat, this is the system which lets you filter logging code in the Log window, explained in more detail here.
Your IDE will most likely already have a regular debug window where you can set breakpoints and single step code, but that’s aimed at any regular Java process. The DDMS understands specifically your Android device, so is really worth getting to know well when you need the extra level of control it offers.

2 comments:

  1. You describe very useful information about basic things for android programmer. It may be very useful to beginner of Android Programmer, they can understand basic aliments and also learn about programming flow and compiling process.

    ReplyDelete
  2. I think it will help for the beginner too much. Since as a developer i think this is a very good tutorial for a beginner.

    ReplyDelete