Ios_ the life cycle of an application

Source: Internet
Author: User
Tags switches

Each iphone program contains a unique UIApplication object that manages the entire lifecycle of the program, starting with the loading of the first display interface, and listening to system events, program events, and the execution of the entire program.

int main (int argc, char *argv[]) {

NSAutoreleasePool * Pool = [[NSAutoreleasePool alloc] init];
int retVal = Uiapplicationmain (argc, argv, nil, nil);
[Pool release];
return retVal;
}

In the main function, the second line of code UI application Main (ARGC, argv, nil, nil);

The UIApplication object is initialized, the object is suppressed, the last 2 arguments of the function are changed: string to identify the UI application class and UI application proxy class , where the default is 2 nil,

The previous nil initializes the UI application class as the default, or you can use your own defined UI application subclass instead of nil .

The latter parameter is the agent, although the UI Application object manages the entire program life cycle, in fact, it does not do anything specific, it is only responsible for monitoring events, when the need to do the actual work of the UI application proxy class to do, UI Application is the equivalent of commanding the Commander to communicate the command to the UI application proxy class This soldier, and then by this soldier to solve the problem, so you need to set the UI Application object proxy class.

2. Development process

There are five types of iOS apps in a single state:

1. Not running: The app has not started, or the app is running but is stopped by the system on the way.

2. Inactive: The current app is running in the foreground, but does not receive events (other code may be executing at the moment). Typically, a midway transition stays in this state briefly whenever the app is switching from one state to another. The only time it takes longer to stay in this state is when the user locks the screen, or the user is prompted to respond to certain events (such as phone calls, unread text messages, etc.).

3. Active: The current app is running in the foreground and receiving events. This is the normal state at which the app is running in the foreground.

4. Background: The application is in the background, and the code is still executing. Most applications that will enter the suspended state will briefly enter this state. However, applications that require additional execution time will remain in this state for a longer period of time. In addition, if an application needs to run directly into the background when it starts, such an application will enter the background state directly from the not running state and will not go through the inactive state. For example, there are no interface applications. Note Here does not refer to the application without the interface, in fact, it can also be an interface application, but if you want to directly into the background state, the application interface will not be displayed.

5. Suspended: The application is in the background and the code execution has stopped. The system automatically moves the app into this state and does not notify the app before the move. When in this state, the app still resides in memory but does not execute any program code. When the system has a low memory alarm, the system will clear the suspended state of the application to provide enough memory for the app that is running in the foreground.

Such as:

3. State transitions

3.1 Application Startup

A. Opening a new project

When the app starts, it enters the FZ yo from the not running state? " http://www.2cto.com/kf/ware/vc/"target=" _blank "class=" Keylink "> vcmvncm91bms78txf1rg90734yotiywnrz3jvdw5k1mvq0kgjvfji68ewzkjksaosxutktdfu1txkx9kqvfi1vufjdgl2zde0zkyjrnbqzb674c /itszu3b34you1vuluywn0axzl17tmrkgj1nrtptpdxvs2r8qxo6zptc2zu+ g0tl2o0ru49nbyb2nlc3o6zdk7upbw93rocmvhzkossqlh0tta1vd0ahjlywtw0lx308ntywluuq/k/ aosvltjz8pmtv7m4bw9tcshoybtywluuq/k/ dtatls9qlmks8zksdpjwgnvzgxx1lavyfqzyagjbwfpbrqvyv24uttwvulbchbsawnhdglvbrbuz/oz9cq8u6+ jrlywyejww1vjqxbwbgljyxrpb260+sdtwoc1ylxioapu2tom08oz9cq8u6+yote8sbi9+lw9x7dmqntl0ndwrsewtcs087k/ t9a5pnf3trzu2m1haw66r8r91tdn6rpjoam8l3a+cjxwpiagicdtptpdsbvg9lav1rg1vcewzkjuy9dqtcs5/bpmyofpws28o6zt0rlgsr+ 31s6qtfftw7xevulbchbsawnhdglvbrt6wo3a4lxet723qkgjpc9wpgo8cd48aw1nihnyyz0= "http://www.2cto.com/uploadfile/ Collfiles/20140625/20140625132319103.gif "alt=" \ ">

