iOS 程序退到后台,如何继续执行任务

程序从前台退到后,将执行程序的委托方法。

- (void)applicationDidEnterBackground:(UIApplication *)application

{

}

问题:

当应用被送到后台,主线程就会被暂停。用 NSThread 的 detachNewThreadSelector:toTar get:withObject:类方法创建的线程也被挂起。

场景:

应用从前台退到后台

程序执行代理方法 applicationDidEnterBackground。这时候,我们只有很短的时间来处理需要处理的工作,随后,所有的线程就都被挂起了。

实际上,我们需要更长的时间来完成我们的需要的必要操作:

比如:

1.将数据保存到远程服务器的操作。

2.记录一些需要的信息操作。

参考解决方案 :

向iOS申请,在后台完成一个Long-Running Task任务

1.项目的AppDelegate.h文件中

声明一个 UIBackgroundTaskIdentifier ,相当于写了一条借据。告诉iOS,我们的程序将要借更多的时间来完成 Long-Running Task 任务。

@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;

@property (nonatomic, strong) NSTimer *myTimer;

2.项目的AppDelegate.m文件中

1.注意在applicationDidEnterBackground方法中,完成借据的流程

即:

self. backgroundTaskIdentifier =[application beginBackgroundTaskWithExpirationHandler:^( void) {

[self endBackgroundTask];

}];

// 当应用程序掉到后台时,执行该方法

- (void)applicationDidEnterBackground:(UIApplication *)application

{

// 使用这个方法来释放公共的资源、存储用户数据、停止我们定义的定时器(timers)、并且存储在程序终止前的相关信息。

// 如果,我们的应用程序提供了后台执行的方法,那么,在程序退出时,这个方法将代替applicationWillTerminate方法的执行。

// 标记一个长时间运行的后台任务将开始

// 通过调试,发现,iOS给了我们10分钟(600s)来执行这个任务。

self.backgroundTaskIdentifier =[application beginBackgroundTaskWithExpirationHandler:^(void) {

// 当应用程序留给后台的时间快要到结束时(应用程序留给后台执行的时间是有限的), 这个Block块将被执行

// 我们需要在Block块中执行一些清理工作。

// 如果清理工作失败了,那么将导致程序挂掉

// 清理工作需要在主线程中用同步的方式来进行

[self endBackgroundTask];

}];

// 模拟一个Long-Running Task

self.myTimer =[NSTimer scheduledTimerWithTimeInterval:1.0f

target:self

selector:@selector(timerMethod:)     userInfo:nil

repeats:YES];

}

2.完成后,要告诉iOS,任务完成,提交完成申请“好借好还”:

[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];

strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;

}

});

- (void) endBackgroundTask{

dispatch_queue_t mainQueue = dispatch_get_main_queue();

AppDelegate *weakSelf = self;

dispatch_async(mainQueue, ^(void) {

AppDelegate *strongSelf = weakSelf;

if (strongSelf != nil){

[strongSelf.myTimer invalidate];// 停止定时器

// 每个对 beginBackgroundTaskWithExpirationHandler:方法的调用,必须要相应的调用 endBackgroundTask:方法。这样,来告诉应用程序你已经执行完成了。

// 也就是说,我们向 iOS 要更多时间来完成一个任务,那么我们必须告诉 iOS 你什么时候能完成那个任务。

// 也就是要告诉应用程序:“好借好还”嘛。

// 标记指定的后台任务完成

[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];

// 销毁后台任务标识符

strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;

}

});

}

// 模拟的一个 Long-Running Task 方法

- (void) timerMethod:(NSTimer *)paramSender{

// backgroundTimeRemaining 属性包含了程序留给的我们的时间

NSTimeInterval backgroundTimeRemaining =[[UIApplication sharedApplication] backgroundTimeRemaining];

if (backgroundTimeRemaining == DBL_MAX){

NSLog(@"Background Time Remaining = Undetermined");

} else {

NSLog(@"Background Time Remaining = %.02f Seconds", backgroundTimeRemaining);

}

}

3.记住,借和换必须成双成对!

具体的解释,我也写在了方法中,如果有错误之处,还希望能够指正!谢谢!

4.如果,程序提前完成了,也可以提前结束:

[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];

self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;

向iOS申请,在后台无限时间

经过证明,即使时执行Long-Running Task 任务,当程序被调到后台后,也是有时间限制的。一般为10分总(600s)。如何向程序申请无限时间呢?!

那就欺骗iOS系统吧。让它感觉你的程序还是在运行。

那就在后台用 AVAudioPlayer无限循环播放一个音频文件。

呵呵,如果播放一个无声音的音频文件呢?!!

步骤:

1.在plish文件中加入背景播放的支持。

加入项:Required background modes。并设置为:audio

2.初始化一个AVAudioPlayer音频,并且无限制的播放下去。

- (void)viewDidLoad

