多任务

启动后台运行任务时,调用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值为DBL_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)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;
        }
    });
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值