Background Apps on the iPhone

The iPhone 2.0 software was recently released, and with it came the ability for users to download native apps (i.e., not web sites) directly to their phones from within the iPhone UI or via iTunes. Developers (anyone who pays Apple 59GBP for the privilege) can then write their own apps and have them available for purchase in the App Store.

One limitation of the Apple-sanctioned SDK is that only one application is allowed to be running at a time. This presents a problem for apps such as IM clients, music players and other programs whose functionality relies on being able to run in the background. Another example (courtesy of James) would be an app that takes advantage of the iPhone 3G's GPS chip to create a log of all the places you visit.

However, there is a neat trick that I discovered: your app will only get terminated if you switch away from it, and hitting the iPhone's power button while your app is in the foreground doesn't count as switching away. The upshot of this is you can create apps which continue to run while the iPhone is in your pocket - perfect for the GPS example.

Achieving this is as simple as implementing two methods in your UIApplication delegate - applicationWillResignActive: and applicationDidBecomeActive:. Here's a simple example to demonstrate the effect.

In your UIApplication delegate header file, add a new ivar: BOOL activeApp. Then, in your implementation, add the following three methods:

- (void)applicationWillResignActive:(UIApplication *)application {
	NSLog(@"resigning active status...");
	activeApp = NO;
	[self performSelector:@selector(sayHello) withObject:nil afterDelay:1.0];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
	NSLog(@"becoming the active app...");
	activeApp = YES;
}

- (void)sayHello
{
	NSLog(@"Hello!");
	if (!activeApp)
		[self performSelector:@selector(sayHello) withObject:nil afterDelay:1.0];
}

Then run the app on your iPhone, hit the power button, and watch the log fill with pointless but oh-so-cool messages.

Of course, when the phone is put into standby mode by the user the expectation is that barely any juice will be drained from the battery, so it's a good idea for your app to reflect this. Indeed, you can make a big difference by halting your updating of the UI; the user isn't going to see it when the screen is turned off.

This isn't a perfect method, and won't be helpful in situations where the user wants to do other things with their phone while your app continues to run. However it might come in handy for certain scenarios.

date: Mon Jul 21 06:03:56 2008 | permalink | tags: howto iphone code