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

启动后台运行任务时,调用UIApplication的实例方法beginBackgroundTaskWithExpirationHandler:

任务完成后,调用UIApplication实例方法endBackgroundTask:

01 //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>

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

转载自:http://my.oschina.net/notting/blog/79855

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值