iOS 後台運行一段時間(不是地圖,音樂類型APP)

來源:互聯網
上載者:User

iOS 後台運行一段時間(不是地圖,音樂類型APP)

iOS 通常是不能在後台啟動並執行,尤其是使用者點擊鎖屏鍵,APP進入後台,網路立馬斷開等。如何解決這個問題呢?在APP進入後台,APP怎麼爭取一些時間來“善後”。代碼如下:註:需要定義一個屬性UIBackgroundTaskIdentifier _bgTask;該代碼可以自訂後台多長時間自動結束任務。

- (void) timerMethod:(NSTimer *)paramSender{    /*這裡處理後台需要的邏輯,不可太長*/    }- (void)applicationDidEnterBackground:(UIApplication *)application{    UIDevice * device = [UIDevice currentDevice];    if([device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported])    {        self.pushTimer =  [NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES];        //向iOS系統,借用10分鐘(預設就是10分鐘)時間。當調用beginBackgroundTaskWithExpirationHandler: 記得必須調用endBackgroundTask:方法,否則iOS會終止你的程式.        _bgTask = [application beginBackgroundTaskWithExpirationHandler:^                   {                       NSLog(@"後台10分鐘運行完成,APP進程即將被掛起");                       if(_pushTimer!=nil)                       {                           [_pushTimer invalidate];                       }                       [application endBackgroundTask:_bgTask];                       _bgTask = UIBackgroundTaskInvalid;                   }];        //如果想提前結束10分鐘的後台運行,可在下面加邏輯,目前是空轉.        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{            NSInteger remaining = [application backgroundTimeRemaining];            NSLog(@"remain %d S", remaining);            while (remaining > 30 && _bgTask != UIBackgroundTaskInvalid) {                sleep(15);                remaining = [application backgroundTimeRemaining];                NSLog(@"remain %d S", remaining);//iOS 7就只有180秒,但是超過這個時間程式依然可以運行                //                if (remaining<=180) {//如果想提前結束10分鐘的後台運行,開啟這個if                //                [application endBackgroundTask:_bgTask];                //                _bgTask = UIBackgroundTaskInvalid;                //                }            }            NSLog(@"background thread finished");        });    }}

相關文章

聯繫我們

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