An explanation of the iOS app lifecycle (front background switch, application status)

Source: Internet
Author: User

The lifecycle of an iOS application, and whether the program is running in the foreground or in the background, transforms the state of the application, which is important to the developer. The resources for iOS systems are limited, and applications are not the same in the foreground and in the background. In the background, the program is subject to many limitations of the system, which can improve battery usage and user experience.

To develop the app, we follow some of Apple's guiding principles, as follows:

1. Status of the application

The status is as follows:

Not running running program does not start

Inactive inactive The program is running in the foreground, but no events are received. In the absence of event handling, the program usually stays in this state

The active activation program runs in the foreground and receives the event. This is also a normal mode of the front desk

Backgroud daemon in the background and can execute code, most programs enter this state will stay in this state for a while. The time will then go into the suspended state (Suspended). Some programs can be in Backgroud state for a long time after special request

The Suspended suspend program cannot execute code in the background. The system automatically turns the program into this state and does not give notice. When suspended, the program is still in memory, when the system memory is low, the system will remove the suspended program, to provide more memory for the foreground program.

is the program state change diagram:

Callback for the agent when each program is running state:

-(BOOL) Application: (UIApplication *) application willfinishlaunchingwithoptions: (nsdictionary *) launchOptions       Tell the agent process to start but not yet into state save-(BOOL) Application: (UIApplication *) Application Didfinishlaunchingwithoptions :(nsdictionary *) launchoptions       Tell the agent to start the basic Completion program ready to start running-(void) Applicationwillresignactive: ( UIApplication *) application     When an application is going into an inactive state, during which time the application does not receive messages or events, such as a call-(void) Applicationdidbecomeactive: (uiapplication *) application        When the application is in the active state, this is exactly the opposite of the method above-(void ) Applicationdidenterbackground: (uiapplication *) application     Called when the program is pushed to the background. So to set the background to continue running, then in this function can be set-(void) Applicationwillenterforeground: (uiapplication *) application when the program from the background will be back to the foreground when the call, This is just the opposite of the method above. -(void) Applicationwillterminate: (uiapplication *) application when the program is about to exit is called, usually to save the data and some cleanup work before exiting. This needs to set the key value of the uiapplicationexitsonsuspend. -(void) applicationdidfinishlaunching: (uiapplication*) application when the program loads and executes

Type NSLog print in the method that corresponds to the above 8 methods.

Now start the program to see the order of execution:

Startup program lifecycle[40428:11303] willfinishlaunchingwithoptions lifecycle[40428:11303] Didfinishlaunchingwithoptions LIFECYCLE[40428:11303] Applicationdidbecomeactive

Press the Home button

LIFECYCLE[40428:11303] applicationwillresignactive lifecycle[40428:11303] Applicationdidenterbackground

Double-click the Home button and then open the program

LIFECYCLE[40428:11303] Applicationwillenterforeground lifecycle[40428:11303] Applicationdidbecomeactive

2. Application life cycle 2.1, loading applications into the foreground

2.2. Loading the application into the background

2.3. About main function

The main function is the entry for program initiation, in the iOS app, the function of the main function is minimized, and its main work is given to the Uikit framework

[CPP]View Plaincopy
    1. #import <UIKit/UIKit.h>
    2. int main (int argc, char *argv[])
    3. {
    4. @autoreleasepool {
    5. return Uiapplicationmain (argc, argv, Nil, Nsstringfromclass ([Myappdelegate class]));
    6. }
    7. }


The Uiapplicationmain function has four parameters, you do not need to change these parameter values, but we also need to understand how these parameters and programs start

The ARGC and argv parameters contain the boot time brought over by the system. The third parameter determines the name of the primary application class, which is specified as nil, so that Uikit uses the default program class UIApplication. The fourth parameter is the program's custom proxy class name, which is responsible for the interaction between the system and the code. It is typically generated automatically when Xcode creates a new project.

In addition, the Uiapplicationmain function loads the file of the program's main interface. Although this function loads the interface file, but does not put it on the application's windows, you need to load it in the delegate Application:willfinishlaunchingwithoptions method.

An application can have either a master storyboard file or a master nib file, but not two exist at the same time.

If the program does not automatically load the main storyboard or nib file at startup, you can prepare the Windows display in the Application:willfinishlaunchingwithoptions method.

3. Response Interrupt 3.1 When an alert-based interrupt occurs, such as when a call comes in, the program temporarily enters the inactive state, which allows the user to choose how to handle the interrupt, such as:

