步驟:
1.在info.plist里加入UIBackgroundModes鍵,其值為數組,數組之一為voip字符串:
<key>UIBackgroundModes</key><array><string>voip</string></array>
2.在程序啟動的時候調用- (void)setupBackgroundHandler函數,函數體如下:
#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]; } }
解說:
- (BOOL)setKeepAliveTimeout:(NSTimeInterval)timeout handler:(void (^)(void))keepAliveHandler
函數功能:app每隔timeout喚醒一次。
0.要成功調用該函數,就必須在Info.plist里設UIBackgroundModes鍵的array值之一voip字符串.
1.timeout必須>=600
2.喚醒app的時間間隔是不精准的。
3.喚醒后只有10秒執行時間。即handler里的代碼要在10秒類執行完。10秒后app再次被阻塞。
(可以用-backgroundTimeRemaining屬性來返回剩余時間)
4.該函數成功調用后,在程序生命周期內有效。
該函數的效果在回到前台的狀況下,依然有效。(因此可以把它當timer使.)
5.clearKeepAliveTimeout函數用來清除handler。