The life cycle of application execution

Source: Internet
Author: User
Tags uikit

Main function Inquiry

There is a main.m file in the iOS project, it is the entry class of the program, the code is as follows:

#import <UIKit/UIKit.h> #import "AppDelegate.h" int main (int argc, char * argv[]) {    @autoreleasepool {        Return Uiapplicationmain (argc, argv, Nil, Nsstringfromclass ([Appdelegate class]);    }}

The parameter argc and argv are consistent with the standard C language main function, argc (arguments count) represents the number of arguments, and argv (arguments value) is a character-type pointer array.

The default argc is 1, which includes a parameter, which is the full path of the program, and we can add some additional parameters to test it:

P.S. Open the edit form via the Product-scheme-edit Scheme in the Xcode menu bar.

int main (int argc, char * argv[]) {for    (int i=0; i<argc; i++)    {        NSLog (@ "Arg%i:%s", I,argv[i]);    }        @autoreleasepool {        return Uiapplicationmain (argc, argv, Nil, Nsstringfromclass ([Appdelegate class]);    }}

Output Result:

Arg 0:/var/mobile/applications/c12b5c94-cad7-489d-ab8e-13280e7cd886/sample0616.app/sample0616
Arg 1:god
Arg 2:bless
Arg 3:me
Arg 4:new
Arg 5:york

You can see that the parameters are separated by a space. The first parameter is the full path of the program on the real machine.

The main function calls a Uiapplicationmain function, first to look at the prototype of this function:

int Uiapplicationmain (   int argc,   char *argv[],   nsstring *principalclassname,   NSString * Delegateclassname);

The previous two parameters have already been analyzed, with the emphasis being on the last two parameters Principalclassname and delegateclassname:

Principalclassname is the name of the application class that must inherit from the UIApplication class, and the UIApplication class is used by default if Nil,uikit is passed ; Each iOS application contains a UIApplication object that the iOS system uses to monitor the entire application lifecycle through the UIApplication object.

Delegateclassname is the name of the application delegate class, which defaults to the Appdelegate class, which handles life-cycle events and system events for the application.

By calling the main function to create a UIApplication object, the UIApplication object is responsible for listening to the application's life cycle time and handing over the life cycle events to the Appdelegate proxy object.

Life cycle of iOS program running

There are five types of apps:

Not running-does not start the app
Inactive-app runs in the foreground, but does not handle any events
Active-app is running in the foreground and is handling events
Background-app running in the background, still in memory, and executing code
Suspend-app is still in memory, but does not run any code, and if memory is low, it will automatically kill

Icons for changes between the various states of the app:

Start-up phase

There is a start-up phase (Launch time) before an app starts running, and this phase contains two system methods:

-(BOOL) Application: (UIApplication *) application willfinishlaunchingwithoptions: (nsdictionary *) launchOptions{    return YES;} -(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions{    Override point for customization after application launch.    return YES;}

The two methods function almost exactly the same, but the order of execution has successively. The Appdelegate class defaults to the application:didfinishlaunchingwithoptions:, in general, only need to deal with this method.

the parameter launchoptions of the Didfinishlaunchingwithoptions function is an object of type nsdictionary that stores the reason for the program to start.

    • User (click icon) to start the program directly, no data in the launchoptions;
    • Other programs start with the OpenURL: mode, you can get the URL passed through the key Uiapplicationlaunchoptionsurlkey
      Nsurl *url = (Nsurl *) [launchoptions Valueforkey:uiapplicationlaunchoptionsurlkey];

    • Initiated by local notification, the local notification object (Uilocalnotification) can be obtained by key Uiapplicationlaunchoptionslocalnotificationkey
    • Start by remote notification, you can obtain remote notification information by key Uiapplicationlaunchoptionsremotenotificationkey (Nsdictionary)

The possible key values in the program launchoptions can be referenced in the Launch Options keys of uiapplication Class reference.

The return value of the Didfinishlaunchingwithoptions function is a bool type, which determines whether the URL resource is processed and if yes is returned by the Application:openURL:sourceApplication : annotation: method handles URL. If the application has a remote notification to start, the return value is ignored .

P.S. If application:willfinishlaunchingwithoptions is present: and Application:didfinishlaunchingwithoptions:, Then both methods return Yes before the URL resource is processed.

After the start-up phase is over, the program may go into the foreground (foreground) or run in the background (background), and here are the illustrations of the two modes of operation:

Load to foreground:

Loading into the background:

The foreground running is more common, the background run appears in the later iOS version, here does not do very deep research, only provides a background to run the configuration and the test method:

Step 1: set the data acquisition interval in application:didfinishlaunchingwithoptions: and monitor the current program running status

-(BOOL) Application: (UIApplication *) application willfinishlaunchingwithoptions: (nsdictionary *) launchOptions{    [Application setminimumbackgroundfetchinterval:uiapplicationbackgroundfetchintervalminimum];        NSLog (@ "Current state:%d. (%d,%d,%d)", Application.applicationstate,                                         uiapplicationstateactive,                                         Uiapplicationstateinactive,                                         uiapplicationstatebackground);    return YES;}

Step 2: Enable "Background Modes" in the Capabilities tab and tick "Background fetch"

Step 3: implement-application:performfetchwithcompletionhandler in Appdelegate: Thesystem will execute the fetch This method is called when the

-(void) Application: (UIApplication *) application Performfetchwithcompletionhandler: (void (^) ( Uibackgroundfetchresult)) completionhandler{    //do Something ...}

Step 4: Use scheme to change how Xcode runs the program. Product-scheme-manage schemes, and then create or edit a scheme entry:

Step 5: Start Debugging.

Run phase (only consider direct launch to the foreground)

After the start-up phase executes, the program's status is "inactive", and the following method becomes "active" when it goes into the run phase:

-(void) Applicationdidbecomeactive: (uiapplication *) application{    //Restart Any tasks this were paused (or not yet STA rted) While the application was inactive. If the application is previously in the background, optionally refresh the user interface.}

Official comments are translated into Chinese: "When the application is inactive, restart a task that is paused (or not started)." If the program is in the background before, you can refresh the user interface as appropriate. "This method is triggered very frequently, and this method is executed first when the program is started or when the program resumes its foreground state.

Interrupt condition

Here are a few common scenarios where you'll consider outages:

1. Press the home button or double-click the Home button to click the taskbar icon to run other apps
2. Have call notification
3. There is a text message or other app's top notification or push message.

The following detailed analysis of each action, print out the trigger method and Status:

Case 1: When you press the home button function:[applicationwillresignactive], State:[active]function:[applicationdidenterbackground], State:[background]case 2: When double-clicking the Home key and then selecting return current App:function:[applicationwillresignactive], state:[active]function:[ Applicationdidbecomeactive], State:[active]case 3: When you double-click the Home key and select other App:function:[applicationwillresignactive], State:[active]function:[applicationdidenterbackground], State:[background]case 4: When there is a call, refuse to answer: function:[ Applicationwillresignactive], state:[active]function:[applicationdidbecomeactive], state:[Active]case 5: When there is a call, Answer and hang up: function:[applicationwillresignactive], State:[active]function:[applicationdidenterbackground], state:[ Background]function:[applicationwillenterforeground], state:[background]function:[applicationdidbecomeactive], State:[active]case 6: When there are text messages or push messages at the top, click View: function:[applicationwillresignactive], state:[active]function:[ Applicationdidenterbackground], State:[background]

As you can see from the above, the first method to execute is as long as there is an interrupt operation:

-(void) Applicationwillresignactive: (uiapplication *) application{    //Sent when the application was about to move from a Ctive to inactive state. This can occur for certain types of temporary interruptions (such as a incoming phone call or SMS message) or when the US Er quits the application and it begins the transition to the background state.    Use the This method to the pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should with this method to pause the game.}

In general, we should do the following in the Applicationwillresignactive: method:

    • Stop 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 frequency of OpenGL ES
    • Suspend any distributed queue and non-critical operations queue (you can continue to handle network requests or other time-sensitive background tasks)

When the program returns to the active state, you should use the applicationdidbecomeactive: method to re-develop or resume the operation of the pause above, such as restarting the timer, continuing to distribute the queue, and increasing the frequency of OpenGL ES. For the game may go back to a paused state, there is a user click to start again.

If the program is interrupted and enters the background, the method is called:

-(void) Applicationdidenterbackground: (uiapplication *) application{    //Use the method to release shared resources, Save user data, invalidate timers, and store enough application state information to restore your application to its Curre NT State in case it is terminated later.     If your application supports background execution, this method is called instead of Applicationwillterminate:when the User quits.}

The official comments are translated into Chinese: "Use this method to release shared resources, store user data, cancel timers and store sufficient application state information to restore to its current state before termination." If your application supports background operations, it will replace the method Applicationwillterminate: Called when the user leaves the program .

Conditions returned after an interruption

The method is called when the interrupt condition occurs and then returns to the current app:

-(void) Applicationwillenterforeground: (uiapplication *) application{//called as part of the transition from the    BAC Kground to the inactive state; Here's can undo many of the changes made on entering the background.}

Here is a question, when the app from the background back to the foreground, Applicationwillenterforeground: and applicationdidbecomeactive: will be called, what is the difference between the two? My understanding is that Applicationwillenterforeground is called only when the program is returned from the background to the foreground, and applicationdidbecomeactive: except when the foreground is returned from the background. It will also be called when the program is running in the foreground (such as canceling the answer after receiving a call reminder, and then returning to the current app after double-clicking the Home button). So applicationwillenterforeground: It's good to handle initialization that only needs to be done once before loading.

termination phase

The method is called when the program terminates:

-(void) Applicationwillterminate: (uiapplication *) application{    //Called when the application was about to terminate. Save data if appropriate. See also Applicationdidenterbackground:.}

This method is usually used to save data and some cleanup work before exiting, and it is necessary to set the key value of Uiapplicationexitsonsuspend.

The life cycle of application execution

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.