iOS 通过定位获取常驻后台(重要是省电)

来源:互联网 发布:淘宝店铺怎么替换图片 编辑:程序博客网 时间:2024/05/18 02:37

我们知道ios 的应用,大部分都是进入后台,就不会执行任何操作,但是 ,很多时候我们希望程序进入后台,也能执行一些检测操作,比如说,应用进入后台,我们仍然可以实时去获取当前的位置信息。下面我们来了解下,ios 获取后台时间的几种方式

根据苹果文档中关于后台执行的描述,任何app都有3分钟左右的后台任务执行时间。 3分钟后,app会被iOS强行挂起。

但是,有几类app允许有“无限的”后台运行时间:

  1. Audio。
  2. Location/GPS。
  3. VoIP。

你可以将任何app声明为上述3种类型以获得无限的后台运行时间,但当你提交app到App Store时,苹果会审查你的app,一旦发现你“滥用”了后台API,你的app将被拒绝。也即是说你在info.plist 设置这几种backgroundmode,你的程序必须含有这些功能,你的程序才会有审核通过,你想获取应用进入后台获取更多的后台时间,还要看苹果给不给机会了。。。

1 上面有一种方式苹果文档说到任何应用都有3分钟的后台执行任务时间。好吧先看下一段代码

(1)

- (void)applicationDidEnterBackground:(UIApplication *)application {    

UIApplication*   app = [UIApplication sharedApplication]; 

        __block    UIBackgroundTaskIdentifier bgTask;

        bgTask = [app beginBackgroundTaskWithExpirationHandler:^{        

       dispatch_async(dispatch_get_main_queue(), ^{    

                     if (bgTask != UIBackgroundTaskInvalid)   

                            {                bgTask = UIBackgroundTaskInvalid;   

            }        

      });

}];               

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{              dispatch_async(dispatch_get_main_queue(), ^{            

                    if (bgTask != UIBackgroundTaskInvalid) {                    

                                              bgTask = UIBackgroundTaskInvalid;        });

      });

}

这种方式,是不需要再info.plist 配置就可以在申请到短时间的后台运行时间,苹果也不会对这个进行审核

2 第二种方式,也是今天想着重提到的,就是通过定位获取更多的后台使用的时间,这种适合于需要在后台收集用户的定位的场景,例如滴滴打车此类应用。

上面已经提到了这种方式,需要在info.plist 设置


因为在苹果在info.plist 进行了设置,苹果也会对其 进行审核。

接下来是在来看下代码段

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    // Override point for customization after application launch. 

   _task = [BGTask shareBGTask];  

  UIAlertView *alert;    //判断定位权限    

if([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusDenied)    {  

      alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"应用没有不可以定位,需要在在设置/通用/后台应用刷新开启" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];   

     [alert show];  

  }    elseif ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusRestricted)    {        

alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"设备不可以定位" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; 

       [alert show];    

}    else    {  

      _location = [[CLLocationManager alloc]init]; 

       _location.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//导航级别的精确度              _location.allowsBackgroundLocationUpdates = YES; //允许后台刷新                _location.pausesLocationUpdatesAutomatically = NO; //不允许自动暂停刷新 

       _location.distanceFilter = kCLDistanceFilterNone;  //不需要移动都可以刷新      

       [_location startUpdatingLocation];      

       [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(log) userInfo:nil repeats:YES];    }    return YES;

}//进入后台开启定位

- (void)applicationDidEnterBackground:(UIApplication *)application {

    [_location startUpdatingLocation];

}

经测试而得只要这样无论在前台或者是后台,log 这个方法都是有打印的。这里必须注意一点就是

  _location.distanceFilter = kCLDistanceFilterNone;  //不需要移动都可以刷新

之前因为要这样设置,不然就各种掉坑,不移动就不会执行定位,不定位的话,那么后台进程也就挂起了,那么就不能执行任何操作

(2)其实这种后台刷新是很暴力的,导航仪不断在定位,你才可以获取后台活跃的时间,去执行你的一些想要的操作,但是不断的定位会导致,电量消耗过快,我测试一个小时奖金跑去了10%的电量,那么有没有一些更优的方案,减少定位的次数,然后又能让后台活跃呢

下面来讲解下思路



这个优化面临的问题,就是当程序进入了后台,如果让定位停止了,那么程序就后台就无法活跃了,就是把程序进入后台的问题解决了,那就好办了,看了上图,也可以看出,思路主要是在当前正在定位的时候,10秒后关闭当前的定位,然后此时开启后台任务backgroundtask,那么只要就会有3分钟的活跃时间,那么在这个后台任务有效时间内再次开启定位的话,程序在后台便依旧可以活跃,那么只要开启和关闭循环进行,就可以实现常驻后台了,那么这个时间间隔可以自定义,在自己需要的范围内即可,但是不能超过3分钟,那么接下来在看看主要代码实现

//定位回调里执行重启定位和关闭定位

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{   

 NSLog(@"定位收集");//正在手机定位不执行任何操作    

if (isCollect) { 

       return;   

 }    

      [self performSelector:@selector(restartLocation) withObject:nil afterDelay:120]; 

      [self performSelector:@selector(stopLocation) withObject:nil afterDelay:10]; 

      isCollect = YES;

}

-(void)restartLocation{    NSLog(@"重新启动定位");  

          CLLocationManager *locationManager = [BGLogation shareBGLocation];   

          locationManager.delegate = self;    

          locationManager.distanceFilter = kCLDistanceFilterNone; // 不移动也可以后台刷新回调  

  if ([[UIDevice currentDevice].systemVersion floatValue]>= 8.0) {     

          [locationManager requestAlwaysAuthorization];    

}   


         [locationManager startUpdatingLocation]; 

         [self.bgTask beginNewBackgroundTask];

}//停止后台定位

-(void)stopLocation{    

         NSLog(@"停止定位");   

         isCollect = NO;   

         CLLocationManager *locationManager = [BGLogation shareBGLocation];  

         [locationManager stopUpdatingLocation];

}

接下来是demo 的地址

https://github.com/heysunnyboy/locationdemo.git

可以看到下面的代码 ,在delegate 里设置的定时器一直都在跑没有停止就知道这个后台常驻是有效的

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    // Override point for customization after application launch.  

           _task = [BGTask shareBGTask]; 

           UIAlertView *alert; 

   //判断定位权限    if([UIApplication sharedApplication].backgroundRefreshStatus ==       UIBackgroundRefreshStatusDenied) { 

       alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"应用没有不可以定位,需要在在设置/通用/后台应用刷新开启" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; 

          [alert show];  

  } elseif ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusRestricted)    {       

              alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"设备不可以定位" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; 

       [alert show];   

 }  else  {    

              self.bgLocation = [[BGLogation alloc]init];    

              [self.bgLocation startLocation];     

              [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(log) userInfo:nil repeats:YES];    

}    return YES;

}

1 0
原创粉丝点击