This article is based on iOS 4 in Action, to be published on June 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ Use promotional code 'java40beat' and get 40% discount on eBooks and pBooks ]
What’s multitasking? It’s one of the important and exciting API features in iOS 4. When the end user quits an application, instead of termination, the application will enter the background state so that we can use this feature to support fast app switching, running tasks in the background. In this article, we will take a look at the basics of multitasking on iOS 4 and the applications life cycle.
Multitasking is a key feature that has been requested on the iOS since it was first released. It’s basically the ability to let the device run more than one application at once. For example, you may want to listen to music using the Pandora application while performing other tasks such as checking your email.
In the past, Apple had a few arguments opposed to multitasking on the iOS; the primary one was that it slows down the device and makes for an overall poor user experience. If you allow the user to run too many applications at once, the device will eventually run out of memory and start killing those applications. Another argument was that running many applications at the same time drains battery life much more quickly. Because running an app requires processing power, the constant strain on the processor will quickly result in a drained battery.
Finally, in iOS 4, Apple has implemented the ability for programs to run in the background. Figure 1 shows the multitasking UI on iPhone and iPad. This isn’t true multitasking per se, but it’s getting closer and addresses most of users’ other gripes.
Figure 1 Multitasking UI on iPad and iPhoneApplications that wish to execute operations in the background are restricted to certain tasks, which include the following:
- Requesting a set amount of time to finish a task.
- Implementing specific services allowed by Apple, including location tracking, audio playback, and voice over IP services.
By default, all applications that are compiled for iOS 4 will support multitasking. But after the user taps the home button, the app will go into the background suspended state unless the background running mode is added.
Because most applications don’t require constant usage, the system automatically puts them in a suspended state when the user exits them. Upon resuming the application, it should load in the last state it was in when the user exited it. This is more of a fast application-switching model. A great comparison is when you are reading a book, you may want to take a break and get a cup of coffee, so you will put a bookmark at the page you stopped. Later when you are back, you can continue from the exact same page where you left.
Application life cycle
With the iOS multitasking support, the application life cycle expands to not running, running in the foreground and running in the background (as shown in figure 2).
Figure 2 Application life cycle in iOS 4When the application first launches, it will move from the not running state to the foreground, stay inactive briefly, and become active. That’s the time when the MainWindow.xib file gets loaded into the application. While the application is running in the foreground state, an SMS message or an incoming call could pop out and interrupt the current application, which, therefore, will become inactive.
When the user presses the Home button, the application will move from the foreground state to the background. The application may continue running if the background mode is supported on the device (in other words, iPhone 3G and iPod Touch 2nd Gen won’t support the background state at all), such as the background audio. When a user is listening to their iPod and pushes the Home button, the application still plays music in the background state.
Most applications will stay in the suspended state after moving to background mode and won’t execute code in the suspended state. When the user switches back to this application after some time, it will automatically return from the background to the foreground state, where it was left last time.
Sometimes, when the system is running low on memory, the heavy memory usage applications in the background will get terminated in order to free up more memory for the foreground application. Another possibility is when the user manually terminates the application from the multitasking UI stack.
In iOS 4, it’s really important to understand the application’s life cycle in order to design a responsive and smooth transition application. For example, when you are designing a game application, you want to pause the game when there is an incoming call and save the important data before the application quits or moves to the background state. How can you monitor the application’s life cycle during the run time?
There are two solutions available on iOS 4. One solution is to respond to each major callback method in the application delegate. Another way is to observe the notifications from the notification center. Table 1 has a complete side-by-side list of application delegate methods and notifications.
- application:didFinishLaunchingWithOptions:—This is the most important method and has been used in the entire book. This method can be used to initialize the application and prepare it for running in the foreground state, such as loading the Main Window nib file.
- applicationDidEnterBackground:—It’s the key callback method to prepare the application for the background state. Use this method to release shared resources, save user data, invalidate timers, and store enough application state information in order to restore your application to its current state. If the application supports background execution, this method will get called instead of applicationWillTerminate when the user taps the home button.
- applicationWillEnterForeground:—This method is sent when the application resumes from the background state and will enter into foreground. You can use this method to restore the application and undo the changes before the application enters the background. For example, the application can load the resources and restore the data.
- applicationDidBecomeActive:—This method can be used to customize the application behavior when the application becomes active in the foreground. For example, it will be called when the interruption is gone. Or when the application continues transition from inactive state to active state after the method applicationWillEnterForeground gets called. Use this task to restart the tasks paused before. For example, you should continue the game, restart the timer, and update the user interface.
- applicationWillResignActive:—This method gets called when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it’s about to start the transition to the background state. You can use this method to pause ongoing tasks, disable timers, and tune down OpenGL ES usage.
- applicationWillTerminate:—This method is called when the application is about to get terminated. The application will transit back to the not running state.
In order to monitor the application’s transition states with the notification center, table 1 has a complete list of notifications. For example, you can use the code snippet below to register a notification for UIApplicationWillResignActiveNotification inside the view controllers.
NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter]; [notifCenter addObserver:self selector:@selector(resignActive:) name:UIApplicationWillResignActiveNotification object:nil];
As you can tell, in order to support the multitasking smoothly in the application, you need to consider saving the application’s data properly before the application moves to the background, and reload the necessary data before the application launches from the background mode.
Multitasking is really useful in so many ways. With the application continues running in the background, you can provide an amazing user experience with the iOS 4′s platform. We covered the multitasking basics and the application’s life cycle on iOS 4.