Steps:
1. Add the Uibackgroundmodes key to the Info.plist, and its 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, and the function body is as follows:
#pragma mark - VoIP- (void)setupBackgroundHandler{ if( UIUDeviceIsBackgroundSupported() )
if( [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler: ^ { [selfrequestServerHowManyUnreadMessages]; } ] ) { 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 = [NSDatedateWithTimeIntervalSinceNow:15]; alarm.timeZone = [NSTimeZone defaultTimeZone]; alarm.repeatInterval = 0; alarm.soundName = UILocalNotificationDefaultSoundName; alarm.alertBody = @"Time to request MOA2 Server!"; [app scheduleLocalNotification:alarm]; } } elseif([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 function: The app wakes up once every timeout.
0. To successfully invoke this function, you must set the Uibackgroundmodes key in Info.plist to one of the array values of the VoIP string.
1.timeout must be >=600
2. The time interval for waking up the app is not accurate.
3. Only 10 second execution time after wake-up. That is, the code in handler is executed in the 10-second class. The app is blocked again after 10 seconds.
(You can use the-backgroundtimeremaining property to return the remaining time )
4. After the function is successfully called, it is valid for the program life cycle.
The effect of this function is still valid when returning to the foreground. (so it can be used as a timer to make.)
The 5.clearKeepAliveTimeout function is used to clear the handler.
iOS executes in the background every few times