{

[super viewDidLoad];

dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(dispatchQueue, ^(void) {

NSError *audioSessionError = nil;

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

if ([audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]){

NSLog(@"Successfully set the audio session.");

} else {

NSLog(@"Could not set the audio session");

}

NSBundle *mainBundle = [NSBundle mainBundle];

NSString *filePath = [mainBundle pathForResource:@"mySong" ofType:@"mp3"];

NSData *fileData = [NSData dataWithContentsOfFile:filePath];

NSError *error = nil;

self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];

if (self.audioPlayer != nil){

self.audioPlayer.delegate = self;

[self.audioPlayer setNumberOfLoops:-1];

if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){

NSLog(@"Successfully started playing...");

} else {

NSLog(@"Failed to play.");

}

} else {

}

});

}

时间: 2024-08-24 18:24:12

iOS 程序退到后台,如何继续执行任务的相关文章

iOS程序执行顺序和UIViewController 的生命周期(整理)

说明:此文是自己的总结笔记,主要参考: iOS程序的启动执行顺序 AppDelegate 及 UIViewController 的生命周期 UIView的生命周期 言叶之庭.jpeg 一. iOS程序的启动执行顺序 程序启动顺序图 iOS启动原理图.png 具体执行流程 程序入口进入main函数,设置AppDelegate称为函数的代理 程序完成加载[AppDelegate application:didFinishLaunchingWithOptions:] 创建window窗口 程序被激活[

UIViewController的生命周期及iOS程序执行顺序

当一个视图控制器被创建,并在屏幕上显示的时候. 代码的执行顺序1. alloc                                   创建对象,分配空间2.init (initWithNibName) 初始化对象,初始化数据3.loadView                          从nib载入视图 ,通常这一步不需要去干涉.除非你没有使用xib文件创建视图4.viewDidLoad                   载入完成,可以进行自定义数据以及动态创建其他控件5

ios程序后台运行设置(不是太懂)

文一 我从苹果文档中得知,一般的应用在进入后台的时候可以获取一定时间来运行相关任务,也就是说可以在后台运行一小段时间. 还有三种类型的可以运行在后以, 1.音乐 2.location 3.voip 文二 在IOS后台执行是本文要介绍的内容,大多数应用程序进入后台状态不久后转入暂停状态.在这种状态下,应用程序不执行任何代码,并有可能在任意时候从内存中删除.应用程序提供特定的服务,用户可以请求后台执行时间,以提供这些服务. 判断是否支持多线程 UIDevice* device = [UIDevice

iOS程序的执行顺序 和 UIViewController的生命周期

iOS程序的执行顺序 1 进入程序的入口 进入main函数, 设置AppDelegate称为函数的代理 2  程序完成加载 -[AppDelegate application:didFinishLaunchingWithOptions:] 3 创建window窗口 4 程序被激活 -[AppDelegate applicationDidBecomeActive:] 5 当点击command+H时  程序取消激活状态 -[AppDelegate applicationWillResignActiv

iOS程序执行顺序 AppDelegate及 UIViewController 的生命周期

iOS程序的启动执行顺序 AppDelegate 及 UIViewController 的生命周期 iOS应用程序的状态切换很重要,而UIViewControler对于iOS这种MVC模式来说尤为重要,基本都要继承自他. 一.iOS程序的启动执行顺序 1 程序的入口 进入main函数, 设置AppDelegate称为函数的代理 2  程序完成加载 -[AppDelegate application:didFinishLaunchingWithOptions:] 3 创建window窗口 4 程序

iOS程序的执行顺序和iOS程序文件执行顺序

iOS程序的执行顺序 首先从main.m文件的main函数开始执行的.int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } //1.principalClassName:应用程序对象的类名(UIApplication或其子类) //2.delegateClassName

程序被送入后台后,向 iOS 借时间,完成长期任务-备

12.2.2. 方案 使用UIApplication的beginBackgroundTaskWithExpirationHandler: 实例方法.在你完成任务后,调用UIApplication的endBackgroundTask:方法. 12.2.3. 讨论 当一个iOS应用被送到后台,它的主线程会被暂停.你用NSThread的detachNewThreadSelector:toTar get:withObject:类方法创建的线程也被挂起了.如果你想在后台完成一个长期任务,就必须调用UIAp

iOS程序进入后台,延迟指定时间退出

程序进入后台,延迟指定时间退出 正常程序退出后,会在几秒内停止工作:要想申请更长的时间,需要用到beginBackgroundTaskWithExpirationHandlerendBackgroundTask一定要成对出现 {   NSTimer *_timer; int aa; __block UIBackgroundTaskIdentifier _backIden; } - (void)applicationDidEnterBackground:(UIApplication *)appli

iOS 在视图控制器里面判断 应用程序的前台 后台切换 UIViewController

1.时机  用户点击home 键  应用退到后台 再次点击进入前台  在UIViewController里面 控制器如何获取相关的事件? 2.需求 (1)NSTimer   在应用程序进入后台 10秒至10分钟会停止(10分钟左右一般应用也会被kill)  但是只要在后台这个nstimer 运行 就是邋遢的 所以我想停止它 在应用进入后台的时候 (2)程序支持后台下载,当用户停止在下载管理界面时,然后用户点击home键使程序进入后台运行,等用户返回到程序时,下载管理界面需要显示最新的下载进度.(