【代码笔记】iOS-后台运行,可以选择在前台或后台或前后台
一,工程图。

二,代码。
AppDelegate.h
AppDelegate.m
RootViewController.h

#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (nonatomic, strong) NSTimer *myTimer; @end

RootViewController.m

#import "AppDelegate.h"
#import "RootViewController.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch. RootViewController *rootVC=[[RootViewController alloc]init];
UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:rootVC];
self.window.rootViewController=nav; self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
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
{ // 使用这个方法来释放公共的资源、存储用户数据、停止我们定义的定时器(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]; } - (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);
}
} - (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. //添加此段代码,则在前台就不运行了。否则会前后台一起运行。除第一次启动的时候,是前台不运行,退出后台时候运行。 if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){
[self endBackgroundTask];
}
} - (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

【代码笔记】iOS-后台运行,可以选择在前台或后台或前后台的更多相关文章
- Linux后台运行java的jar包后台运行java -jar 命令
为什么java -jar 的命令终端的窗口关闭就停止运行了??tomcat中war的就不会? 关闭终端的窗口相当于ctrl+c的命令,关闭了窗口就相当于停止了java -jar这个进程,即ctrl+c ...
- iOS开发小技巧--iOS程序进入后台运行的实现
iOS程序进入后台运行的实现 视频中看到老师用的iOS7,代码中有开启timer,无限请求数据的功能,但是切换到后台,代码就不打印了 自己用的iOS9,进入后台还是可以打印的,再次进入前台也可以正常运 ...
- iOS后台运行
http://www.cocoachina.com/bbs/read.php?tid=149564 文一 我从苹果文档中得知,一般的应用在进入后台的时候可以获取一定时间来运行相关任务,也就是说可以在后 ...
- nobup 与 后台运行命令
1. Linux进程状态:R (TASK_RUNNING),可执行状态&运行状态(在run_queue队列里的状态) 2. Linux进程状态:S (TASK_INTERRUPTIBLE),可 ...
- linux nohup命令使程序在后台运行的方法
在linux操作系统中从后台一直运行某个程序的方法,就是使用nohup命令了. Unix/Linux下一般比如想让某个程序在后台运行,很多都是使用 & 在程序结尾来让程序自动运行. 比如要运行 ...
- Linux中如何让命令在后台运行
1.在下达的命令后面加上&,就可以使该命令在后台进行工作,这样做最大的好处就是不怕被ctrl+c这个中断指令所中断. 2. 那大家可能又要问了,在后台执行的程序怎么使它恢复到前台来运行呢?很简 ...
- 判断App整体处于前台还是后台
1.通过RunningTaskInfo类判断(需要额外权限): 复制代码代码如下: /** *判断当前应用程序处于前台还是后台 */ public static boolean isApplicati ...
- linux 命令 后台运行
转载 1.在下达的命令后面加上&,就可以使该命令在后台进行工作,这样做最大的好处就是不怕被ctrl+c这个中断指令所中断. 2. 那大家可能又要问了,在后台执行的程序怎么使它恢复到前台来运行呢 ...
- linux===linux后台运行和关闭、查看后台任务(转)
fg.bg.jobs.&.ctrl + z都是跟系统任务有关的,虽然现在基本上不怎么需要用到这些命令,但学会了也是很实用的 一.& 最经常被用到这个用在一个命令的最后,可以把这个命令放 ...
随机推荐
- [译]学习IPython进行交互式计算和数据可视化(五)
第四章:交互式绘图接口 本章我们将展示Python的绘图功能以及如何在IPython中交互式地使用它们. NumPy为处理大量的多维数组结构的数据提供了高效的方法.但是看行行列列的数字总不如直接看曲线 ...
- 2013最新版Subversion 1.7.10 for Windows x86 + Apache 2.4.4 x64 安装配置教程+错误解决方案
一 .工作环境 操作系统:Windows Server 2008 R2 SP1 x64 Apache版本:2.4.4 Subversion版本: Setup-Subversion-1.7.10.msi ...
- iis 不能访问json文件
我从网上查的资料,解决方案都是设置MIME 映射和“处理脚本映射”. 我按照网上的解决方案执行之后还没有解决我的这个问题,所以我想会不会是其他的原因. 在那么一瞬间,灵光一闪,我把json文件放到新建 ...
- C#微信公众平台开发—access_token的获取存储与更新
一.什么是access_token? access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token.正常情况下access_token有效期为7200秒,重复获取 ...
- 动态dynamically变更母版_Layout页body标签css的class
这个功能演示是Insus.NET最近想实现的一个功能,就是动态dynamically变更母版_Layout页body标签的样式css的class. 很多视图共同一个母版_Layout页,但是某一个视图 ...
- Model元数据提供机制小结
在最开始先我得说说我看这部分的情况,最开始被各种ModelMetadata和各种ModelMetadataProvider给搞晕了,就几页书花了我好大的精力去看,直到后来看了一幅类图,细细看各个类之间 ...
- Firemonkey TEdit 切换不同 KeyboardType 样式
用代码切换 Edit 不同的键盘样式: procedure TForm1.Button1Click(Sender: TObject); begin Edit1.KeyboardType := TVir ...
- 我整理的PHP 7.0主要新特性
原文:http://php.net/manual/en/migration70.new-features.php 1.标量参数类型声明 现在支持字符串(string).整型(int).浮点数(floa ...
- maven url
aliyun阿里云Maven仓库地址--加速你的maven构建 maven仓库用过的人都知道,国内有多么的悲催.还好有比较好用的镜像可以使用,尽快记录下来.速度提升100倍. http://mav ...
- 【视频处理】YV12ToARGB
前面提到了YV12转RGB的各种实现方法和优化方法,主要是CPU上的实现.本文主要介绍基于GPU的YV12转RGB的实现. 1. 基于OpenGL的实现 利用OpenGL shader实现将YV12转 ...