Unlimited operation in IOS background

Source: Internet
Author: User
Tags call back

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. Add the audio key to tell the system framework to continue playing the audio and call back the application at an appropriate interval. If this item 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.

The following is an article by instructor kmyhy.

According to the background execution description in the Apple documentation, any app has a background task execution time of about 10 minutes. After 10 minutes, the app will be forcibly suspended by IOS.

However, five types of apps allow "unlimited" background running time:

1. audio.

2. Location/GPS.

3. VoIP.

4. newsstand.

5. exernal accessory.

You can declare any app as the above five types for unlimited background running time. However, when you submit an app to the App Store, Apple will review your app, once you find that you have "abused" the background API, your app will be rejected.

Of course, for enterprise development, there is no "Abuse" problem-enterprise apps can be deployed through Ota, without being reviewed by the Apple store.

In enterprise deployment, you can declare an app as VoIP, but this program has nothing to do with VoIP. Our goal is to allow Ios to give us unlimited background execution permissions. The Declaration process is to add the following key to the info. plist file of the APP:

<Key> uibackgroundmodes </key>

<Array>

<String> VoIP </string>

</Array>

I tested the following code:

-(Void) backgroundhandler {

Nslog (@ "### --> backgroundinghandler ");

Uiapplication * APP = [uiapplicationsharedapplication];

Bgtask = [App beginbackgroundtaskwithexpirationhandler: ^ {

[App endbackgroundtask: bgtask];

Bgtask = uibackgroundtaskinvalid;

}];

// Start the long-running task

Dispatch_async (dispatch_get_global_queue (dispatch_queue_priority_default,
0), ^ {

While (1 ){

Nslog (@ "counter: % lD", counter ++ );

Sleep (1 );

}

});

}

-(Void) applicationdidenterbackground :( uiapplication *) Application

{

Bool backgroundaccepted = [[uiapplicationsharedapplication] setkeepalivetimeout: 600 handler: ^ {
[Selfbackgroundhandler];}];

If (backgroundaccepted)

{

Nslog (@ "Backgrounding accepted ");

}

[Selfbackgroundhandler];

}


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.