If your application requires you to go directly to the background state after startup, the corresponding boot process and the slightly different, the main difference is that the above application is going into active, and your application to go into the background, and handle the event, when there is no event processing, will be suspended into the suspended state. As shown in.

One thing to note is that for applications that go directly into the background state from the not running state, the user interface file will still be loaded if the application has an interface when the boot enters the background state, but it will not appear on the application window.
In order to determine in the program whether your program is entering the foreground or background, you can application:didfinishlaunchingwithoptions: The ApplicationState property of the UIApplication class object is detected in the method, and if the application enters foreground, the property value is Uiapplicationstateinactive, and if you enter background, is the Uiapplicationstatebackground.

To detect the sample code:

Uiapplicationstate state = [UIApplication sharedapplication].applicationstate;
Return (state==uiapplicationstateactive "| state==uiapplicationstateinactive);

Note: When an app launches with a URL open, the startup process for this type of app is slightly different from the two charts in three, as follows:

An app with a custom URL pattern must be able to handle all URLs that are passed to it. All URLs are passed to the application's agent for processing, whether the current application is in the startup phase or running running or background in the background. To be able to handle URL requests, your application proxy must implement the following interface methods:

(1) Use the Application:didfinishinglaunchingwithoptions: method to retrieve the URL information, and decide whether you want to open the URL, this method only when the application is started to call.

(2) iOS4.2 or newer version, use method Application:openURL:sourceApplication:annotation: method to open the file.

(3) iOS4.1 or older version, use method Application:handleopenurl: method to open the file.

B. Modifying old items
When the URL request arrives, if your app is not running, it will be started and moved to the foreground to open the URL. Your application:didfinishinglaunchingwithoptions: The method implementation should include the part that retrieves the URL from the Options dictionary option dictionary and determines whether the app can open it. If it can be opened, return Yes to the method Application:openURL:sourceApplication:annotation: or method Application:handleopenurl: To handle the specific URL opening process. For apps that require a URL to open at startup, the boot order is as follows:

When a URL request arrives, if your app is running background or is suspended, it will be moved to the foreground to open the URL. Shortly thereafter, the system will invoke the application proxy's application:openURL:sourceApplication:annotation: method to detect the URL and open it. If your application proxy does not implement this method (or if the current system is iOS4.1 or older), the system will call the application proxy's Application:handleopenurl: method instead. Here is the program execution process that wakes the background or hangs the app to open the URL, as shown in:

Applications that support custom URL patterns can specify different splash screen images between apps before they start and go to work with URLs. For details, see Apple's Official document Iphoneappprogrammingguide.pdf on page 85th, "providing Launch Images for Custom URL schemes".

3.2 Response Interrupt

When a warning-based interrupt (such as a phone call) occurs, the app temporarily switches from the active state to the inactive state to give the system an opportunity to prompt the user and let the user decide what to do with it. The app will remain in the inactive state until the user decides how to handle this interrupt warning.

After the user makes a selection, the current app either goes back to the active state or continues to run, or switches directly to the background state to give way to other applications. In this case, the application execution process is as follows:

In iOS5, notification, specifically the notification that displays the banner mode, does not switch the current active state to the inactive state as in the previous interrupt. The banner of such notifications is placed above the top edge of your application window, so your app is still in active state and continues to receive touch events as before. However, if the user pulls down banner to render the notification hub content, the current app will switch to the inactive state as the warning-based interrupt above. At this point the app will remain in the inactive state until the user processes the banner notification that was pulled, perhaps by simply clearing the notification or launching another application. The corresponding current app either switches back to the active state to continue running or switches to the background state. Users can configure which notifications are displayed in banner form and which are displayed as alert warnings through the Settings app.

The user presses the "Hibernate/Wake" key as a different type of interrupt, which prompts the application to be deactived, when the user presses the "Hibernate/Wake" key, the system can touch the event, deactivate the current application, and lock the screen. For applications that use data protection for encrypting files, lock screen events in addition to the above deactivated applications, there are other processes besides touch events.

What do you do when an outage occurs?

Warning-based interrupts will cause the user to temporarily lose control of the app. The current app continues to run in the foreground foreground but no longer receives any touch events. (In fact, the app simply no longer receives touch class events, other types of events such as accelerometer events, and notification notification, the app still receives.) So in response to these changes, the application needs to do the following work in the Applicationwillresignactive: method:

(1) Stop timers and terminate other recurring tasks.

(2) Stop any running meta-data queries.

(3) No new tasks are initialized.

(4) Pause movie playback (except for playback on airplay)

(5) The game enters a paused state.

(6) Restore OpenGL ES frame rate.

(7) Suspend any distribution queue or operation queue that is being executed in the critical section. (Of course, the app can continue to process network requests and other time-sensitive background tasks while the app is in the inactive state)

When the app recovery switches back to the active state, all the work done in the Applicationwillresignactive: method is resumed when the app is suspended in the Applicationdidbecomeactive: method. Therefore, when the app is reactivated reactivate, the app should restart timers, restore any distribution queue, and restore the OpenGL ES frame rate. However, the game should not automatically resume running and should remain in a paused state until the user resumes them manually.

When the user presses the Hibernate/Wake key, the app with the Nsfileprotectioncomplete protection option that needs to protect the file must close all references to the file. For devices with passwords, lock the screen when the hibernate/Wake key is pressed, and force the system to throw away the decryption key so that full protection can be enabled. When the screen is locked, any attempt to access the corresponding protected file will fail. So if you have such a protected file in your app, you should close all references to these files in the Applicationwillresignactive: method, and in Applicationdidbecomeactive: method to reopen a reference to such a file.

During a call, adjust the UI of your app:

When the user is on the phone and returns to your app to continue the call, the height of the status bar should increase to reflect the fact that the user is calling. Similarly, when a user ends a call, the height of the status bar should be scaled back to normal height. The best way to handle the height change of the status bar is to use view controllers to manage your app views. When the status bar frame size changes, view controllers automatically adjusts all the internal views that they manage.

If your app is not using view controllers for some reason, you should manually respond to the change in the status bar frame size, Specifically, through the registration of Uiapplicationdidchangestatusbarframenotification notification to achieve. The notification handler handler should get the height of the status bar and use that data to moderately adjust the height of the view included in the current app.

3.3 Cutting back background status

When the user presses the "Home" key or the system launches another app, the foreground foreground app first switches to the inactive state and then switches to the background state.

This conversion will cause the applicationwillresignactive: and ApplicationDidenterbackground: Method to invoke the application proxy successively.

After the Applicationdidenterbackground: method returns, most applications are transferred to the suspended state shortly thereafter.

Applications that request specific background background tasks, such as playing music apps, or those that request additional execution time, may continue to perform for a longer period of time.

The specific process is as follows:

Note: The app switching from foreground to background only occurs on devices that support multitasking and that are running iOS4.0 or newer versions of the system. In all other cases, the application is not tangent to the background, but is terminated directly and purged from memory.

What to do when applying a background to the back table:

Applications can do some preparatory work before the Applicationdidenterbackground: Background state, and when tangential to the background state, all applications need to do the following:

(1) Application interface snapshot. When the Applicationdidenterbackground: method returns, the system saves a snapshot of the application interface and uses the snapshot image as the conversion animation. If you have a view that involves sensitive information in your application interface, you should hide or modify the views before Applicationdidenterbackground: method returns.

(2) save user data and app status information . All unsaved changes should be written to disk before being cut to the background state. This step is necessary because your app is likely to be killed quickly in the background for a variety of other reasons. You can perform these operations on background thread background threads, as needed.

(3) Release as many memory resources as possible.

ApplicationDidenterbackground: Method allows up to 5 seconds to complete any task and then return. In practice, this method should be returned as quickly as possible. If this method does not return after the time expires, the app is killed and the memory consumed is cleared.

If your application does require more time to perform a task, you can call Beginbackgroundtaskwithexpirationhandler: The method requests the background execution time, and then starts a thread that can perform the task for a long time.

Whether or not you start a thread that performs a background task, the Applicationdidenterbackground: Method must exit after 5 seconds .

Note: Uiapplicationdidenterbackgroundnotification notifications are also sent so that the app is interested in this notification to know the current applied tangent to the background state. Objects in your app can register for this notification using the default notification hubs.

Depending on the application, there are a lot of other things to do when applying a tangent to the background, such as the active state of the Bonjour service should be paused and the application should stop calling the OpenGL ES function.

Because foreground apps have a higher priority than background apps when they use system resources and hardware.

Apps running in the background should be psychologically prepared for this discrepancy and adjust their access resource behavior when running in the background. In particular, when applying tangential background, it is important to follow the following points:

(1) Do not invoke anything in the app code for OpenGL ES. when the app is running in the background, you can't create a Eaglcontext object or issue any OpenGL es paint commands , and using these calls will cause the app to be killed immediately. The application must also ensure that all commands issued by the previous commit have been executed before they are applied to the background state.

(2) All Bonjour related services are canceled before the app hangs suspended. Applications should unregister Bonjour services and switch off any sockets monitoring associated with the network service when the app is turned back and before it is suspended. Pending applications are not able to respond to these service requests. If your app does not turn off these and Bonjour related services, the system will automatically turn off these services when the app is suspended.

(3) in the network-based sockets application, the connection failure needs to be handled. When your app is suspended for some reason, the system may remove the socket connection. As long as your application handles as many network error situations as possible, such as losing signals, such problems will not cause your application to appear unhealthy. When the app exits resume execution from the background, if you encounter sockets using errors, simply rebuild the socket connection.

(4) Save the application state before cutting to the background state. In the case of low memory alarms, the background app may be cleared out of memory to free up space. applications in the suspended state are prioritized to clear memory and will not be notified before they are purged . Therefore, be sure to save enough application state information for later recovery when the application is in the background state.

(5) When you cut back into the background, release any memory that is no longer needed. If your app maintains a large memory cache object (the image), then cut into the front and release all references to those cached objects.

(6) stop using the system shared resource before it is suspended . Applications that use system-shared resources, such as Address Book or Calendar Data, must stop using these shared resources before they are suspended. Using these resources, the foreground app has a higher priority, and if you find that your app has not stopped using these shared resources after it has been suspended, you should be killed.

(7) avoid updating application windows and views . When the app is in the background, the app window and view are not visible, so you don't need to update it. Although creating and manipulating windows and view objects in the background does not cause the app to be killed, you might consider deferring the work until the app returns to the foreground.

(8) Respond to external attachment connections and loss of connection notifications. For applications that communicate with external attachments, a disconnection notification is sent when the application is tangential to the background state. The app must register this notification and use it to switch off the current attachment access session. When the app returns foreground, a matching notification is sent, giving the app an opportunity to re-establish the session.

(9) When you cut back into the background, clear the resources associated with the behavior warning. In order to save the application context between apps switching, the system does not automatically dismiss action sheets (uiactionsheet) and alert Views (Uialertview) when the app is tangent to the background. By the application Designer to provide a clean solution. For apps running before the iOS4.0 version, action sheets and alerts are still dismiss out when exiting, so that the application's cancellation handler has the opportunity to run.

(10) Remove all sensitive view information when cutting back into the background. Views or windows with sensitive information must be hidden or removed, as described earlier, because the system will snapshot the application interface and generate app toggle animations.

(11) The app performs the least amount of work when running in the background. The system is usually very limited in execution time for applications running in the background and for applications running in the foreground. If the app plays audio in the background or monitors location changes, the app should focus only on this task, and all unnecessary tasks should be deferred. Applications that perform too long in the background will be throttled back by the system or killed directly.

When the application is cleared out of memory due to a system memory alarm, the app calls his agent's Applicationwillterminate: method to perform the final task before the app exits.

Memory usage for background apps:

When an app cuts into background, each app should free as much memory as it actually consumes. The system tries to keep as many applications as possible in memory, but when memory is about to run out, the system terminates applications that suspend suspended to reclaim memory. However, applications that consume a large amount of memory while running in the background background will be terminated first.

To be realistic, it is when your application is no longer needed to remove the references to those used objects as quickly as possible. Removing references allows the automatic reference counting system to release objects and reclaim memory. However, if the app uses caching to improve performance, the app should wait and release the cache before switching to the background state. Here are some examples of objects that need to be recycled:

(1) Cached image objects

(2) relatively large multimedia files or data files that can be reloaded from disk.

(3) Any application that is no longer needed, and which can easily be recreated later.

To help your application reduce its memory footprint, the system automatically frees up many objects behind the scenes to support your application. For example:

(1) Release the backing store of all the core animation layers to prevent these layers from continuing to appear on the screen without changing the properties of the current layer. And does not release the Layer object itself.

(2) Remove all references to cached images. (If the app does not have strong references to these images, then they are then removed from memory)

(3) Release some other data caches that are managed by the system.

3.4 back to front desk foreground

If the app has been moved into the background and the corresponding task is stopped, you can restart the task to resume execution when you return to the foreground. Application Applicationwillenterforeground: The method should restore all the work done in the Applicationdidenterbackground: method. At the same time, the Applicationdidbecomeactive: method should continue to perform the same activation task that was done when the app started. The application process from the background to the foreground is as follows:

Note: If the app is registered with the UIAPPLICATIONWILLENTERFOREGROUDNOTIFICATION notification in the default notification hub, the notification is also available when the app re-enters the foreground.

(1) Processing the notification queue when the application tangent forward station is awakened

The suspended app is always ready to process all notification queues when the foreground or background state is restored. Because the app cannot execute any code while it is suspended, there is no way to handle those and other behaviors or states such as direction changes, time changes, preference changes, and other effects that affect the appearance of the app. To ensure that these changes are not lost, these related notifications are queued and sent to the app as soon as the app resumes foreground or background re-executing the code. To prevent the application from being overwhelmed by too many notifications because of excessive notification, the system merges events and only passes a single notification that responds to a network change since the app was suspended.

The specific notification consolidation rules are shown in the following table:

Most notifications are passed directly to the observers registered for it, but notifications such as directional changes are clearly parsed by the system framework, and such notifications are passed on to the application in a different way.

The notification queue is typically delivered before any touch events and user input to the main running loop of the application main run loops. Most applications should be able to handle these events quickly enough to cause any noticeable lag in application recovery. However, if you find your app looks noticeably sluggish when recovering from the background, you can use instruments to determine whether the notification processing code is running and causing a delay. An app will also receive update notifications for all views that have been marked as dirty since it was updated when it returns to the foreground. Apps running in background background can also call the Setneedsdisplay or Setneedsdisplayinrect: method to request a view update. However, because the interface is not visible at this point, the system merges the requests and updates the view only after the app resumes the foreground.

(2) calmly handle local changes

When the app is in a pending suspended state, if the user changes the current language setting, you can use the NSCURRENTLOCALDIDCHANENOTIFICATION notification to force any local sensitive information (such as date, time, Numbers, and so on) are updated. Of course, the best way to avoid local information-related event handling is to write code that updates the view in such a way that it is easier to update the view. Like what:

A. Use the Autoupdatingcurrentlocal class method to retrieve the Nslocal object. This method returns a local object that responds to local changes and automatically updates itself. So, you don't need to recreate it again. Then, when local information changes, your app still needs to refresh the view that contains the local information.

B. Re-create the cached date or number format object whenever local information changes.

(3) Response to Application settings change

If the app contains settings that are managed by the Settings app, the app should follow nsuserdefaultsdidchangenotification notifications. Because users can modify settings when your app is in the background or suspended, you can use this notification in your app to respond to any important settings changes. In some cases, responding to this notification can help turn off some potential security vulnerabilities. For example, an email program should respond to changes in user account information, and failure to monitor these changes will create some privacy and security concerns. For example, the user is most likely to send a message or use an old user account, even if the account is no longer part of the user, but the user is not the slightest feeling that the new account is used. When the app receives the notification, the app should reload all and set the relevant stuff and reset the user interface appropriately, if necessary. For example, when a password or other security-related information changes, the app should hide any previously displayed information and force the user to enter a new password.

3.5 Application Termination

Although the app is usually cut to the background or suspended, if any of the following conditions occur, the app is terminated and the memory is cleared:

(1) Application dependent on previous version of OS iOS4.0

(2) Applications are deployed on devices running the iOS4.0 version of the operating system

(3) The current device does not support multi-tasking

(4) The application contains uiapplicationexitonsuspend key in the Info.plist file.

If the app will be terminated when it is running in the foreground or in the background, the system will call the app agent's Applicationwillterminate: method so that the app can do whatever recycling is needed before exiting. You can use this method to save user data or app state information for use when the app then restarts the recovery state. The maximum run time for this method is 5 seconds , and expired apps are killed and memory removed.

Note: The Applicationwillterminate: method is not called when the app is currently suspended.

Even if you are developing an app using iOS SDK4 or an updated version of the SDK, you should also consider the case where the app was killed without any notification. Users can use the multitasking UI to kill an app explicitly. In addition, if a memory alarm occurs, the system also removes the app from memory to free up space. There is no notification when an app in the suspended state is terminated. However, if the app is currently running in the background background, the system invokes the Applicationwillterminate: Method of the application proxy when the app is to be terminated. The app is not allowed to request additional background execution time in this method.

3.6 Main running loop main run loop

The application master run loop is responsible for handling all user-related events. The UIApplication object installs the main run loop when the app starts and uses this loop to handle events and handle view-based interface updates. As the name suggests, the main run loop is run in the app's main thread app "s main threads . This ensures that all user events are executed serially in the order in which they are received.

Shows the structure of the main run loop and how user events are causing the application behavior. When the user interacts with the app, the events associated with these interactions are automatically generated by the system and passed to the application via a special port set by Uikit. An event exists as a queue within the application and one is distributed to the application's main run loop to execute. The UIApplication object is the first object to receive an event, and determines how the event needs to be handled. Touch events are typically distributed to the application's main window object, and are eventually distributed to the view on which the touch event occurred. Other event passes may be slightly different from touch event passing through a variety of application objects.

There are many types of events that can be passed in an iOS app. The most common events are listed in the following table:

Most of these event types are passed through the application's main run loop, but some are not. For example: The accelerometer event is passed directly to the application of the specified accelerometer proxy object.

Some events, such as touch, remote control classes, are typically handled by the response object being applied. The response object exists anywhere in the app. (UIApplication objects, view objects, view controller objects, and so on are examples of response objects). Most events target a specific response object, but can also be passed to other response objects (with a response chain), for example: A view that does not handle any event can pass an event to its parent view or to a view controller.

The handling of events that occur on the controls class's view (for example, button, switch, and so on) and the touch event processing that occurs on other types of views is somewhat different. Because there are only a very limited number of interaction behaviors that occur on the object of the control class, these interactions are repackaged into an active message and passed to the appropriate target object. This target-action design pattern makes it very easy to apply a control-type View object to trigger a custom code execution.

Ios_ the life cycle of an application

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.