IOS background Run Request more time

Source: Internet
Author: User

When the application enters the background, the system will automatically callback the application delegate's Applicationdidenterbackground: method.

The application can complete the preparation that needs to be done before moving to the background in this method, all the applications need to do the following things.

Frees all memory that can be freed.

Save user data or status information, all files or information that are not written to the disk, should be written to the disk before entering the background, because the program may be killed in the background.

Free memory when entering the background

When the program enters the background, in order to ensure the best user experience, it is recommended to release those resources that are large in memory and can be retrieved again-

This is because when the app is in the background, the iOS system takes precedence over those memory-intensive apps. If the app frees up as much memory as it consumes,

Then the app can be stored in the background or longer. From this point of view, you can get a conclusion: the memory consumed when the app is paused is less risky for iOS to completely terminate the app.

If the app does not have an arc mechanism enabled, the program needs to turn the reference count of those resources that need to be freed to 0 when the app enters the background, allowing the system to reclaim those resources.

When the app goes to the foreground, the system needs to re-restore these resources.

If the app has the ARC mechanism enabled, the program will apply nil to the variables that need to be freed when the app enters the background. When the application is transferred to the foreground,

The system needs to re-restore these resources.

"

code

slice

//  Use the default notification hubs to listen to the app's transition to the foreground

//  When applied to the foreground, the uiapplicationwillenterforegroundnotification

//  is sent to the notification hub to fire Enterfore: Method

