iOS4支持后台运行,程序的事件响应

来源:互联网 发布:淘宝有没有投诉电话 编辑:程序博客网 时间:2024/06/05 21:04

程序事件:

启动时事件

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

切换后台(按home键)

- (void)applicationWillResignActive:(UIApplication *)application
- (void)applicationDidEnterBackground:(UIApplication *)application

从后台恢复

- (void)applicationWillEnterForeground:(UIApplication *)application
- (void)applicationDidBecomeActive:(UIApplication *)application

在后台关闭程序:

其实appDelegate中还有一个事件响应函数

- (void)applicationWillTerminate:(UIApplication *)application(该函数在iOS4之前的系统不支持后台任务时,当按home键相当于退出程序,所以按home键会响应)

而到了iOS4之后,按home键等于enterbackground,如果双击home键以后在多任务栏里关闭程序,那么也不会调用到applicationWillTerminate,因为在后台的程序默认是suspend,所以那样关闭,不会执行到该函数。


如果再切换到后台时候,把该程序标记为一个后台程序,那么系统还会分配cpu cycle给改程序,改程序还可以运行一段时间,此时双击home键在多任务栏中关闭程序,就会调用到applicationWillTerminate了。

下面是如何让切换到后台时标记为后台程序的方法:

UIBackgroundTaskIdentifier _bgTask;

- (BOOL)needBackgroundRunning{return YES;}- (void)applicationDidEnterBackground:(UIApplication *)application{    UIDevice* device = [UIDevice currentDevice];BOOL backgroundSupported = NO;if ([device respondsToSelector:@selector(isMultitaskingSupported)]){backgroundSupported = device.multitaskingSupported;}if (backgroundSupported && _bgTask==UIBackgroundTaskInvalid && [self needBackgroundRunning]){    UIApplication*    app = [UIApplication sharedApplication];        _bgTask = [app beginBackgroundTaskWithExpirationHandler:^{NSLog(@"background task %d ExpirationHandler fired remaining time %d.",_bgTask, (int)app.backgroundTimeRemaining);}];// Start the long-running task and return immediately.dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// Do the work associated with the task.NSLog(@"background task %d start time %d.", _bgTask, (int)[app backgroundTimeRemaining]);while (app.applicationState==UIApplicationStateBackground && _bgTask!=UIBackgroundTaskInvalid && [self needBackgroundRunning] && [app backgroundTimeRemaining] > 10) {[NSThread sleepForTimeInterval:1];}            NSLog(@"background task %d finished.", _bgTask);[app endBackgroundTask:_bgTask];_bgTask = UIBackgroundTaskInvalid;            });}    NSLog(@"!Enter Background",nil);    /*     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.     */}

UIBackgroundTaskIdentifier _bgTask;