iOS 後台執行

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   color   os   ar   for   

轉自:http://blog.csdn.net/yujianxiang666/article/details/35996005

當App進入到後台時,可以有一段時間做處理工作。

或者,對於某些服務,可以長時間運行,比如播放音樂。

?

對於長時間啟動並執行任務,需要在Info.plist添加一行,鍵為UIBackgroundModes,值為一個數組,可以包含如下幾個字串:

  • audio
  • location
  • voip
  • newsstand-content
  • external-accessory
  • bluetooth-central

?

然後,在後台就可以做一些事情了


- (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, this method is called instead of applicationWillTerminate: when the user quits.            UIDevice *device = [UIDevicecurrentDevice];      BOOL backgroundSupported = NO;      if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {          backgroundSupported = YES;      }            __blockUIBackgroundTaskIdentifier bgTaskId = [application beginBackgroundTaskWithExpirationHandler:^{          [application endBackgroundTask:bgTaskId];          bgTaskId = UIBackgroundTaskInvalid;      }];            if (backgroundSupported) {          dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{              //          });      }  ?

}?

步驟:

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。

iOS 後台執行

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.