IOS background operating mechanism and action

Source: Internet
Author: User
Tags exit in notification center

IOS background operating mechanism and action
When you press the "Home" key or the system starts another application, the foreground application first switches to the Inactive state and then to the Background state. This conversion will result in successively calling the applicationWillResignActive: And applicationDidEnterBackground: Methods of the application proxy.

In applicationDidEnterBackground: After the method is returned, most applications will be transferred to the suincluded status shortly afterwards. Applications that request specific background tasks, such as playing music applications, or those that require additional execution time, may continue to be executed for a longer period of time.

The specific process is shown in:
  


Note: Switching an application from froeground to background only occurs on devices that support multitasking and run iOS4.0 or later versions. In all other cases, the application is terminated directly instead of the backend and cleared from the memory.

What should I do when the application is redirected to the background:

In applicationDidEnterBackground: In the method, make some preparations before the background state is switched to. When the background state is switched to, all applications need to do the following:

(1) Application Interface snapshot. When applicationDidEnterBackground: returns the result, the system saves the snapshot of the application interface and uses the snapshot image as the conversion animation. If you have a view that involves sensitive information in your application interface, you should hide or modify these views before the applicationDidEnterBackground: method returns.

(2) Save User Data and application status information. All unsaved changes should be written to the disk before the background state is switched to save. This step is required because your application may be quickly killed for many other reasons in the background. You can perform these operations in the background thread of the background thread as needed.

(3) release as many memory resources as possible.

ApplicationDidEnterBackground: The method allows up to five seconds to complete any task and then return it. In practice, this method should be returned as quickly as possible. If this method is not returned after expiration, the application is killed and the occupied memory is cleared. If your application needs more time to execute the task, you can call beginBackgroundTaskWithExpirationHandler to request the background execution time of the method, and then start a thread that can execute the task for a long time. Whether or not you start a thread that executes background tasks, applicationDidEnterBackground: The method must exit in 5 seconds.

Note: The UIApplicationDidEnterBackgroundNotification notification will also be sent to let the application know the status of the current application tangent to the background. The objects in your application can use the default notification center to register this notification.

Based on different application scenarios, there are many other things to be done when the application is switched to the background. For example, the active Bonjour service should be suspended, and the application should stop calling the OpenGL ES function.

Because foreground applications always have a higher priority than background applications when using system resources and hardware. Applications running in the background should be prepared for this difference and adjust their resource access behavior when running in the background. In particular, when the application is switched to the background, the following points must be observed:

(1) do not call any OpenGL ES in application code. When an application is running in the background, it cannot create an EAGLContext object or issue any OpenGL ES painting commands. Using these calls will cause the application to be killed immediately. The application must also ensure that all commands previously submitted and issued have been executed before the application is switched to the background state. For details, see "Implementing a Multitasking-aware OpenGL ES Application" in "OpenGL ES Programming Guide for iOS.

(2) cancel all Bonjour-related services before the application suspends the suincluded service. When the application is switched to the background and is suspended, the application should unregister Bonjour service and turn off any sockets listening related to the network service. Pending applications cannot respond to these service requests. If your application does not turn off these Bonjour-related services, the system will automatically turn off these services when the application is suspended.

(3) In network-based sockets applications, you must handle connection failures. When your application is suspended for some reason, the system may remove the socket connection. As long as your application can handle as many network errors as possible, such as losing a signal, such problems will not cause your application to become abnormal. When the application exits from the background and resumes execution, if the sockets usage error occurs, simply re-establish the socket connection.

(4) Save the application status before the background state. When there is a low-memory alarm, background applications may be cleared out of memory to release space. Applications in the sudedded state are preferentially cleared of memory, and no notification is given before being cleared. Therefore, you must save enough application status information before the application enters the background state for future recovery.

(5) When it is switched to the background, all memory that is no longer needed will be released. If your application maintains a large memory cache object (such as image), all references to these cache objects will be released before the background.

(6) Stop using system shared resources before being suspended. Applications that use system shared resources (such as Address Book or Calendar Data) must stop using these shared resources before being suspended. Foreground applications have higher priority to use these resources. If your application has not stopped using these shared resources after being suspended, it should be killed.

(7) avoid updating the application window and view. When an application is in the background, the application window and view are invisible, so you do not need to update it. Although creating and manipulating windows and view objects in the background does not cause the application to be killed, you can postpone the operation until the application returns to the foreground.

(8) respond to external attachment connection and lost connection notifications. For applications that communicate with external attachments, the system sends a disconnection notification when the application switches to the background state. The application must register this notification and use it to disable the access session of the current attachment. When the application returns foreground, a matched notification will be sent, providing the application with the opportunity to re-establish the session.

(9) Clear the resources related to the behavior warning when it is switched to the background. To save the application context between applications, when the application is switched to the backend, the system does not automatically dismiss action sheets (UIActionSheet) and alert views (UIAlertView ). The Application Designer provides a local clearing solution. For applications running before iOS4.0, the action sheet and alerts are still dismiss when exiting, so that the cancellation handler function of the application can be run.

(10) Remove all sensitive view information from the backend. Because the system takes a snapshot of the application interface and generates an application switching animation, the view or window with sensitive information must be hidden or removed.

(11) The minimum amount of work performed by the application in the background. The execution time of applications running on the background by the system is usually very limited compared with that running on the foreground. If the app plays audio in the background or monitors location changes, the app should only focus on this task, and all unnecessary tasks should be postponed. Applications that have been executed in the background for too long will be throttled back by the system or directly killed.

Next, let's take a look:
AppDelegate. h:

///

UIBackgroundTaskIdentifier bgTask;

NSUInteger counter;


AppDelegate. m:

-(Void) backgroundHandler {

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

UIApplication * app = [UIApplicationsharedApplication];

BgTask = [appbeginBackgroundTaskWithExpirationHandler: ^ {

[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: % d", counter ++ );

[[UIApplicationsharedApplication] setApplicationIconBadgeNumber: numbers ++];

Sleep (1 );

}

});

}



-(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.

*/

Printf ("\ n applicationDidEnterBackground \ n ");

//////////////////////////////////////

BOOL backgroundAccepted = [[UIApplicationsharedApplication] setKeepAliveTimeout: 600 handler: ^ {

[SelfbackgroundHandler];

}];

If (backgroundAccepted)

{

NSLog (@ "backgrounding accepted ");

}

[SelfbackgroundHandler];

}



Info. plist:

Required background modes field:

App provides Voice over IP services;


OK, you can see that the background program is running!

Add QQ chat 64874940



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.