In iOS5, the notification will not turn the program into an active state, the notification is displayed in the status bar, if you pull the status bar, the program will become inactive, put the status bar back, the program back to active.

Press the lock screen key is another kind of interruption of the program, when you press the Lock screen button, the system blocked all touch events, put the app in the background, then the app state is inactive, and into the background.

3.2 What happens to our app when there are interruptions? We should be in the Applicationwillresignactive: method:

    • Stop the timer and other recurring tasks
    • Stop any requests that are running
    • Pause the playback of a video
    • If it's a game, then pause it.
    • Reduce the frame rate of OpenGL ES
    • Suspends any distribution of queues and unimportant operations queues (you can continue to handle network requests or other time-sensitive background tasks).
When the program returns to the active state, applicationDidBecomeActive: The method should start again with the tasks mentioned above, such as restarting the timer, continuing to distribute the queue, and increasing the frame rate of OpenGL es. However, the game will go back to a paused state and not start automatically. 4, go to the background to run 4.1:ps: only in the IOS4 system or support multi-tasking devices to run in the background. Otherwise, the state will be terminated directly. 4.2 What should we write when the application goes backstage?
    • Save user data or status information, all the files or information that are not written to the disk, when entering the background, the last is written to disk, because the program may be killed in the background,
    • Frees as much memory as possible
Applicationdidenterbackgound: The method has about 5 seconds to complete these tasks. If there is an unfinished task over time, your program will be terminated and purged from memory. If you still need to run the task for a long time, you can call the Beginbackgroundtaskwithexpirationhandler method to request the background run time and start the thread to run a long-running task. 4.3 When the application is in the background when memory is used in the background, each application should release the maximum memory. The system strives to keep more applications running at the same time in the background. However, when memory is low, some suspended programs are terminated to reclaim memory, and the most memory programs are terminated first. In fact, if the object that the application should be no longer used, it should remove the strong reference as soon as possible, so that the compiler can reclaim the memory. If you want to cache the performance of some object-boosting programs, you can remove these objects from strong references when you enter the background. The following objects should remove the strong references as soon as possible:
    • Picture Object
    • You can reload the large video or data files
    • Anything that doesn't work and can be easily created
In the background, in order to reduce the memory used by the program, the system will automatically recycle some systems to help you open up the memory. For example: The system recycles the backup storage of the core animation. Remove any system-referenced cached pictures Remove the system Management data cache strong Reference 5, back to the foreground running process: When the app is in a suspended state, it cannot execute any code. Therefore it cannot handle notifications that are sent during the suspension, such as direction changes, time changes, changes to settings, and other notifications that affect the presentation or status of the program. When the program returns to the background or the foreground, the program handles the notifications correctly. 6, the program terminates the program as long as one of the following conditions, as long as the background or suspended status will be terminated: iOS4.0 Previous system app was developed based on iOS4.0 system. Device does not support multitasking in the Info.plist file, the program contains the Uiapplicationexitsonsuspend key. If the app terminates, the system will call the app's proxy method Applicationwillterminate: This will allow you to do some cleanup work. You can save some data or app status. This method also has a 5-second limit. After a timeout, the method returns the program from memory cleanup. Note: Users can close the application manually. 7. The main run loop master runs the cycle, and is responsible for handling user-related events. The UIApplication object launches the main run Loop at program startup, which handles events and updates the view's interface. See main run loop to know that it is running on the main thread of the program. This ensures that events that receive user-related actions are processed sequentially. Main Run Loop handles the event's schema diagram:  User operating devices, related operation events are generated by the system and distributed through the specified port of Uikit. Events are queued internally and distributed to main run loop for processing. The UIApplication object is the first object to receive a time, and it determines how the event is handled. Touch events are distributed to the main window, and the window is then distributed to the view that corresponds to the start touch event. Other events are distributed to other object variables for processing by other means.   Most of the events can be distributed in your app, similar to touch events, remote manipulation events (line-controlled headphones, etc.) are handled by the app's  responder objects  object. Responder objects is everywhere in your app, such as: UIApplication objects. The View object, the View controller object, is Resopnder objects. The target of most events specifies Resopnder object, but events can also be passed to other objects. For example, if the view object does not handle events, it can be passed to the parent view or view controller.   Reference: https://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ Managingyourapplicationsflow/managingyourapplicationsflow.html#//apple_ref/doc/uid/tp40007072-ch4-sw20

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.