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

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

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

//AppDelegate.h

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundIdentifier;

@property (nonatomic, strong) NSTimer *myTimer;

@end

//  AppDelegate.m
//  test
//

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window;
@synthesize backgroundIdentifier;
@synthesize myTimer;

- (BOOL)isMultitaskingSupported
{
    BOOL result = NO;
    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
        result = [[UIDevice currentDevice] isMultitaskingSupported];
    }
    return result;
}

- (void)timerMethod:(NSTimer *)paramSender{
    //获取后台任务可执行时间,单位秒,若应用未能在此时间内完成任务,则应用将被终止
    NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];
    
    //应用处于前台时,backgroundTimeRemaining值weiDBL_MAX
    if (backgroundTimeRemaining == DBL_MAX) {
        NSLog(@"Background time remaining = Undetermined");
    } else {
        NSLog(@"Background time remaining = %.02f seconds", backgroundTimeRemaining);
    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if ([self isMultitaskingSupported]) {
        NSLog(@"Multitasking is supported.");
    } else {
        NSLog(@"Multitasking is not supported.");
    }
    
    return YES;
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
    // 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.
    // 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.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if ([self isMultitaskingSupported] == NO){
        return; }
    self.myTimer =
    [NSTimer scheduledTimerWithTimeInterval:1.0f
                                     target:self
                                   selector:@selector(timerMethod:) userInfo:nil
                                    repeats:YES];
    self.backgroundIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {
        [self endBackgroundTask];
    }];
}

- (void) endBackgroundTask{
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    __weak AppDelegate *weakSelf = self;
    dispatch_async(mainQueue, ^(void) {
        AppDelegate *strongSelf = weakSelf;
        if (strongSelf != nil){
            [strongSelf.myTimer invalidate];
            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundIdentifier];
            strongSelf.backgroundIdentifier = UIBackgroundTaskInvalid;
        }
    });
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // 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.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // 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.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


运行结果:

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

转载于:https://my.oschina.net/notting/blog/79855

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值