【代碼筆記】後臺運行,可以選擇在前臺或後臺或前後臺

来源:http://www.cnblogs.com/yang-guang-girl/archive/2016/03/18/5290732.html
-Advertisement-
Play Games

一,工程圖。 二,代碼。 AppDelegate.h AppDelegate.m RootViewController.h RootViewController.m


一,工程圖。

二,代碼。

AppDelegate.h

AppDelegate.m

RootViewController.h

複製代碼
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (nonatomic, strong) NSTimer *myTimer;

@end
複製代碼

 

RootViewController.m

複製代碼
#import "AppDelegate.h"
#import "RootViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    RootViewController *rootVC=[[RootViewController alloc]init];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:rootVC];
    self.window.rootViewController=nav;
    
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
    
    // 使用這個方法來釋放公共的資源、存儲用戶數據、停止我們定義的定時器(timers)、並且存儲在程式終止前的相關信息。
    // 如果,我們的應用程式提供了後臺執行的方法,那麼,在程式退出時,這個方法將代替applicationWillTerminate方法的執行。
    
    
    // 標記一個長時間運行的後臺任務將開始
    // 通過調試,發現,iOS給了我們額外的10分鐘(600s)來執行這個任務。
    self.backgroundTaskIdentifier =[application beginBackgroundTaskWithExpirationHandler:^(void) {
        
        // 當應用程式留給後臺的時間快要到結束時(應用程式留給後臺執行的時間是有限的), 這個Block塊將被執行
        // 我們需要在次Block塊中執行一些清理工作。
        // 如果清理工作失敗了,那麼將導致程式掛掉
        
        // 清理工作需要在主線程中用同步的方式來進行
        [self endBackgroundTask];
    }];
    
    // 模擬一個Long-Running Task
    self.myTimer =[NSTimer scheduledTimerWithTimeInterval:1.0f
                                                   target:self
                                                 selector:@selector(timerMethod:)     userInfo:nil
                                                  repeats:YES];
    

}

- (void) endBackgroundTask{
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    AppDelegate *weakSelf = self;
    dispatch_async(mainQueue, ^(void) {
        
        AppDelegate *strongSelf = weakSelf;
        if (strongSelf != nil){
            [strongSelf.myTimer invalidate];// 停止定時器
            
            // 每個對 beginBackgroundTaskWithExpirationHandler:方法的調用,必須要相應的調用 endBackgroundTask:方法。這樣,來告訴應用程式你已經執行完成了。
            // 也就是說,我們向 iOS 要更多時間來完成一個任務,那麼我們必須告訴 iOS 你什麼時候能完成那個任務。
            // 也就是要告訴應用程式:“好借好還”嘛。
            // 標記指定的後臺任務完成
            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
            // 銷毀後臺任務標識符
            strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
        }
    });
}

// 模擬的一個 Long-Running Task 方法
- (void) timerMethod:(NSTimer *)paramSender{
    // backgroundTimeRemaining 屬性包含了程式留給的我們的時間
    NSTimeInterval backgroundTimeRemaining =[[UIApplication sharedApplication] backgroundTimeRemaining];
    
    if (backgroundTimeRemaining == DBL_MAX){
        //前臺列印
        NSLog(@"Background Time Remaining = Undetermined");
    } else {
        //後臺列印
        NSLog(@"Background Time Remaining = %.02f Seconds", backgroundTimeRemaining);
    }
}


- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    //添加此段代碼,則在前臺就不運行了。否則會前後臺一起運行。除第一次啟動的時候,是前臺不運行,退出後臺時候運行。
    
    if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){
        [self endBackgroundTask];
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
複製代碼

 

 

   
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • html垂直居中
  • 用原生js寫了一個超級簡單的日曆。當做是練習js中的Date類型。 思路: html css js 效果圖:
  • DIV顯示內容有時會超長,並把頁面撐的很難看, 以前的做法是在JS中,或者後臺判斷其長度,過長就截斷, 但由於中英文數字展示的寬度並不一樣,截斷的長度也就只能取最小值, 展示的效果也不好。利用CSS提供的方法,可以完美的解決該問題。 這裡寬度是必須定義的,
  • canvas 元素使用 JavaScript 在網頁上繪製圖像,本身是沒有繪圖能力。 canvas 是一個矩形區域,可以控制其每一像素。 canvas 擁有多種繪製路徑、矩形、圓形、字元以及添加圖像的方法。 下麵來做幾個示例: 1、填充畫布 <canvas id="myCanvas" width="
  • Direction: up, down, left, right scrollamount:滾動速度,單位像素 loop: -1無限迴圈
  • 環境描述 前端:jsp 後端:SpringMVC Controller 儘管jsp頁面已設置了pageEncoding: 然後在控制器中,讀取到的對應參數如果含有中文,則出現亂碼,例如: public ModelAndView search(@RequestParam("keyword") Stri...
  • 基於 Material Design 的 BiliBili 第三方 Android 客戶端,我們知道這個APP目前比較流行,所以大家也比較喜歡模仿,需要的參考一下 文檔共用 : https://drive.google.com/folderview?id=0B5Izr6QMl6WhflNwY3MyZ
  • 高仿餓了麽界面效果,動畫效果還是不錯滴,分享給大家一下。 源碼下載:http://code.662p.com/list/11_1.html <ignore_js_op> 詳細說明:http://android.662p.com/thread-6472-1-1.html
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...