iOS后台多任务研究

在iOS 4.0中,苹果引入了多任务的概念。所谓的多任务,只是“伪”多任务,因为苹果只支持以下几种类型的多任务,除了这几种,其它的应用程序进入后台都是处于休眠状态,直到程序被再次激活。

以下是苹果官方的原文:

iPhone OS 4 delivers seven new multitasking services that allow your apps to perform tasks in the background while preserving battery life and performance. These multitasking services include:
Background audio - Allows your app to play audio continuously. So customers can listen to your app while they surf the web, play games, and more.
Voice over IP - Your VoIP apps can now be even better. Users can now receive VoIP calls and have conversati***** while using another app. Your users can even receive calls when their phones are locked in their pocket.
Background location - Navigation apps can now continue to guide users who are listening to their iPods, or using other apps. iPhone OS 4 also provides a new and battery efficient way to monitor location when users move between cell towers. This is a great way for your social networking apps to keep track of users and their friends' locati*****.
Push notification - Receive alerts from your remote servers even when your app isn't running.
Local notification - Your app can now alert users of scheduled events and alarms in the background, no servers required.
Task finishing - If your app is in mid-task when your customer leaves it, the app can now keep running to finish the task.
Fast app switching - All developers should take advantage of this. This will allow users to leave your app and come right back to where they were when they left - no more having to reload the app

关于background audioBackground locationLocal notificationTask finishing,可以参考以下链接的教程系列,讲解很详细,不再赘述。Push notification需要服务器的配合,也很简单。

http://mobile.tutsplus.com/series/ios-multitasking/

特别要指出的是Task finishing。Task finishing一般在程序进入后台时做一些释放资源的操作。一般在appDelegate的- (void)applicationDidEnterBackground:(UIApplication *)app方法中实现。

- (void)applicationDidEnterBackground:(UIApplication *)app
{
    /*
     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.
     */
    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
		if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
			UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
            
			__block UIBackgroundTaskIdentifier background_task; //Create a task object
            
			background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
                /*
                 当应用程序后台停留的时间为0时,会执行下面的操作(应用程序后台停留的时间为600s,可以通过backgroundTimeRemaining查看)
                 */
				[application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
				background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
                
				//System will be shutting down the app at any point in time now
			}];
            
			// Background tasks require you to use asyncrous tasks
            
			dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
				//Perform your tasks that your application requires
                NSLog(@"time remain:%f", app.backgroundTimeRemaining);
                
				[application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
				background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
			});
		}
	}
}

 具体的使用方法参看官方文档:

beginBackgroundTaskWithExpirationHandler:

Marks the beginning of a new long-running background task.

- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void)) handler
Parameters
handler

A handler to be called shortly before the application’s remaining background time reaches 0. You should use this handler to clean up and mark the end of the background task. Failure to end the task explicitly will result in the termination of the application. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified.

Return Value

A unique identifier for the new background task. You must pass this value to the endBackgroundTask: method to mark the end of this task. This method returns UIBackgroundTaskInvalid if running in the background is not possible.

Discussion

This method lets your application continue to run for a period of time after it transitions to the background. You should call this method at times where leaving a task unfinished might be detrimental to your application’s user experience. For example, your application could call this method to ensure that had enough time to transfer an important file to a remote server or at least attempt to make the transfer and note any errors. You should not use this method simply to keep your application running after it moves to the background.

Each call to this method must be balanced by a matching call to the endBackgroundTask: method. Applications running background tasks have a finite amount of time in which to run them. (You can find out how much time is available using thebackgroundTimeRemaining property.) If you do not call endBackgroundTask: for each task before time expires, the system kills the application. If you provide a block object in the handler parameter, the system calls your handler before time expires to give you a chance to end the task.

You can call this method at any point in your application’s execution. You may also call this method multiple times to mark the beginning of several background tasks that run in parallel. However, each task must be ended separately. You identify a given task using the value returned by this method.

This method can be safely called on a non-main thread.

Availability
  • Available in iOS 4.0 and later.
Declared In
UIApplication.h
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值