Wen Yi
I learned from the Apple documentation that the general application can get a certain amount of time to run the task in the background, that is, it can run in the background for a short period of time.
There are also three kinds of types that can be run at the rear,
1. Music
2.location
3.voip
Wen ER
In iOS background execution is what this article describes, and most applications go into a paused state shortly after entering the background state. In this state, the application does not execute any code, and it is possible to remove it from memory at any time. Applications provide specific services, and users can request a background execution time to provide these services.
Determine if multithreading is supported
uidevice* device = [Uidevice currentdevice];
BOOL backgroundsupported = NO;
if ([Device respondstoselector: @selector (ismultitaskingsupported)])
backgroundsupported = device.multitaskingsupported;
Declare the background tasks you need
Info.plist adds a Uibackgroundmodes key value that contains one or more string values, including
Audio: Provides sound playback functionality in the background, including audio streaming and sound when playing video
Location: In the background you can keep the user's position information
VoIP: Use VoIP features in the background
Each of the preceding value lets the system know that your application should be awakened at the appropriate time. For example, an application that starts playing music and then moves to the background still requires execution time to fill the audio output buffer. Adding the audio key is used to tell the system frame that it needs to resume playback and can callback the application at the appropriate time interval, and if the application does not include this, any audio playback will stop running after moving to the background.
In addition to the method of adding key values, iOS provides two ways to make your application work in the background:
The task completion-application can request additional time from the system to complete a given task
Local notifications-application can schedule time to perform local notifications delivery
Bunza
How to let the program play music in the background
http://developer.apple.com/library/ios/#qa/qa1668/_index.html
Wen Si
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 accomplish some important tasks.
2. An application can declare a recurring background execution time to support a particular service.
3. An application can use locally generated alerts for the user at a specified time, whether the application is running or not.
Original address: http://blog.csdn.net/diyagoanyhacker/article/details/7071055
Zhuo to Strong
Disclaimer: Part of this article comes from the Web, part of the official document (translation), and part of the author's summary
Wen Wu
Background run was mentioned for the first time
http://developer.apple.com/library/ios/#releasenotes/general/whatsnewiniphoneos/articles/iphoneos4.html#// Apple_ref/doc/uid/tp40009559-sw1
Wen Liu
Run official documents in the background
http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ Managingyourapplicationsflow/managingyourapplicationsflow.html#//apple_ref/doc/uid/tp40007072-ch4-sw3
In iOS background execution is what this article describes, and most applications go into a paused state shortly after entering the background state. In this state, the application does not execute any code, and it is possible to remove it from memory at any time. Applications provide specific services, and users can request a background execution time to provide these services.
Determine if multithreading is supported
uidevice* device = [Uidevice currentdevice];
BOOL backgroundsupported = NO;
if ([Device respondstoselector: @selector (ismultitaskingsupported)])
backgroundsupported = device.multitaskingsupported;
Declare the background tasks you need
Info.plist adds a Uibackgroundmodes key value that contains one or more string values, including
Audio: Provides sound playback functionality in the background, including audio streaming and sound when playing video
Location: In the background you can keep the user's position information
VoIP: Use VoIP features in the background
Each of the preceding value lets the system know that your application should be awakened at the appropriate time. For example, an application that starts playing music and then moves to the background still requires execution time to fill the audio output buffer. Adding the audio key is used to tell the system frame that it needs to resume playback and can callback the application at the appropriate time interval, and if the application does not include this, any audio playback will stop running after moving to the background.
In addition to the method of adding key values, iOS provides two ways to make your application work in the background:
The task completion-application can request additional time from the system to complete a given task
Local notifications-application can schedule time to perform local notifications delivery
Implement long-time 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: slightly
2. Play audio in the background:
Add the audio value in Uibackgroundmodes to register the background audio app. This value allows the application to use a listening background, such as music playback or audio streaming applications, in the background. For applications that support audio and video capabilities, you can also add this value to ensure that you can continue running the flow continuously.
When the audio value is set, when your application enters the background, the system's multimedia frame automatically prevents it from being hung up, but if the application stops playing audio or video, the system hangs up the application.
When your application is in the background, you can perform arbitrary system audio frames to initialize the background audio. Your application should restrict itself in the background so that it executes work-related code and cannot perform any tasks unrelated to the content being played.
Because there are multiple applications that support audio, the foreground application always allows audio playback, and the background application is allowed to play some audio content, depending on the setting of the audio Session object. Applications should always set their audio session object and handle other types of audio-related notifications and interrupts with care. See Audio Session Programming Guide.
3. Implement VoIP Applications:
VoIP programs require a stable network to connect to and its associated services so that it can receive incoming calls and other related data. The system allows VoIP programs to hang up and provide components to listen for their sockets, rather than waking up at any time. Set up the VoIP application as follows:
A, add the VoIP key value in the Uibackgroundmodes
B. Set up an application socket for VoIP
C, before moving out of the background, call Setkeepalivetimeout:handler: method to establish a regular execution of the handler, your application can run this handler to maintain the service connection.
D. Set your audio session to handle this switch
Interpretation:
A, most VoIP applications need to set up a background audio app to deliver audio, so you should set audio and VoIP two key values.
B, in order for the application to maintain a stable connection in the background, you must tag your main communication socket specifically applied to the voip,tagging socket to tell the system that it must take over the socket when your application is interrupted. The switch itself is transparent to your application, and when the new data arrives at the socket, the system wakes up the application and returns control of the socket to the application so that the application can process the new data.
You only need to tag the socket for the VoIP service, which is used to receive incoming calls or other related data to keep your VoIP service connected. According to the information received, the socket will decide what to do next. such as a call, you will want to pop up a local notification to inform the user, for other less critical data, you may want to quietly process the data and let the system to re-interrupt the application.
In iOS, sockets is a stream or more advanced structure, set up a VoIP socket, you just need to add a special key in the usual settings to indicate that this interface is used to connect to the VoIP service, the following table lists the interface and settings of the stream:
Set up a stream interface for VoIP
Interface
Set up
Nsinputstream and Nsoutputstream
For Cocoa streams, use the Setproperty:forkey: method to add
Nsstreamnetworkservicetype
property to
Stream.
The value of the Change property is set to
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 should is set to
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 should is
Set to Kcfstreamnetworkservicetypevoip.
(Note: When setting up a socket, you need to set the appropriate service type key in your main signal channel.) When setting the channel, you do not need to set this key)
Because VoIP applications need to run continuously to ensure that incoming calls are received, if the program exits with a nonzero exit code, the system will automatically restart the application (this exit can occur when the memory pressure is high to terminate the program). However, the interrupt application will release all sockets, including the socket used to connect to the VoIP service. Therefore, when the program runs, it needs to create the socket from scratch.
C, in order to prevent disconnection, VoIP programs need to be periodically awakened to check its services. To make this behavior easier, iOS creates a special handle by using the (UIApplication Setkeepalivetimeout:handler:) method. You can create the handle in the Applicationdidenterbackground method. Once established, the system will invoke the handle at least once before timing out to wake up your application.
This keep-alive handler is executed in the background and must be returned as soon as possible, it has a maximum of 30 seconds to perform the required task, and if the handle is not returned during this time, the system terminates the application.
When you have established handler, determine the maximum time-out required for the application. The system guarantees that handler will be called before the maximum time-out, but this time is indeterminate, so your handler must be ready to execute the program before you declare the timeout.
D, set audio session, see Audio Session Programming Guide.
Complete a limited-length task in the background
At any time before being terminated, the application calls the Beginbackgroundtaskwithexpirationhandler: method to give the system an extra time to complete tasks that need to be performed in the background for a long time. (The Backgroundtimeremaining property of UIApplication contains the total time that the program runs)
You can use task completion to ensure that programs that are more important but that need to run for a long time do not suddenly close because the user is in the background. For example, you can use this feature to save a user's information to disk or to download an important file from the Web. There are two ways to initialize such a task:
1, the long-running important task with Beginbackgroundtaskwithexpirationhandler: and Endbackgroundtask: Packaging. This protects these tasks from interruption when the program is suddenly cut into the background.
2. When your application delegates Applicationdidenterbackground: The method is called and then the task is started
The two methods must be one by one corresponding, Endbackgroundtask: The method tells the system that the task has been completed and the program can be terminated at this time. Since the application has only a limited amount of time to complete the background task, you must call this method before the timeout or the system will terminate the program. To avoid being terminated, you can also provide a expiration handler and Endbackgroundtask at the beginning of a task: method. (You can view the Backgroundtimeremaining property to determine how much time is left).
A program can provide multiple tasks at the same time, whenever you start a task, Beginbackgroundtaskwithexpirationhandler: The method will return 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), ^{
The work associated with the task.
[App Endbackgroundtask:bgtask];
Bgtask = Uibackgroundtaskinvalid;
});
}
In the example above, the Bgtask variable is a member variable of a class that stores a pointer to the background task indicator.
In Expriation handler, you can add the code that is required to close a task. However, the added code cannot take too long, and when Expriation handler is called, the program is very close to being closed, so there is only a very short time to clear the state information and terminate the task.
Arranging the delivery of local notification
The Uilocalnotification class provides a way to pass the local notifications. Unlike push notifications, where remote server needs to be set up, local notifications is scheduled and executed on the current device in the program. The ability can be used to meet the following conditions:
1, a time-based program, you can at a certain time in the future to the program post an alert, such as alarm clock
2, a program running in the background, post a local notification to attract the user's attention
In order to arrange the delivery of the local notification, you need to create an instance of Uilocalnotification and set it up, using the UIApplication class method to arrange it. The Local notification object contains the type to be passed (Sound,alert, or badge) and when the time is rendered. The UIApplication class method provides the option to determine whether to pass immediately or at a specified time.
Listing 4-3 scheduling an alarm notification
-(void) Schedulealarmfordate: (nsdate*) thedate
{
uiapplication* app = [UIApplication sharedapplication];
nsarray* oldnotifications = [app scheduledlocalnotifications];
Clear out the old notification before scheduling a new one.
if ([oldnotifications count] > 0)
[App Cancelalllocalnotifications];
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];
}
}
(Can contain up to 128 local notifications active in any given time, any of the which can be configured to repeat at a specified interval .) If the program is already in the foreground when calling the notification, then Application:didreceivelocalnotification: The method will be replaced.
Summary: About the details in the iOS backstage implementation of the content is finished, I hope this article has helped you!
Wen VII
iOS is not a real multitasking system, and when the user presses the home button, all applications go into the background state, and most of them quickly go into a paused state, and all of the application's working memory is in RAM and it is not executed at all when paused. Therefore, switching back to such an application is very fast. However, if the system needs more memory for the currently active application, it is possible to terminate the suspended state of the application, and their memory will be freed.
On the one hand, when an application enters the background state, it needs to release some resources to make its own pause snapshot smaller, thereby reducing the risk of removal from RAM, on the other hand, in order to avoid being terminated and lose the user's data, need to save their progress information when the user leaves, the work needs to be completed within 5 seconds, Otherwise, the system will be determined that an exception is forced to quit. Processing can be triggered by a notification sent by the receiving application (uiapplicationdidenterbackgroundnotification), which would inevitably cause an exception to exit if the following statement is added to the processing code:
View Plain
[Nsthread Sleepfortimeinterval:10];
You can avoid this problem by requesting more background time in one way. Assume that the processing method triggered by receiving a notification is applicationdidenterbackground:
View Plain
-(void) applicationdidenterbackground{
NSLog (@ "%@", Nsstringfromselector (_cmd));
Get the UIApplication object for the current application
UIApplication *app = [UIApplication sharedapplication];
A background task identifier
Uibackgroundtaskidentifier TaskID;
TaskID = [App beginbackgroundtaskwithexpirationhandler:^{
If the system thinks we're still running too long, it will execute this block and stop running the application
[App Endbackgroundtask:taskid];
}];
Uibackgroundtaskinvalid said the system did not provide us with extra time
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 we're done.
[App Endbackgroundtask:taskid];
}
iOS program background run settings (not too understanding)