IOS background running

Source: Internet
Author: User

IOS background running

 

Wenyi

I learned from the apple documentation that a general application can get a certain amount of time to run related tasks when entering the background, that is, it can run a short period of time in the background.
Three other types can be run after,
1. Music
2. location
3. voip

Article 2

Execution in the IOS background is the content described in this article. Most applications will be paused shortly after they enter the background status. In this state, the application does not execute any code and may delete it from the memory at any time. Applications provide specific services. Users can request the backend execution time to provide these services.

Determine whether multithreading is supported

UIDevice * device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
If ([device respondsToSelector: @ selector (isMultitaskingSupported)])
BackgroundSupported = device. multitaskingSupported;
Declare the background task you need

Add the UIBackgroundModes key value to Info. plist. It contains one or more string values, including

Audio: provides sound playing functions in the background, including audio streams and sounds during video playback.

Location: the user's location information can be maintained in the background.

Voip: Use the VOIP function in the background

Each of the preceding values let the system know that your application should be awakened when appropriate. For example, an application that starts playing music and then moves to the background still needs to execute time to fill the audio output buffer. The audio key is added to tell the system framework that the audio needs to be played continuously and the application can be called back at an appropriate interval. If this option is not included in the application, any audio playback stops running after it is moved to the background.

In addition to the key value adding method, IOS also provides two ways for applications to work in the background:

Task completion-the application can apply for additional time from the system to complete the specified Task.

Local communications-applications can schedule time for local communications transfers

Article 3
How to play music in the background

Http://developer.apple.com/library/ios/#qa/qa1668/_index.html



Article 4

If your application needs to run in the background, you can use the following methods:

1. Applications can request a limited amount of time to complete some important tasks.

2. The application can declare that regular background execution time is required to support specific services.

3. Applications can use local generation of user alarms at a specified time to generate notifications of whether the application is running or not.

Address: http://blog.csdn.net/diyagoanyhacker/article/details/7071055

Author: Ma laiqiang

Statement: Part of this article is from the Internet, part is from the official documentation (translation), and part is the author's summary.

Article 5
Background running is mentioned for the first time

Http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html#//apple_ref/doc/uid/TP40009559-SW1

Wen 6

Official background running documentation

Http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW3



Execution in the IOS background is the content described in this article. Most applications will be paused shortly after they enter the background status. In this state, the application does not execute any code and may delete it from the memory at any time. Applications provide specific services. Users can request the backend execution time to provide these services.

Determine whether multithreading is supported

UIDevice * device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
If ([device respondsToSelector: @ selector (isMultitaskingSupported)])
BackgroundSupported = device. multitaskingSupported;
Declare the background task you need

Add the UIBackgroundModes key value to Info. plist. It contains one or more string values, including

Audio: provides sound playing functions in the background, including audio streams and sounds during video playback.

Location: the user's location information can be maintained in the background.

Voip: Use the VOIP function in the background

Each of the preceding values let the system know that your application should be awakened when appropriate. For example, an application that starts playing music and then moves to the background still needs to execute time to fill the audio output buffer. The audio key is added to tell the system framework that the audio needs to be played continuously and the application can be called back at an appropriate interval. If this option is not included in the application, any audio playback stops running after it is moved to the background.

In addition to the key value adding method, IOS also provides two ways for applications to work in the background:

Task completion-the application can apply for additional time from the system to complete the specified Task.

Local communications-applications can schedule time for local communications transfers

Implement long background tasks

Applications can request to run in the background to implement special services. These applications do not run continuously, but are awakened by the system framework at the right time to implement these services.

1. tracking user location: omitted

2. play audio in the background:

Add the audio value in UIBackgroundModes to register the background audio application. This value allows applications to use audible backgrounds, such as music playback or audio stream applications, in the background. This value can also be added to applications that support audio and video functions to ensure continuous streaming.

After the audio value is set, when your application enters the background, the multimedia framework of the system will automatically stop it from being hung up. However, if the application stops playing audio or video, the application will be hung up.

When your application is in the background, you can execute any system audio framework to initialize background audio. Your application should restrict itself in the background so that it can execute work-related code and cannot execute any tasks unrelated to the playback content.

