您的位置:首页 > 移动开发 > IOS开发

ios-multitasking-应用转入后台时,如何继续后台运行任务

2014-04-13 23:18 411 查看
启动后台运行任务时,调用UIApplication的实例方法beginBackgroundTaskWithExpirationHandler:
任务完成后,调用UIApplication实例方法endBackgroundTask:

//AppDelegate.h
02
03	#import <UIKit/UIKit.h>
04
05	@interface AppDelegate : UIResponder <UIApplicationDelegate>
06
07	@property (strong, nonatomic) UIWindow *window;
08
09	@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundIdentifier;
10
11	@property (nonatomic, strong) NSTimer *myTimer;
12
13	<a href="http://my.oschina.net/u/567204" class="referer" target="_blank">@end</a>

view source
print?
01	//  AppDelegate.m
02	//  test
03	//
04
05	#import "AppDelegate.h"
06
07	@implementation AppDelegate
08
09	@synthesize window;
10	@synthesize backgroundIdentifier;
11	@synthesize myTimer;
12
13	- (BOOL)isMultitaskingSupported
14	{
15	    BOOL result = NO;
16	    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
17	        result = [[UIDevice currentDevice] isMultitaskingSupported];
18	    }
19	    return result;
20	}
21
22	- (void)timerMethod:(NSTimer *)paramSender{
23	    //获取后台任务可执行时间,单位秒,若应用未能在此时间内完成任务,则应用将被终止
24	    NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];
25
26	    //应用处于前台时,backgroundTimeRemaining值weiDBL_MAX
27	    if (backgroundTimeRemaining == DBL_MAX) {
28	        NSLog(@"Background time remaining = Undetermined");
29	    } else {
30	        NSLog(@"Background time remaining = %.02f seconds", backgroundTimeRemaining);
31	    }
32	}
33
34	- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
35	{
36	    if ([self isMultitaskingSupported]) {
37	        NSLog(@"Multitasking is supported.");
38	    } else {
39	        NSLog(@"Multitasking is not supported.");
40	    }
41
42	    return YES;
43	}
44
45	- (void)applicationWillResignActive:(UIApplication *)application
46	{
47	    // 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.
48	    // 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.
49	}
50
51	- (void)applicationDidEnterBackground:(UIApplication *)application
52	{
53	    if ([self isMultitaskingSupported] == NO){
54	        return; }
55	    self.myTimer =
56	    [NSTimer scheduledTimerWithTimeInterval:1.0f
57	                                     target:self
58	                                   selector:@selector(timerMethod:) userInfo:nil
59	                                    repeats:YES];
60	    self.backgroundIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {
61	        [self endBackgroundTask];
62	    }];
63	}
64
65	- (void) endBackgroundTask{
66	    dispatch_queue_t mainQueue = dispatch_get_main_queue();
67	    __weak AppDelegate *weakSelf = self;
68	    dispatch_async(mainQueue, ^(void) {
69	        AppDelegate *strongSelf = weakSelf;
70	        if (strongSelf != nil){
71	            [strongSelf.myTimer invalidate];
72	            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundIdentifier];
73	            strongSelf.backgroundIdentifier = UIBackgroundTaskInvalid;
74	        }
75	    });
76	}
77
78	- (void)applicationWillEnterForeground:(UIApplication *)application
79	{
80	    // 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.
81	}
82
83	- (void)applicationDidBecomeActive:(UIApplication *)application
84	{
85	    // 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.
86	}
87
88	- (void)applicationWillTerminate:(UIApplication *)application
89	{
90	    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
91	}
92
93	<a href="http://my.oschina.net/u/567204" class="referer" target="_blank">@end</a>


运行结果:

2012-09-22 15:10:57.618 test[2253:f803] Background time remaining = 599.00 seconds

2012-09-22 15:10:58.618 test[2253:f803] Background time remaining = 598.00 seconds

2012-09-22 15:10:59.617 test[2253:f803] Background time remaining = 597.00 seconds

2012-09-22 15:11:00.618 test[2253:f803] Background time remaining = 596.00 seconds

2012-09-22 15:11:01.618 test[2253:f803] Background time remaining = 595.00 seconds

2012-09-22 15:11:02.617 test[2253:f803] Background time remaining = 594.00 seconds

2012-09-22 15:11:03.618 test[2253:f803] Background time remaining = 593.00 seconds
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: