码迷,mamicode.com
首页 > 其他好文 > 详细

程序放后台运行

时间:2016-05-12 12:43:10      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

/**
 *  使用block的另一个用处是可以让程序在后台较长久的运行。
    以前,当app被home键退出后,app仅有最多5秒钟的时候做一些保存或清理 
    资源工作。但是应用可以调用UIApplication的beginBackgroundTaskWithExpirationHandler方法,让app最多有10分钟的时间在后台长久运行。这个时间可以用来做清理本地缓存,发送统计数据等工作。
    让程序在后台长久运行示例代码
 
 *
 *  @param application
 *  @param launchOptions <#launchOptions description#>
 *
 *  @return <#return value description#>
 */

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    

    // Override point for customization after application launch.
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    [self beingBackgroundUpdateTask];
    
    // 在这里加上需要长久运行的代码
    [self endBackgroundUpdateTask];


}

- (void)beingBackgroundUpdateTask {
    
    self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask {
    
    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
    self.backgroundTask = UIBackgroundTaskInvalid;
}

- (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)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.
}

- (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

程序放后台运行

标签:

原文地址:http://blog.csdn.net/u012701023/article/details/51366256

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!