Because multiple applications support audio, the foreground application always allows playing audio, and the background application is also allowed to play some audio content, depending on the settings of the audio session object. Applications should always set their audio session objects and be careful with audio-related notifications and interruptions of other types. For more information, see audio session programming guide.

3. Implement VOIP applications:

A voip program needs a stable network to connect to its related services so that it can receive incoming calls and other related data. The system allows VOIP programs to be hung up and provides components to listen to their sockets, rather than being awakened at any time. Set the VOIP application as follows:

A. Add the VOIP key value in UIBackgroundModes

B. Set an application socket for VOIP

C. Call setKeepAliveTimeout: handler before moving out of the background to create a regular handler. Your application can run this handler to maintain service connections.

D. Set your audio session to handle this switchover.

Meaning:

A. Most VOIP applications require background audio applications to transmit audio. Therefore, you should set both audio and voip keys.

B. To ensure stable connection of applications in the background, you must tag your main communication socket for VOIP. The tagging socket tells the system, it must take over the socket when your application is interrupted. This switch is transparent to your application. When new data reaches the socket, the system will wake up the application and return control of the socket to the application, in this way, the application can process new data.

You only need tags for the voip service socket. This socket is used to receive incoming calls or other related data to maintain the connection of your VOIP service. Based on the received information, this socket determines the next action. For example, if you want to send a local notification to notify the user of an incoming call, you may want to quietly process the data and let the system interrupt the application again.

In IOS, sockets uses a stream or a more advanced structure to set a VOIP socket, you only need to add a special key in the general settings to indicate that this interface is used to connect to the VOIP service. The following table lists the stream interfaces and settings:

Set the stream interface for voip

Interface

Set

NSInputStream and NSOutputStream
For Cocoa streams, use setProperty: forKey: to add

NSStreamNetworkServiceType
Attribute
Stream.
Set the attribute value
NSStreamNetworkServiceTypeVoIP.
NSURLRequest
For URL loading system, use setNetworkServiceType:

Method of your NSMutableURLRequest object to set the network service
Type of the request. The service type shocould be set
NSURLNetworkServiceTypeVoIP.
CFReadStreamRef and CFWriteStreamRef

For Core Foundation streams, use the CFReadStreamSetProperty or
CFWriteStreamSetProperty function to add the kCFStreamNetwork-
ServiceType property to the stream. The value for this property shocould be
Set to kCFStreamNetworkServiceTypeVoIP.
(Note: When setting the socket, you need to set the appropriate service type key in your main signal channel. This key is not required when you set the audio channel)

Because the VOIP application needs to run all the time to ensure that the incoming call is received, if the program exits through a non-zero exit code, the system automatically restarts the application (this exit method can terminate the program when the memory pressure is high ). Even so, interrupting the application will release all the sockets, including the socket used to connect to the voip service. Therefore, when the program runs, it needs to create a socket from scratch.

C. To prevent disconnection, the voip program needs to be awakened regularly to check its services. To achieve this easily, IOS creates a special handle by using the (UIApplication setKeepAliveTimeout: handler :) method. You can create the handle in the applicationDidEnterBackground method. Once created, the system will call the handle at least once before the timeout to wake up your application.

This keep-alive handler is executed in the background and must return parameters as soon as possible. It has a maximum of 30 seconds to execute the required task. If the handle is not returned during this time period, then the system will terminate the application.

After you create a handler, determine the maximum timeout required by the application. The system guarantees that handler will be called before the maximum timeout, but this time is not certain, so your handler must be prepared to execute the program before the timeout you declare.

D. Set the audio session. For details, see the Audio Session Programming Guide.

Complete a limited-length task in the background

At any time before termination, the application calls beginBackgroundTaskWithExpirationHandler: The method allows the system to provide additional time to complete some tasks that need to be executed for a long time in the backend. (The backgroundTimeRemaining attribute of UIApplication contains the total time of running the program)

You can use task completion to ensure that programs that are important but require long running will not be suddenly closed because the user enters the background. For example, you can use this function to save user information to a disk or download an important file from the network. There are two ways to initialize such a task:

