iOS4支持後臺運行,程序的事件響應

程序事件:

啓動時事件

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章