iOS 应用进入后台后,如何短暂的执行一个任务

来源:互联网 发布:cdr软件手机版 编辑:程序博客网 时间:2024/06/04 18:24

iOS 应用进入后台后短暂的实现任务

在开发中,我们难免会碰到应用程序进入后台后,但是我们任然要执行一些任务。比如保存一个文件,跳到第三方分享的时候处理一些任务,发送一些请求什么的。但是应用进入后台后不久后就会转入暂停状态。在这种状态下,程序不会执行任何的代码,并且有可能随时被删除。有三种服务可以在后台执行。音频,定位,VoIP(VoiceoverInternetProtocol 是一种以IP电话为主,并推出相应的增值业务的技术),这三种都要在plist文件里设置相应的字段。本文说一种简单的方法,可以在应用进入后台后,任然处理一些任务。当应用进入后台以后,开启一个定时器,30秒后打印一个“时间到”。

1.当应用进入后台,在AppDelegate.m文件中,会执行以下方法:

- (void)applicationDidEnterBackground:(UIApplication *)application

2.当应用回到前台的时候,以下方法会实现

- (void)applicationWillEnterForeground:(UIApplication *)application

3.在 applicationDidEnterBackground 方法中

- (void)applicationDidEnterBackground:(UIApplication *)application{    NSLog(@"DidEnterBackground");    self.timeCount = 0;    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeRun) userInfo:nil repeats:true];    UIApplication* app = [UIApplication sharedApplication];  UIBackgroundTaskIdentifier  bgTask = [app beginBackgroundTaskWithExpirationHandler:^{      [app endBackgroundTask:bgTask];  }];}- (void)timeRun{    self.timeCount ++;    NSLog(@"timeCount = %d",self.timeCount);    if (self.timeCount >= 30) {        NSLog(@"时间到");        if (self.timer) {            self.timeCount = 0;            [self.timer invalidate];            self.timer = nil;        }    }}

打印的结果
开始

结束
4.如果时间不到30秒就返回了应用,我们可以把定时器取消

- (void)applicationWillEnterForeground:(UIApplication *)application{    NSLog(@"WillEnterForeground");    if (self.timer) {        self.timeCount = 0;        [self.timer invalidate];        self.timer = nil;    }}

这里写图片描述

这只是一个简便的实现方法。这种方法具体能持续多久时间,我也没有测过。希望有不足的地方大家可以留言指教。
0 0