1. Use beginBackgroundTaskWithExpirationHandler: And endBackgroundTask: To package important tasks that run for a long time. This protects these tasks from being interrupted when the program suddenly enters the background.

2. When your application delegates applicationDidEnterBackground: The method is called and starts the task again.

The two methods in must correspond One to One. endBackgroundTask: The method tells the system that the task has been completed and the program can be terminated at this time. Because the application only has a limited time to complete background tasks, you must call this method before timeout or the system is about to terminate the program. To avoid termination, you can also provide an expiration handler and endBackgroundTask at the beginning of a task: method. (You can view the backgroundTimeRemaining attribute to determine the remaining time ).

A program can provide multiple tasks at the same time. Whenever you start a task, beginBackgroundTaskWithExpirationHandler: The method returns a unique handler to identify the task. You must pass the same handler in the endBackgroundTask: Method to terminate the task.

Listing 4-2 Starting a background task at quit time
-(Void) applicationDidEnterBackground :( UIApplication *) application
{
UIApplication * app = [UIApplication sharedApplication];
BgTask = [app beginBackgroundTaskWithExpirationHandler: ^ {
[App endBackgroundTask: bgTask];
BgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT,
0), ^ {
// Do the work associated with the task.
[App endBackgroundTask: bgTask];
BgTask = UIBackgroundTaskInvalid;
});
}
In the preceding example, the bgTask variable is a member variable of a class and stores a pointer to the background task id.

In expriation handler, you can add the Code required to close the task. However, the added Code cannot be executed for too long. When the expriation handler is called, the program is very close to being closed, therefore, only a very short time is required to clear the status information and terminate the task.

Arrange Local Notification transmission

The UILocalNotification class provides a way to pass local communications. Unlike push notifications, remote servers must be configured. local communications are arranged in the program and executed on the current device. This capability can be used if the following conditions are met:

1. A time-based program allows the program to post an alert at a specific time in the future, such as an alarm clock.

2. A program running in the background, post a local notification to attract user attention

To arrange the transmission of local notification, you need to create a UILocalNotification instance, set it, and use the UIApplication class method to arrange it. The Local notification object contains the type (sound, alert, or badge) to be passed and the time to be presented ). The UIApplication method provides options to determine whether to transfer immediately or at the specified time.

Listing 4-3 Scheduling an alarm notification
-(Void) scheduleAlarmForDate :( NSDate *) theDate
{
UIApplication * app = [UIApplication sharedApplication];
NSArray * oldNotifications = [app scheduledlocalications ications];
// Clear out the old notification before scheduling a new one.
If ([oldNotifications count]> 0)
[App cancelalllocalconfigurications];
// Create a new notification.
UILocalNotification * alarm = [[UILocalNotification alloc] init] autorelease];
If (alarm)
{
Alarm. fireDate = theDate;
Alarm. timeZone = [NSTimeZone defaultTimeZone];
Alarm. repeatInterval = 0;
Alarm. soundName = @ alarmsound. caf;
Alarm. alertBody = @ Time to wake up !;
[App scheduleLocalNotification: alarm];
}
}
(It can contain up to 128 local communications active at any given time, any of which can be configured to repeat at a specified interval .) if the program is already in the foreground when the notification is called, the application: didReceiveLocalNotification: method will be replaced.

Summary: The detailed description of the content executed on the IOS background is complete. I hope this article will help you!
Wen Qi
IOS is not a real multi-task system. After you press the Home button, all applications enter the background status and most of the applications immediately enter the paused status, all the application's working memory is in RAM, and it is not executed at all when it is paused. Therefore, switching back to such an application is very fast. However, if the system requires more memory for the currently active applications, it is possible to end the paused applications and their memory will be released.

On the one hand, when an application enters the background state, it needs to release some resources to make its pause snapshot smaller, thus reducing the risk of clearing from RAM. On the other hand, to avoid the loss of user data due to termination, you need to save the progress information when the user leaves. These tasks need to be completed within five seconds, otherwise, the system determines that an exception is forced to exit. The processing may be triggered by receiving the notification sent by the application (UIApplicationDidEnterBackgroundNotification). If you add this statement to the processing code, it will inevitably cause an exception to exit:

