一,工程图。

二,代码。

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-后台运行,可以选择在前台或后台或前后台的更多相关文章

  1. Linux后台运行java的jar包后台运行java -jar 命令

    为什么java -jar 的命令终端的窗口关闭就停止运行了??tomcat中war的就不会? 关闭终端的窗口相当于ctrl+c的命令,关闭了窗口就相当于停止了java -jar这个进程,即ctrl+c ...

  2. iOS开发小技巧--iOS程序进入后台运行的实现

    iOS程序进入后台运行的实现 视频中看到老师用的iOS7,代码中有开启timer,无限请求数据的功能,但是切换到后台,代码就不打印了 自己用的iOS9,进入后台还是可以打印的,再次进入前台也可以正常运 ...

  3. iOS后台运行

    http://www.cocoachina.com/bbs/read.php?tid=149564 文一 我从苹果文档中得知,一般的应用在进入后台的时候可以获取一定时间来运行相关任务,也就是说可以在后 ...

  4. nobup 与 后台运行命令

    1. Linux进程状态:R (TASK_RUNNING),可执行状态&运行状态(在run_queue队列里的状态) 2. Linux进程状态:S (TASK_INTERRUPTIBLE),可 ...

  5. linux nohup命令使程序在后台运行的方法

    在linux操作系统中从后台一直运行某个程序的方法,就是使用nohup命令了. Unix/Linux下一般比如想让某个程序在后台运行,很多都是使用 & 在程序结尾来让程序自动运行. 比如要运行 ...

  6. Linux中如何让命令在后台运行

    1.在下达的命令后面加上&,就可以使该命令在后台进行工作,这样做最大的好处就是不怕被ctrl+c这个中断指令所中断. 2. 那大家可能又要问了,在后台执行的程序怎么使它恢复到前台来运行呢?很简 ...

  7. 判断App整体处于前台还是后台

    1.通过RunningTaskInfo类判断(需要额外权限): 复制代码代码如下: /** *判断当前应用程序处于前台还是后台 */ public static boolean isApplicati ...

  8. linux 命令 后台运行

    转载 1.在下达的命令后面加上&,就可以使该命令在后台进行工作,这样做最大的好处就是不怕被ctrl+c这个中断指令所中断. 2. 那大家可能又要问了,在后台执行的程序怎么使它恢复到前台来运行呢 ...

  9. linux===linux后台运行和关闭、查看后台任务(转)

    fg.bg.jobs.&.ctrl + z都是跟系统任务有关的,虽然现在基本上不怎么需要用到这些命令,但学会了也是很实用的 一.& 最经常被用到这个用在一个命令的最后,可以把这个命令放 ...

随机推荐

  1. [Server] 搭建发布环境Web Deploy

    在Web Deploy前,实际上完全可以使用FTP方式发布网站. 如果你购买的只是虚拟空间,那FTP方式更广泛. 先来搭建一套FTP吧 添加FTP服务 在网站上添加FTP发布 配置FTP服务 FTP注 ...

  2. 这些HTML、CSS知识点,面试和平时开发都需要 No8-No9

    系列知识点汇总 这些HTML.CSS知识点,面试和平时开发都需要 No1-No4(知识点:HTML.CSS.盒子模型.内容布局) 这些HTML.CSS知识点,面试和平时开发都需要 No5-No7(知识 ...

  3. call、apply、bind的区别

    me.setname.call(me,"dpd","dpd12");      通过call执行say方法 ,第一个参数为作用对象,后边的一些列参数作为实参传入 ...

  4. 【原创】Kakfa serializer包源代码分析

    这个包很简单,只有两个scala文件: decoder和encoder,就是提供序列化/反序列化的服务.我们一个一个说. 一.Decoder.scala 首先定义了一个trait: Decoder[T ...

  5. jquery.form.js实现异步上传

    前台页面 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewpor ...

  6. 新学C++的for,switch和随机数

    通过一个小程序学习: #include<iostream> #include<cstdlib> #include<ctime> using namespace st ...

  7. EF更新,数据库值变化,前台页面并不变化,刷新也不变化,重新运行程序则变化----开发中遇到的问题(已解决)

    首先说一下我遇到这个情况的代码情景,首先上错误代码 UserInfo userInfo = Session["UserInfo"] as UserInfo; ); 这段代码所呈现的 ...

  8. jquery取消超链接

  9. Android录音应用

    首先是xml布局文件: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xm ...

  10. MySQL Error Handling in Stored Procedures 2

    Summary: this tutorial shows you how to use MySQL handler to handle exceptions or errors encountered ...