[[ Nsnotificationcenter Defaultcenter] addobserver:self  selector: @selector: @selector (enterback:) Name: Uiapplicationwillenterforegroundnotification

Object:[uiapplication sharedapplication];

//  Use the default notification hubs to listen to the app's transition to the foreground

The//  app sends uiapplicationdidenterbackgroundnotification to the notification hub when it goes to the foreground

//  thereby firing Enterfore: Method

[[Nsnotificationcenter Defaultcenter] addobserver:self  selector: @selector: @selector (enterback:) Name: Uiapplicationdidenterbackgroundnotification

Object:[uiapplication sharedapplication];

Description

The above program control when the application into the foreground, the View controller Enterfore: method is called, when the application into the background, the controller's Enterback: method is called, the following is the code of the Enterback: method

-(void) Enterback: (nsnotification *) notification

{

NSLog (@ "-enterback-");

Can be rebuilt quickly in the background, and the larger-memory object is set to nil so that the system frees up memory

Bglayer1.contents = nil;

Bglayer2.contents = nil;

EPlaneImage1 = nil;

}

Description

Because the application already has the ARC mechanism enabled, the above method can reclaim the memory used by these pictures and music resources by setting the variables of these pictures and music resources to nil.

When the app goes to the foreground again, the controller's Enterfore: method is called, and the method is responsible for loading the pictures and music resources again. Here is the code for the Enterfore: method.

Code Snippets

-(void) Enterfore: (nsnotification *) notification

{

NSLog (@ "===enterfore===");

Bglayer1.contents = (ID) [Bgimage cgimage];

Bglayer2.contents = (ID) [Bgimage cgimage];

EPlaneImage1 = [UIImage imagenamed:@ "E1"];

}

Description

With the above approach, the program can release most of the memory when the app is in the background, allowing the app to run in a small amount of memory in the background, reducing the risk that the app will be terminated by the iOS system. When the app goes to the foreground, the system will initialize the resources again, ensuring that the iOS app can recover quickly.

Save state when entering background

When an app enters the background, if the program has some state data that is not saved, and the iOS system may terminate the app when memory is tight, it can cause the app to lose these state data.

To keep the app from losing state data, the program can record the app state when the app is in the background, and the Enterback: method of the View controller will be called when the app goes backstage, so add the following code after the method:

Using Nsuserdefaults Storage System credits

[[Nsuserdefaults Standarduserdefaults] setinteger:score forkey:@ "Score"];

The code above simply uses Nsuserdefault to save the program state. If the program needs to save more state data, you can also use the Plist property file or other form to save the program state.

The next step is to restore the program state when the app goes to the foreground, and the Enterfore: method of the View controller will be called when the app is transferred to the foreground, so add the following code after the method:

Use Nsuserdefaults to read points that the system has saved

nsnumber* Scorenumber;

if (Scorenumber = [[Nsuserdefault standarduserdefaults]

objectforkey:@ "Score"]))

{

Score = Scorenumber.integervalue;

}

Ask for more background time

When the app is in the background, do not perform more than 5 seconds in the main thread, and the app may be removed from memory if it takes too much time (i.e. Applicationdidenterbackground: the execution of the method spends too much time) in the background.

If the application is performing a file download or file transfer, and when the app is in the background, if the task has not finished executing, the task will be paused when the app is in the background. Do not force the task to be done directly in the Applicationdidenterbackground: Method- Because this causes the app to take too much time to get into the background, the iOS system may remove the app directly from memory. The correct approach is: to Applicationdidenterbackground: Method for the platform, tell the system to enter the background or more tasks need to be completed, This allows for more background time to be applied to the system. In this way, when our app is in the background, even if the user is using another app, our app can be saved in memory as long as the system is still enough memory, and the iOS system will keep the app running for some time.

To request more background time, follow these steps:

1. Call the UIApplication object's Beginbackgroundtaskwithexpirationhandler: Method request to get more background execution time, the method default request additional 10 minutes of background time. The method needs to pass in a code block as a parameter, and if the request gets a failed background execution time, the code block will be executed. This variable can be used as an identifier for a background task.

2. Call the Dispatch_async () method to submit the specified code block to the background execution.

3. When the background task execution completes, call the UIApplication object's Endbackgroundtask: method to end the background task

For example, the following example application, which requests a background execution time when the system is in the background, then launches a block of code that loops 100 times and simulates a time-consuming download task. This mechanism allows iOS apps to perform longer in the background, as seen from the procedure.

The following is the implementation part of the application's View controller class code

Viewcontroller.m

@implementation Viewcontroller

-(void) viewdidload

{

[Super Viewdidload];

Use the default notification hubs to listen to the app's transition to the background

Uiapplicationdidenterbackgroundnotification is sent to notification hubs when the app is in the background

Thus triggering the Enterback: method

[[Nsnotificationcenter Defaultcenter] Addobserve:self

Selector: @selector (enterback:)

Name:uiapplicationdidenterbackgroundnotification

Object:[uiapplication Sharedapplication]];

}

-(void) Enterback: (nsnotification *) notification

{

UIApplication *app = [UIApplication sharedapplication];

A variable that defines a uibackgroundtaskidentifier type (essentially Nsuinteger)

The variable will be used as the identifier for the background task

__block Uibackgroundtaskidentifier Backtaskid;

Backtaskid = [App beginbackgroundtaskwithexpirationhandler:^

{

NSLog (@ "= = = Not completed within 10 minutes of the additional application = = =");

End a background task

[App Endbackgroundtask:backtaskid];

}];

if (Backtaskid = = uibackgroundtaskinvalid)

{

NSLog (@ "===ios version does not support background run, background task start failure = = =");

Return

}

To commit a block of code to the system's global concurrency queue asynchronously

Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0)

, ^{

NSLog (@ "= = = Additional Application for background task time:%f===")

, app.backgroundtimeremaining);

Other memory cleanup code can also be done here

for (int i = 0; i <; i++)

{

NSLog (@ "Download task completed%d%%", I);//Convert to percent

Pause 10 seconds simulation is performing background download

[Nsthread Sleepfortimeinterval:10];

}

NSLog (@ "= = = remaining background task time:%f===")

, app.backgroundtimeremaining);

End a background task

[App Endbackgroundtask:backtaskid];

});

}

@end

IOS background Run Request more time

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.