IOS在後台每隔一段時間執行一下

來源:互聯網
上載者:User

步驟:

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。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.