IOS background Suspend program after the program is in the background, continue to complete long-running task tasks

Source: Internet
Author: User
Tags terminates

We know that the program's delegate method will be executed after our program has retreated from the foreground to the backstage (the home) key.

This method is executed when the application falls into the background

-(void) Applicationdidenterbackground: (uiapplication *) application

{

}

We already know:

When an IOS app is sent to the background, its main thread is paused. You use the Nsthread detachnewthreadselector:totar get:withobject: The thread created by the class method is also suspended.

Let's assume that there is a situation when our application is sent to the background from the front desk. At this time, our program will execute the delegate method Applicationdidenterbackground. However, at this point, the application only gives us a pitiful little bit of time (that is, the second level) to handle things, and then all the threads are suspended. In practice, we may need more time to complete the necessary operations for our needs:

1. We need to have enough time to save the data to the remote server when the application is pushed to the background.

2. Have enough time to record some required information operations.

What to do?! Because the time we need may be a bit long, by default, iOS doesn't leave us enough time. Tragedy ... There's always a way to solve it ~ ~ ~ apply to iOS, complete a long-running task task in the background

When an IOS app is sent to the background, its main thread is paused. You use the Nsthread detachnewthreadselector:totar get:withobject: The thread created by the class method is also suspended.

If you want to complete a long-term task in the background, you must call UIApplication's Beginbackgroundtaskwithexpirationhandler: instance method to borrow some time from IOS.

By default, if a long-term task is not completed during this period, IOS terminates the program.

What to do? You can use the Beginbackgroundtaskwithexpirationhandler: instance method to borrow some time from IOS.

Since it is time to borrow, there is a need for some conventional ways. Paste the code First: 1. In the project's AppDelegate.h fileDeclare a uibackgroundtaskidentifier, which is equivalent to an IOU. Tell iOS that our program will take more time to complete long-running TaskTask.

@property (nonatomic, unsafe_unretained) Uibackgroundtaskidentifier backgroundtaskidentifier;

@property (nonatomic, strong) Nstimer *mytimer;

2. In the project's APPDELEGATE.M file 1. Note The process of completing the IOU in the Applicationdidenterbackground methodThat is: self. Backgroundtaskidentifier =[application beginbackgroundtaskwithexpirationhandler:^ (void) {

[Self endbackgroundtask];

}];

This method is executed when the application falls into the background

When an IOS app is sent to the background, its main thread is paused. You use the Nsthread detachnewthreadselector:totar get:withobject: The thread created by the class method is also suspended.

If you want to complete a long-term task in the background, you must call UIApplication's Beginbackgroundtaskwithexpirationhandler: instance method to borrow some time from IOS.

By default, if a long-term task is not completed during this period, IOS terminates the program.

What to do? You can use the Beginbackgroundtaskwithexpirationhandler: instance method to borrow some time from IOS.

-(void) Applicationdidenterbackground: (uiapplication *) application

{

Use this method to free up public resources, store user data, stop our defined timers (timers), and store relevant information before the program terminates.

If our application provides a way to execute in the background, this method will replace the execution of the Applicationwillterminate method when the program exits.

Mark a long-running background task to begin

By debugging, it was found that iOS gave us an additional 10 minutes (600s) to perform this task.

Self.backgroundtaskidentifier =[application beginbackgroundtaskwithexpirationhandler:^ (void) {

The block block will be executed when the application leaves the backend at the end of the day (the time the application leaves the background to execute is limited)

We need to do some cleanup work in the sub block blocks.

If the cleanup fails, it will cause the program to hang

Cleanup work needs to be done synchronously in the main thread

[Self endbackgroundtask];

}];

Simulating a long-running Task

Self.mytimer =[nstimer scheduledtimerwithtimeinterval:1.0f

Target:self

Selector: @selector (timermethod:) userinfo:nil

Repeats:yes];

}

