Overview of IOS4 multi-task mechanism

Source: Internet
Author: User

By viewing the official documentation, we learned that the backend operating mechanism allows three services to run for a long time in the backend, which are
1. location service
2. Play Music
3. VoIP
Apple has a saying for these three services: "Such applications do not run continuously but are woken up by the system frameworks at appropriate times to perform work related to those services ."
Therefore, they are only promptly awakened by the system. When will it be stopped? For music playback, the "if the application stops playing audio, the system suspends it." system will immediately suspend the audio when it stops playing it. These are not the key points I want to talk about today.

I am talking about another background running mechanism that requires a limited time to complete background tasks (official Article: Finite Length Task ).
Why? This is because someone asked me about multitasking in the jar a few days ago. The example is a third-party alarm clock. after entering the background, can I complete the alarm Task five minutes later. (Because I do not remember which post it is, I will not give a link here. Sorry !)
I have seen a lot of answers to him, all of which explain a problem, that is, after the application enters the background, it is suspended by the system and cannot continue to execute the code.
It may be because I have a problem with my personal understanding. The description is strictly incorrect. Because Apple gave us some time to do what we didn't finish in the background.
Let's take the poster as an example. after entering the background for 5 minutes, a bell will be triggered. From this description alone, there is no problem in implementing this function (Remember, it's only five minutes, you will know why after reading it ).
The implementation method consists of the following steps:
1. send an application to the system to execute background tasks and define the operations to save data and status when the task execution time exceeds the system's limit. Reference an official code, as follows:

UIApplication*    app = [UIApplication sharedApplication];

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];

2. add the tasks you want to execute to the asynchronous task queue of the system in the form of blocks (the official recommendation is asynchronous. I used synchronous to implement the alarm function, see the code package in the attachment ). The official code is as follows:

Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
// Add the task to be completed here
// After the task is completed, use the following code to notify the system that the task has ended. If there are no other tasks, the process can be suspended.
[App endBackgroundTask: bgTask];
BgTask = UIBackgroundTaskInvalid;
});

/********************* Split line for coder ************* ********/

As described above, I believe many people already know how to implement this alarm. However, to carry forward the spirit of sharing, I will talk about my simple implementation here.
0. Describe the dispatch_block_t type. This type is the block type. Literally, it is a program block. Place the code you want to execute between "^ {" and "}", and it becomes a block object (just call it an object ). For example

dispatch_block_t block = ^{
NSLog(@"Hello DevDivers!");
};

1. Define a timer for timing when the program is activated.

2. Define two macros to write those troublesome block structures. Note that I am using a synchronization queue.

#define DoorsBgTaskBegin() { \
UIApplication *app = [UIApplication sharedApplication]; \
UIBackgroundTaskIdentifier task = [app beginBackgroundTaskWithExpirationHandler:^{ \
[app endBackgroundTask:task]; \
/* task = UIBackgroundTaskInvalid; */ \
}]; \
dispatch_block_t block = ^{ \
#define DoorsBgTaskEnd() \
[app endBackgroundTask:task]; \
/* task = UIBackgroundTaskInvalid; */ \
}; \
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block); \
}

3. Start the timer when the program starts. The focus of this article is not on the timer, so I will not describe the timer too much.

4. Create an alarm in applicationDidEnterBackground.
4.1 first, describe the three variables

Static int giAlarmInterval = 5*60; // 5 minutes, alarm Interval
Const int kTimerInterval = 1*60; // 1 minute, Timer Interval
Const int kSysMaxTimePerBgTask = 10*600; // 10 minutes. The maximum time allocated by the current version system for each background task

4.2 run the code

- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
int i = giAlarmInterval / kTimerInterval;
while (i > 0)
{
DoorsBgTaskBegin();
[NSThread sleepForTimeInterval:kTimerInterval];
[self alarmFunc];
DoorsBgTaskEnd();

i--;
}
}

4.3 alarm code. This is relatively simple. Just print a bit of information.

- (void)alarmFunc
{
giAlarmInterval -= kTimerInterval;

if (giAlarmInterval > 0)
{
NSLog(@"%d minutes left!", giAlarmInterval / 60);
}
else
{
NSLog(@"Alarm!Alarm!Alarm!");

if ([alarmTimer isValid])
{
[alarmTimer invalidate];
}
}
}

/********************* Split line for coder ************* ********/

This is basically the case. I just want to give you a hint. If you can gain something, you can play it freely. I hope you can develop applications that use multiple tasks reasonably.

Finally, we recommend that you use Asynchronous queues to split large tasks into many small parts and put them into queues to improve efficiency, if synchronization is used, it may cause you to be wiped out by the system card if you fail to finish the task within 10 minutes.

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.