【代码笔记】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都是跟系统任务有关的,虽然现在基本上不怎么需要用到这些命令,但学会了也是很实用的 一.& 最经常被用到这个用在一个命令的最后,可以把这个命令放 ...
随机推荐
- linux的计划
我接触linux也有好几年了,至少有5年了.最近公司在搞内部培训,人人都可以报名培训别人.想到自己在linux浸淫多年,应该出来出一份力.一直以来想就linux写一个专题.今天刚好在做相关的ppt,借 ...
- Web Scraping with Python读书笔记及思考
Web Scraping with Python读书笔记 标签(空格分隔): web scraping ,python 做数据抓取一定一定要明确:抓取\解析数据不是目的,目的是对数据的利用 一般的数据 ...
- JAVA - HashMap,TreeMap迭代
1.使用for_each循环迭代 public class TestUnit { public static void main(String[] args) { HashMap hashMap=ne ...
- Microsoft Orleans 之 入门指南
Microsoft Orleans 在.net用简单方法构建高并发.分布式的大型应用程序框架. 原文:http://dotnet.github.io/orleans/ 在线文档:http://dotn ...
- 基于C#的MongoDB数据库开发应用(2)--MongoDB数据库的C#开发
在上篇博客<基于C#的MongoDB数据库开发应用(1)--MongoDB数据库的基础知识和使用>里面,我总结了MongoDB数据库的一些基础信息,并在最后面部分简单介绍了数据库C#驱动的 ...
- Entity Framework 实体框架的形成之旅--基类接口的统一和异步操作的实现(3)
在本系列的第一篇随笔<Entity Framework 实体框架的形成之旅--基于泛型的仓储模式的实体框架(1)>中介绍了Entity Framework 实体框架的一些基础知识,以及构建 ...
- mybatis xml 中的特殊符转义字符号和模糊查询
xml特殊符号转义写法 < < 小于 <= <= 小于或等于 > > 大于 >= >= 大于或等于 <> <> 不等于 & ...
- 阿里巴巴开源技术 WebX
0. WebX项目目前已开源, 项目开源地址:https://github.com/webx/citrus-sample.git 项目参考文档:http://www.openwebx.org/docs ...
- C++转换构造函数与类型转换构造函数
转换构造函数: 转换构造函数的只有一个形参: Student(float s) { score = s; age = ; } 如果已经在上面定义了构造函数: Student(); //建立对象c1,由 ...
- 相识不易,要懂珍惜----------Spring Mvc
一.Spring Mvc简介 Spring Mvc也叫Spring Web Mvc,属于表现层额框架.Spring Mvc是Spring框架的一部分,是在Spring3.0后发布的. 二.Spring ...