2. After completion, to tell iOS, the task completed, submit the completion of the application "good to Borrow good":

[[UIApplication sharedapplication] endBackgroundTask:self.backgroundTaskIdentifier];

Strongself.backgroundtaskidentifier = Uibackgroundtaskinvalid;

}

});

-(void) endbackgroundtask{

dispatch_queue_t mainqueue = Dispatch_get_main_queue ();

Appdelegate *weakself = self;

Dispatch_async (mainqueue, ^ (void) {

Appdelegate *strongself = weakself;

if (strongself! = nil) {

[Strongself.mytimer invalidate];//Stop Timer

For each call to the Beginbackgroundtaskwithexpirationhandler: method, the Endbackgroundtask: method must be called accordingly. So, to tell the application that you've done it.

That is, we need more time for iOS to complete a task, so we have to tell iOS when you can finish that task.

That is to tell the application: "Good to borrow good".

Mark the specified background task complete

[[UIApplication sharedapplication] endBackgroundTask:self.backgroundTaskIdentifier];

Destroying background task identifiers

Strongself.backgroundtaskidentifier = Uibackgroundtaskinvalid;

}

});

}

A long-running Task method for simulation

-(void) Timermethod: (Nstimer *) paramsender{

The Backgroundtimeremaining property contains the time that the program left for us

Nstimeinterval backgroundtimeremaining =[[uiapplication sharedapplication] backgroundtimeremaining];

if (backgroundtimeremaining = = Dbl_max) {

NSLog (@ "Background time Remaining = undetermined");

} else {

NSLog (@ "Background time Remaining =%.02f Seconds", backgroundtimeremaining);

}

}

3. Remember, borrowing and swapping must be paired! The specific explanation, I also wrote in the method, if has the mistake place, also hoped can correct me! Thank you! 4. If the program is completed ahead of time, you can also end it early:

[[UIApplication sharedapplication] endBackgroundTask:self.backgroundTaskIdentifier];

Self.backgroundtaskidentifier = Uibackgroundtaskinvalid;

apply to iOS, unlimited time in the backgroundIt is proven that even when performing long-running task tasks, there is a time limit when the program is transferred to the background. Generally 10 points (600s). How to apply for unlimited time to the program?! Then cheat on the iOS system. Make it feel like your program is still running. Then play an audio file in the background with Avaudioplayer Infinite loop. Hehe, if play a audio file without sound?!! Steps: 1. Add background playback support to the Plish file. Added: Required background modes. and set to: Audio 2. Initialize a avaudioplayer audio and play it without any restrictions.

-(void) viewdidload

{

[Super Viewdidload];

dispatch_queue_t dispatchqueue = dispatch_get_global_queue (dispatch_queue_priority_default, 0);

Dispatch_async (dispatchqueue, ^ (void) {

Nserror *audiosessionerror = nil;

Avaudiosession *audiosession = [Avaudiosession sharedinstance];

if ([Audiosession setcategory:avaudiosessioncategoryplayback Error:&audiosessionerror]) {

NSLog (@ "Successfully set the audio session.");

} else {

NSLog (@ "Could not set the audio session");

}

NSBundle *mainbundle = [NSBundle mainbundle];

NSString *filepath = [Mainbundle pathforresource:@ "Mysong" oftype:@ "MP3"];

NSData *filedata = [NSData Datawithcontentsoffile:filepath];

Nserror *error = nil;

Self.audioplayer = [[Avaudioplayer alloc] Initwithdata:filedata error:&error];

if (self.audioplayer! = nil) {

Self.audioPlayer.delegate = self;

[Self.audioplayer setnumberofloops:-1];

if ([Self.audioplayer preparetoplay] && [Self.audioplayer play]) {

NSLog (@ "successfully started playing ...");

} else {

NSLog (@ "Failed to play.");

}

} else {

}

});

}

IOS background Suspend program after the program is in the background, continue to complete long-running task tasks

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.