转自 http://www.jianshu.com/p/d1ecc467faff
我们知道 ios 的应用,大部分都是进入后台,就不会执行任何操作,但是 ,很多时候我们希望程序进入后台,也能执行一些检测操作,比如说,应用进入后台,我们仍然可以实时去获取当前的位置信息。下面我们来了解下,ios 获取后台时间的几种方式
根据苹果文档中关于后台执行的描述,任何 app 都有 3 分钟左右的后台任务执行时间。 3 分钟后,app 会被 iOS 强行挂起。
但是,有几类 app 允许有 "无限的" 后台运行时间:
你可以将任何 app 声明为上述 3 种类型以获得无限的后台运行时间,但当你提交 app 到 App Store 时,苹果会审查你的 app,一旦发现你 "滥用" 了后台 API,你的 app 将被拒绝。也即是说你在 info.plist 设置这几种 backgroundmode, 你的程序必须含有这些功能,你的程序才会有审核通过,你想获取应用进入后台获取更多的后台时间,还要看苹果给不给机会了。。。
1 上面有一种方式苹果文档说到任何应用都有 3 分钟的后台执行任务时间。好吧先看下一段代码
(1)
- <code class="python" style="padding: 0px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12px; border: none; background-color: transparent;">
- - (void)applicationDidEnterBackground:(UIApplication *)application { UIApplication*
- app = [UIApplication sharedApplication]; __block UIBackgroundTaskIdentifier
- bgTask; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ dispatch_async(dispatch_get_main_queue(),
- ^{
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- if
- </span>
- (bgTask != UIBackgroundTaskInvalid) { bgTask = UIBackgroundTaskInvalid;
- } }); }]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
- <span class="hljs-number" style="color: rgb(42, 161, 152);">
- 0
- </span>
- ), ^{ dispatch_async(dispatch_get_main_queue(), ^{
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- if
- </span>
- (bgTask != UIBackgroundTaskInvalid) { bgTask = UIBackgroundTaskInvalid;
- }); }); }
- </code>
这种方式,是不需要再 info.plist 配置就可以在申请到短时间的后台运行时间,苹果也不会对这个进行审核
2 第二种方式,也是今天想着重提到的,就是通过定位获取更多的后台使用的时间,这种适合于需要在后台收集用户的定位的场景,例如滴滴打车此类应用。
上面已经提到了这种方式,需要在 info.plist 设置
因为在苹果在 info.plist 进行了设置,苹果也会对其 进行审核。
接下来是在来看下代码段
- <code class="python" style="padding: 0px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12px; border: none; background-color: transparent;">
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
- *)launchOptions { // Override point
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- for
- </span>
- customization after application launch. _task = [BGTask shareBGTask];
- UIAlertView *alert; //判断定位权限
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- if
- </span>
- ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusDenied)
- { alert = [[UIAlertView alloc]initWithTitle:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "提示"
- </span>
- message:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "应用没有不可以定位,需要在在设置/通用/后台应用刷新开启"
- </span>
- delegate:nil cancelButtonTitle:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "确定"
- </span>
- otherButtonTitles:nil, nil]; [alert show]; }
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- else
- </span>
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- if
- </span>
- ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusRestricted)
- { alert = [[UIAlertView alloc]initWithTitle:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "提示"
- </span>
- message:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "设备不可以定位"
- </span>
- delegate:nil cancelButtonTitle:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "确定"
- </span>
- otherButtonTitles:nil, nil]; [alert show]; }
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- else
- </span>
- { _location = [[CLLocationManager alloc]init]; _location.desiredAccuracy
- = kCLLocationAccuracyBestForNavigation;//导航级别的精确度 _location.allowsBackgroundLocationUpdates
- = YES; //允许后台刷新 _location.pausesLocationUpdatesAutomatically = NO; //不允许自动暂停刷新
- _location.distanceFilter = kCLDistanceFilterNone; //不需要移动都可以刷新 [_location
- startUpdatingLocation]; [NSTimer scheduledTimerWithTimeInterval:
- <span class="hljs-number" style="color: rgb(42, 161, 152);">
- 1.0
- </span>
- target:self selector:@selector(log) userInfo:nil repeats:YES]; }
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- return
- </span>
- YES; } //进入后台开启定位 - (void)applicationDidEnterBackground:(UIApplication
- *)application { [_location startUpdatingLocation]; }
- </code>
经测试而得只要这样无论在前台或者是后台,log 这个方法都是有打印的。这里必须注意一点就是
- <code class="python" style="padding: 0px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12px; border: none; background-color: transparent;">
- _location.distanceFilter = kCLDistanceFilterNone; //不需要移动都可以刷新
- </code>
之前因为要这样设置,不然就各种掉坑,不移动就不会执行定位,不定位的话,那么后台进程也就挂起了,那么就不能执行任何操作
(2)其实这种后台刷新是很暴力的,导航仪不断在定位,你才可以获取后台活跃的时间,去执行你的一些想要的操作,但是不断的定位会导致,电量消耗过快,我测试一个小时奖金跑去了 10% 的电量,那么有没有一些更优的方案,减少定位的次数,然后又能让后台活跃呢
下面来讲解下思路
这个优化面临的问题,就是当程序进入了后台,如果让定位停止了,那么程序就后台就无法活跃了,就是把程序进入后台的问题解决了,那就好办了,看了上图,也可以看出,思路主要是在当前正在定位的时候,10 秒后关闭当前的定位,然后此时开启后台任务 backgroundtask,那么只要就会有 3 分钟的活跃时间,那么在这个后台任务有效时间内再次开启定位的话,程序在后台便依旧可以活跃,那么只要开启和关闭循环进行,就可以实现常驻后台了,那么这个时间间隔可以自定义,在自己需要的范围内即可,但是不能超过 3 分钟,那么接下来在看看主要代码实现
- <code class="python" style="padding: 0px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12px; border: none; background-color: transparent;">
- //定位回调里执行重启定位和关闭定位 -(void)locationManager:(CLLocationManager *)manager
- didUpdateLocations:(NSArray
- <CLLocation *>
- *)locations { NSLog(@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "定位收集"
- </span>
- ); //正在手机定位不执行任何操作
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- if
- </span>
- (isCollect) {
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- return
- </span>
- ; } [self performSelector:@selector(restartLocation) withObject:nil afterDelay:
- <span class="hljs-number" style="color: rgb(42, 161, 152);">
- 120
- </span>
- ]; [self performSelector:@selector(stopLocation) withObject:nil afterDelay:
- <span class="hljs-number" style="color: rgb(42, 161, 152);">
- 10
- </span>
- ]; isCollect = YES; } -(void)restartLocation { NSLog(@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "重新启动定位"
- </span>
- ); CLLocationManager *locationManager = [BGLogation shareBGLocation];
- locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone;
- // 不移动也可以后台刷新回调
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- if
- </span>
- ([[UIDevice currentDevice].systemVersion floatValue]>=
- <span class="hljs-number" style="color: rgb(42, 161, 152);">
- 8.0
- </span>
- ) { [locationManager requestAlwaysAuthorization]; } [locationManager startUpdatingLocation];
- [self.bgTask beginNewBackgroundTask]; } //停止后台定位 -(void)stopLocation {
- NSLog(@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "停止定位"
- </span>
- ); isCollect = NO; CLLocationManager *locationManager = [BGLogation shareBGLocation];
- [locationManager stopUpdatingLocation]; }
- </code>
接下来是 demo 的地址
可以看到下面的代码 ,在 delegate 里设置的定时器一直都在跑没有停止就知道这个后台常驻是有效的
- <code class="python" style="padding: 0px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12px; border: none; background-color: transparent;">
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
- *)launchOptions { // Override point
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- for
- </span>
- customization after application launch. _task = [BGTask shareBGTask];
- UIAlertView *alert; //判断定位权限
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- if
- </span>
- ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusDenied)
- { alert = [[UIAlertView alloc]initWithTitle:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "提示"
- </span>
- message:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "应用没有不可以定位,需要在在设置/通用/后台应用刷新开启"
- </span>
- delegate:nil cancelButtonTitle:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "确定"
- </span>
- otherButtonTitles:nil, nil]; [alert show]; }
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- else
- </span>
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- if
- </span>
- ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusRestricted)
- { alert = [[UIAlertView alloc]initWithTitle:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "提示"
- </span>
- message:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "设备不可以定位"
- </span>
- delegate:nil cancelButtonTitle:@
- <span class="hljs-string" style="color: rgb(42, 161, 152);">
- "确定"
- </span>
- otherButtonTitles:nil, nil]; [alert show]; }
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- else
- </span>
- { self.bgLocation = [[BGLogation alloc]init]; [self.bgLocation startLocation];
- [NSTimer scheduledTimerWithTimeInterval:
- <span class="hljs-number" style="color: rgb(42, 161, 152);">
- 1.0
- </span>
- target:self selector:@selector(log) userInfo:nil repeats:YES]; }
- <span class="hljs-keyword" style="color: rgb(133, 153, 0);">
- return
- </span>
- YES; }
- </code>
来源: http://lib.csdn.net/article/ios/42734