Steps:
1. Add the uibackgroundmodes key to info. plist. The value is an array and one of the arrays is a VoIP string:
<Key> uibackgroundmodes </key> <array> <string> VoIP </string> </array>
2. Call the-(void) setupbackgroundhandler function when the program starts. The function body is as follows:
#pragma mark - VoIP- (void)setupBackgroundHandler{ if( UIUDeviceIsBackgroundSupported() ) { if( [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler: ^ { [self requestServerHowManyUnreadMessages]; } ] ) { UDLog(@"Set Background handler successed!"); } else {//failed UDLog(@"Set Background handler failed!"); } } else { UDLog(@"This Deviece is not Background supported."); }}- (void)requestServerHowManyUnreadMessages{ UIApplication* app = [UIApplication sharedApplication]; if([app applicationState] == UIApplicationStateBackground) { NSArray * oldNotifications = [app scheduledLocalNotifications]; if ([oldNotifications count] > 0) [app cancelAllLocalNotifications]; UILocalNotification* alarm = [[[UILocalNotification alloc] init] autorelease]; if (alarm) { alarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:15]; alarm.timeZone = [NSTimeZone defaultTimeZone]; alarm.repeatInterval = 0; alarm.soundName = UILocalNotificationDefaultSoundName; alarm.alertBody = @"Time to request MOA2 Server!"; [app scheduleLocalNotification:alarm]; } } else if([app applicationState] == UIApplicationStateActive) { UIAlertView *alertView = [[[UIAlertView alloc] init] autorelease]; [alertView setTitle:@"alert"]; [alertView setMessage:@"Time to request MOA2 Server!"]; [alertView addButtonWithTitle:NSLocalizedString(@"cancel", nil)]; [alertView setDelegate:nil]; [alertView show]; }}
Explanation:
-(Bool) setkeepalivetimeout :( nstimeinterval) Timeout handler :( void (^) (void) keepalivehandler
Function: the app wakes up every timeout.
0. To successfully call this function, you must set one of the array values of the uibackgroundmodes key in info. plist to a VoIP string.
1. Timeout must be greater than or equal to 600
2. The interval between wake-up apps is inaccurate.
3. Only 10 seconds after waking up. That is, the code in handler is executed in 10 seconds. The app is blocked again 10 seconds later.
(The-backgroundtimeremaining attribute can be used to return the remaining time)
4. The function is valid within the life cycle of the program after it is successfully called.
This function is still effective when you return to the foreground. (So you can use it as a timer .)
5. The clearkeepalivetimeout function is used to clear handler.