View plain
[NSThread sleepForTimeInterval: 10];
You can use one method to request more background time to avoid this problem. Assume that the processing method triggered by receiving the notification is applicationDidEnterBackground:
View plain
-(Void) applicationDidEnterBackground {
NSLog (@ % @, NSStringFromSelector (_ cmd ));

// Obtain the UIApplication object of the current application.
UIApplication * app = [UIApplication sharedApplication];

// A background task identifier
UIBackgroundTaskIdentifier taskID;
TaskID = [app beginBackgroundTaskWithExpirationHandler: ^ {
// If the system thinks we have been running for too long, it will execute this block and stop running the application.
[App endBackgroundTask: taskID];
}];
// UIBackgroundTaskInvalid indicates that the system does not provide us with additional information
If (taskID = UIBackgroundTaskInvalid ){
NSLog (@ Failed to start background task !);
Return;
}
NSLog (@ Starting background task with % f seconds remaining, app. backgroundTimeRemaining );
[NSThread sleepForTimeInterval: 10];
NSLog (@ Finishing background task with % f seconds remaining, app. backgroundTimeRemaining );
// Tell the system that we have finished
[App endBackgroundTask: taskID];
}

 

We know that iOS can get a maximum execution time of 600 seconds after enabling background tasks. How do some apps that need to be downloaded in the background or kept connected to the server exceed the limit of 600 seconds? For example, Netease open classes can be continuously downloaded in the background, and Youku also
""
Reader
IOS
We know that iOS can get a maximum execution time of 600 seconds after enabling background tasks. How do some apps that need to be downloaded in the background or kept connected to the server exceed the limit of 600 seconds? For example, Netease open classes can be used for continuous download in the background, and Youku can also continue caching in the background. How does this happen? Generally, to enable iOS to run in the background for a long time, you need to declare VOIP, Audio, or GPS.

Audiosession

The implementation method is very simple, that is, playing a silent music file in the background, which is equivalent to declaring Audio and can easily break through the limit of 600 seconds.

The practice of enabling programs to execute in the background by playing the "silent" sound (that is, using the kAudioUnitRenderAction_OutputIsSilence flag in the audiounit callback function). Although it can indeed implement background execution, there are many restrictions in practice. The biggest problem is that the audiosession of the program cannot be interrupted. When the program is executed in the background, the program will be immediately interrupted as long as another program uses kAudioSessionCategory_RecordAndPlay (such as Skype) or kAudioSessionCategory_SoloAmbientSound (not many sessions are used in the impression.

Interrupt itself is not a problem, but when the playing program is interrupted, only a short period of time can be obtained for processing audiosessioninterruption. My experiment test is about 3 to 5 seconds, but because the program is immediately paused and cannot be mounted to the debugger, it is difficult to accurately estimate, and then the program will be immediately transferred to the sleep state. This time is roughly the same as the time used by the applicationDidEnterBackground callback function, but the interrupt is accompanied by a broadcasting callback action, and the program structure is not very well organized, in many cases, on-site storage is not enough.

It is not recommended to play silent sound. Another problem is that it is very troublesome to Resume playback. For example, when an iOS program is awakened by VOIP in the background, it cannot directly obtain audiounit and start broadcasting again. If you call AudioOutputUnitStart () at this time, an error code is returned, even if no program is running at the front end. At this time, you cannot re-enter the stable running state of the program. Some inexperienced programmers like to use audiosessioninterruptionhandler for automatic playback recovery. However, they do not notice that the callback of audiosessioninterruption status is not guaranteed to be called. Currently, only built-in dialing programs and some special scenarios can be automatically resumed. For example, you can use an MP3 player to interrupt the audiosession and then kill the MP3 player process, then, reset the interrupted program to the front-end ). The result is that you are happy to find that the program is okay, and then you can find various crashes or startup failures from time to time in the production environment.

VOIPsocket

VOIPSocket can be run in the background. When the program enters the background, the entire program is actually suspended, but VOIPsocket is not included in this column because it is controlled by the system. My observation is that every time new data comes to the fore, the program will be awakened and executed for about a few seconds, and then enter sleep again. The statement on Stackoverflow is 10 seconds, but I'm not sure, maybe because my experiment is not accurate enough.

 

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.