Monday, February 8, 2010
Android vs. iPhone: A Developer's Perspective, part II
(See also Part I.)
OS features
The big winner here is Android, due to its multitasking. You can call other apps, eg a browser or a file-system picker, get results from them, and use those results in your own app; all these things are completely impossible on the iPhone, where (aside from a few special cases like iTunes) only one app may run at a time. (And even if you want to sacrifice yourself to launch another app, you can only do so in very restricted circumstances - if they have registered a URL scheme.)
The browser special-case is worth mentioning; you can include browser windows in your own app, and mine do so in a few different places - but this is often not as full-featured or convenient to the user as opening up the full Safari browser.
You can also write Android services that run in the background, and you can launch them at boot time (if the user permits) by registering for the BOOT_COMPLETED intent. What it doesn't really, provide, though, is "push" notifications (other than by faking it with eg Comet HTTP Push) which the iPhone does offer. That's the iPhone's only advantage in this category, though.
Phone features
The iPhone is locked down. You don't get direct Bluetooth API access; you do in Android. You don't get direct SMS access; you do in Android. For security reasons, they claim in Cupertino. At least (like Android) it now lets you access the proximity sensor.
But to its credit, the features it does offer are a joy to work with. In particular, the built-in camera/preview screen (for iPhone) / picture selector (for iPod Touch) is excellent, and requires all of a half-dozen lines of code to launch and respond to. The Android camera code, last I looked at it, was much more complex.
Location management is a little messy and complex on both systems, but overall Android's registration model is easier to work with than the iPhone's delegation model.
The iPhone SDK comes with this daft notion that all settings for all apps should probably be in a single System Settings screen accessible from the main menu; you can roll your own, but it's inconvenient. Android, by contrast, lets you create a settings screen by simply writing XML, no Java required unless you want to customize it. On the other hand, the iPhone simply makes "your default settings" available, whereas Android provides the possibility of multiple sets, which is doubtless more flexible and powerful but also more annoying to work with.
Accessing system and app resources (eg image files) is a little counterintuitive on Android; at compile time, it scans a predetermined bunch of directories, and automatically builds an "R" file with a bunch of final static ints, each of which uniquely identifies a resource; you then use those in code to access resources. (There's also an Android.R for built-in-resources.) This is confusing at first, but fine once you get used to it.
The iPhone makes the basics easy for you in code -
[Image imageNamed:@"myImage.png"]- but if you want to go beyond that, the whole resource-bundling thing is less than intuitive, and while I had no trouble accessing bundle resources, I never felt like I had a clear idea of what was actually going on, unlike with Android.
Screen building
No sense pussyfooting around: when it comes to actually building the screens of your app, the iPhone has a massive advantage. It provides an excellent WYSIWYG tool, and the components it offers - buttons, lists, etc - mostly just look a whole lot nicer and sexier than the Android ones.
(That said, I have two minor complaints about the iPhone UI components: 1) No drop-down options in menus - instead you either have to code an ActionView or use one of the huge screen-eating spinners. 2) The absence of a border around TextViews does not look good and just serves to confuse users.)
In general, though, the iPhone wins here. The delegate model of TableViewController gives you powerful and fine-grained control far more easily than the adapter model of ListActivity. As far as "complicated, hard-to-work-with, but useful subclasses of your basic list view" goes, I'll take the iPhone's LocalizedIndexedCollation over Android's ExpandableListView, though I sure wish both were more developer-friendly.
And then there's maps. Jeez. In iPhone, if you want to add a custom marker for a map, then in the ViewController for that screen, you just override a method and write six lines of code:
- (MKAnnotationView *)mapView:(MKMapView *)myMapView viewForAnnotation:(id)annotation {
NSString viewImageName=@"myImage.jpg";
MKAnnotationView *myView = (MKAnnotationView*)[myMapView dequeueReusableAnnotationViewWithIdentifier:viewImageName];
if (myView==nil) {
myView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:viewImageName] autorelease];
myView.image = [UIImage imageNamed:viewImageName];
}
return myView;
}
In Android, first you have to write a whole new inner class that extends ItemizedOverlay
class ListingsOverlay extends ItemizedOverlay{
private ArrayListoverlays=new ArrayList ();
public ListingsOverlay(android.graphics.drawable.Drawable defaultMarker) {
super(defaultMarker);
}
public void addOverlay(OverlayItem overlay, Drawable marker) {
super.boundCenterBottom(marker);
overlay.setMarker(marker);
overlays.add(overlay);
}
// necessary because populate() is protected
public void doPopulate() {
populate();
}
@Override
protected OverlayItem createItem(int i) {
return(overlays.get(i));
}
@Override
public int size() {
return(overlays.size());
}
and then something like this:
mapView = (MapView) findViewById(R.id.mapview);
mapOverlays = mapView.getOverlays();
mapOverlays.removeAll(mapOverlays);
Drawable drawable = getResources().getDrawable(R.drawable.map_fave);
itemizedOverlay = new ListingsOverlay(drawable);
OverlayItem overlay = new OverlayItem(point, mappable.getIDString(), mappable.getMapDetailText());
Drawable marker = MappableItem.GetMarkerForMappable(ITRMapView.this, mappable.getCategory());
itemizedOverlay.addOverlay(overlay, marker);
itemizedOverlay.doPopulate();
Menus and navigation are also easier and prettier on the iPhone; you can add sleek-looking buttons and toolbars and simply set them to call the selector of your choice, and you get a great NavigationController for iTunes-like interfaces, plus sexy animation. No real equivalent on Android.
On the other hand, Android's XML layouts, while tedious and irritating, and not as pretty or near as exact as the iPhone's WYSIWYG, do work well once you get the hang of them - and they make it much easier to support multiple screen sizes and different orientations. (My iPhone app simply doesn't do landscape orientation; my Android app handles it almost perfectly, without me ever having thought about it.) This wasn't a big deal for the iPhone until last month - but apps that previously were confident of a 320x480 screen now have to deal with the iPad.
The Internet
Accessing web services and launching in-app web views is easy and effective in both Android and iPhone. Edge to the latter, though; there are a couple of weird little bugs with Android's WebViews (though they can be worked around with ease) and the iPhone gives you both more SDK options and better documentation.
Release
Building an iPhone app is kind of scary. You're suddenly reminded that under the hood it's terrifying C++; the "Build" screens are full of dozens if not hundreds of byzantine, cryptic, intimidating options for compiling, precompiling, linking, etc., and you find yourself desperately hoping you've set up your import libraries perfectly and suddenly very careful not to touch anything.
That said, XCode works really well. (Have I mentioned that debugging is far easier with the iPhone SDK? Debugging is far easier with the iPhone SDK. With Android I usually wind up resorting to debugging with log messages.) What does not work really well is Apple's paranoid certification hegemony. God forbid that anyone run an app without going through the App Store!
So you need to go to Apple's site and futz around with it and with device IDs and create and download separate certificates for debug and release, and your temporary "provisioning" device certificates expire every three months, and while it is theoretically possible to build an app for someone else's device, email it to them, and have them install it, I have yet to actually succeed at this, despite repeated attempts. (It's somewhat easier if their device is plugged in to your machine.)
You know how it works on Android?
- You build your app.
- You sign your app. (Which Eclipse can take care of with a simple wizard.)
- Anyone in the whole world who wants to can now download and run the app.
There's a slight pitfall if you're working with Google Maps - you have to jump through hoops like Apple's to create separate debug and release Maps API Keys, and ensure you're using the right one - but by and large, it's miles easier and better than trying to finagle your way into Apple's walled garden.
Plus, if you've built an app and released it, and found some sort of subtle bug? With Android, you can fix that and have a new version up on the Android Market in five minutes. With Apple, it's ... a week? A month? Who knows? App Store approval is an infuriating black box.
Overall
They're both excellent systems. They both have their pros and cons. Overall I would rate the iPhone as better, both in terms of what you can do with it and how - but Android is superior in fundamental ways (eg multitasking and memory management) and catching up fast in terms of results. If Apple doesn't watch out, and move fast, they're going to find themselves superseded soon. Maybe this year.
Labels: Android, building, iPhone, maps, notification, preferences, push, release, resources, Settings
Sunday, February 7, 2010
Android vs. iPhone: A Developer's Perspective, part I
(See also Part II.)
I've spent the last month or so building both Android and iPhone versions of my app iTravel. (See http://wetravelright.com/ for details and links.) Which gives me a pretty good perspective from which to compare and contrast the Android and iPhone environments and SDKs. Hence I give you the following head-to-head analysis, from a developer's point of view:
Language
Non-programmers often think that one's language of choice is a big deal, but really, once you've learned two or three programming languages, picking up another is generally something you can do in a day or two. That said, there are often substantive differences. And this is definitely true of Java (for Android) and Objective-C (for iPhone.)
Let's start off with the really annoying stuff: Objective-C's memory management. By which I mean, its complete lack of any. Programmers have to manually allocate and release memory when writing for the iPhone SDK, which is positively medieval. If you fail to do so, and there are many pitfalls, then you leak memory which is lost until the device reboots. This is awful. (And it's no longer true of the Mac SDK, incidentally; but the iPhone is behind the times.)
There are other annoyances. You have two files to contend with for every class - a .h and a .c file. Which is inconvenient and complicating and inelegant. And suppose you have a basic, bog-standard instance variable. You generally wind up declaring it in, count 'em, not one, not two, not three, but four different places.
In your .h:
{
NSObject *object
}
@property (nonatomic, retain) NSObject *object
In your .c;
@synthesize object
and later, in dealloc(),
[object release];
Whereas with Java, you have one single .java file, which in general will have
private Object object;
public Object getObject() { return object; }
private void setObject(Object o) { object=o; }
all in one place. I know which one I think is easier.
But. On the other hand. Objective-C is sort of the bastard son of C, which is awful, and Smalltalk, which is awesome. As a result, it has Smalltalk-like features like selectors:
[caller performSelector:@selector(myFunctionName)]
...in short, you can use functions as (more or less, ish) first-class objects. Try that in Java and if memory serves you'll most likely wind up in the irritating labyrinth of reflection. Plus, you get options like "doesNotRecognizeSelector:", which can be easily misused, but is potentially very powerful, and does not exist in Java.
On the other hand, Objective C is really annoyingly logorrheic (meaning wordy) especially when it comes to string handlers. Suppose you have strings A and B, and you wish to combine them into string C. In Java, the syntax is
C=A+B;
whereas in Objective-C, you type
C = [A stringByAppendingString: B]
Or suppose you want the location of the last slash in string A. Java:
n=A.lastIndexOf("/");
Objective-C:
n = [A range ofString:@"/" options:NSBackwardSearch].location;
I much prefer Java's syntax and simplicity. But I do admire Objective-C's flexibility.
Development environment
By this I mean: the "integrated development environment" in which coders work; the documentation for the IDE, the language, and the libraries; the testing and source-code support; and all the stuff that is meant to help you write better code faster.
The Android and iPhone IDEs and documentation really incarnate the attitudes of the two companies in question. Android doesn't exactly have an IDE of its own, although they recommend that you use the Android plug-in for the open-source Eclipse IDE, which is slow, irritating, and buggy in various minor ways. The documentation is written by smart people for smart people, with little handholding. Flashy graphics are minimal to nonexistent. And a lot of important stuff is still handled by tools meant to be run from a shell rather than a GUI. But the search function is excellent.
Apple's IDE is slick, seamless and powerful. It comes with a visual tool to help you lay out the screens of your app. The documentation is full of step-by-step guides (although they are often oddly lacking or confusing) and high-quality graphics and other visualizations.
I have many complaints about both. Eclipse is slow and annoying, and I could only get Android's JUnit test harness to run successfully from a terminal window, rather than the IDE; similarly, I had to use shell tools to sign packages, get a fingerprint for a Maps IDE, install a package on my phone, etc. All of which really calls into question the I in IDE.
On the other hand, at last the external unit-testing actually works; XCode's built-in harness is so bad that Google built and released an entirely separate one, which has the advantage of actually functioning correctly. On the other hand, its Subversion integration is excellent, which is not true of Eclipse.
Both have plenty of official and unofficial online support, as well, at official support sites and places like Stack Overflow. Android's open-source ethos gives it a big advantage in terms of external packages, though; for instance, if you want to build a barcode scanner into an Android app, there's a whole open-source library out there for you, ready to be plugged in. For the iPhone? You'll have to roll your own. Sorry.
Multithreading
In phone apps multithreading is key, because the phone needs to remain as responsive as possible, so you need to do your heavy lifting behind the scenes, outside the main UI thread.
Both the iPhone SDK and Android support multithreading, but the latter's is much more convenient, especially if you want to call back to the main thread once your background thread has done its thing. On the iPhone, you have to do something like:
-(void) doWebView {
NSThread* htmlThread = [[NSThread alloc] initWithTarget:self selector:@selector(loadHtml) object:nil];
[htmlThread start];
[htmlThread release];
}
-(void) loadHtml {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *html = doUnroll ? [self getUnrolledData] : root.data;
html=[NSString stringWithFormat: @"%@%@</body></html>", [Util getBaseHtml], html];
[self performSelectorOnMainThread:@selector(setHtml:) withObject:html waitUntilDone:NO];
[pool release];
}
-(void) setHtml:(NSString*)html {
[webView loadHTMLString:html baseURL:nil];
[webView sizeToFit];
[self.tableView setTableHeaderView:webView];
}
Whereas on Android, you can use Java's equally irritating Runnable() framework, but Android provides an extremely convenient (and quite flexible) short form. Just subclass AsyncTask in an inner class:
new LoadHtmlTask().execute();
class LoadHtmlTask extends AsyncTask{
protected String doInBackground(String... strings) {
String headerData = Settings.GetHtmlPrefix() + (unrolled ? getUnrolledData(viewRoot) : viewRoot.getData());
return headerData;
}
protected void onPostExecute(String results) {
mHeaderView.loadDataWithBaseURL("local", headerData, "text/html", "utf-8", "");
}
}
which seems much more encapsulated and intuitive to me.
Persistence
On paper, the iPhone environment has a big advantage here: it features the Core Data object-persistence layer above the SQLite database, whereas Android requires direct DB access.
For me, though, direct DB access was not awful, and given the constraints of my app, arguably simpler than jumping through all of Core Data's hoops - using the separate tool to declare a data model, having to rebuild your custom code every time you add a column, etc. All that without even getting thread safety.
However, I'm totally comfortable writing SQL, not all developers are, and my app had pretty straightforward DB requirements. Core Data is undeniably more elegant and ultimately better. Plus you get nifty little features like shake-to-undo, semi-automatic migration data models in installed apps, etc. And it's not like the Android tools are particularly easy to work with. Check out the method in android.database.sqlite.SQLiteDatabase you use to perform a query:
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
As a (Google employee) friend of mine said, "Holy positional parameters, Batman!" Needless to say, one quickly wraps this monstrosity in other methods less prone to grievous error...
Part II of this post compares and contrasts system features, phone features, settings and resources, screen building, internet connectivity, and the app install/release process. (It does not compare and contrast graphics programming, as my apps are data-heavy not graphics-heavy.) Don't touch that dial.
Labels: Android, compare, comparison, contrast, developer, environment, IDE, iPhone, Java, language, multithreading, Objective-C, persistence, theads
Subscribe to Posts [Atom]