分享

后台运行定位,音频,网络电话

 wintelsui 2014-12-19

大家都知道我们的程序在后台运行的时间是10分钟,10分钟后便会停止。但是像实时定位,播放音频,以及网络电话这些功能我们需要在后台持续运行。那么我们就要进行相应的设置。

下面具体的例子以定位为例

 

Oc代码  收藏代码
  1. <span style="font-family: 'comic sans ms', sans-serif; color: #008080; font-size: small;">#import <UIKit/UIKit.h>  
  2. #import <CoreLocation/CoreLocation.h>  
  3.   
  4. @interface BackgroundTrackerViewController : UIViewController<CLLocationManagerDelegate>  
  5.   
  6. @property(nonatomic, retain) CLLocationManager *locationManager;  
  7. @property(nonatomic, retain)  UIButton *startTrackingButton;  
  8. @property(nonatomic, retain)  UILabel  *alertLabel;  
  9.   
  10. - (void)startTracking:(id)sender;  
  11. </span>  

 #import "BackgroundTrackerViewController.h"

Oc代码  收藏代码
  1. <span style="font-family: 'comic sans ms', sans-serif; color: #008080; font-size: small;">  
  2.   
  3. @interface BackgroundTrackerViewController ()  
  4.   
  5. @end  
  6.   
  7. @implementation BackgroundTrackerViewController  
  8. @synthesize locationManager,startTrackingButton,alertLabel;  
  9.   
  10. //开始跟踪  
  11. - (void)startTracking:(id)sender  
  12. {  
  13.     [locationManager startUpdatingLocation];   
  14. }  
  15.   
  16.   
  17. -(void)start:(id)sender  
  18. {  
  19. //    [locationManager startUpdatingLocation];   
  20. }  
  21.   
  22. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  23. {  
  24.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  25.     if (self) {  
  26.         // Custom initialization  
  27.     }  
  28.     return self;  
  29. }  
  30.   
  31. - (void)viewDidLoad  
  32. {  
  33.     [super viewDidLoad];  
  34.     // Do any additional setup after loading the view from its nib.  
  35.       
  36.     self.view.backgroundColor=[UIColor grayColor];  
  37.       
  38.       
  39.     self.startTrackingButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];  
  40.     startTrackingButton.frame=CGRectMake(0, 200, 100, 50);  
  41.     [startTrackingButton addTarget:self action:@selector(startTracking:) forControlEvents:UIControlEventTouchUpInside];  
  42.     [startTrackingButton setTitle:@"startTracking" forState:UIControlStateNormal];  
  43.     [self.view addSubview:startTrackingButton];  
  44.       
  45.       
  46.     self.alertLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 50)];  
  47.     self.alertLabel.backgroundColor=[UIColor orangeColor];  
  48.     self.alertLabel.hidden=YES;  
  49.     self.alertLabel.text=@"无法找到位置";  
  50.     [self.view addSubview:alertLabel];  
  51.       
  52.       
  53.     locationManager = [[CLLocationManager alloc] init];  
  54.     [locationManager setDelegate:self];  
  55.     //Only applies when in foreground otherwise it is very significant changes  
  56.     [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];//要求的精确度  
  57. }  
  58.   
  59.   
  60. - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {  
  61.     CLLocationCoordinate2D currentCoordinates = newLocation.coordinate;  
  62.     [alertLabel setText:@"Location Has been found"];  
  63.     [alertLabel setHidden:NO];  
  64.     NSLog(@"Entered new Location with the coordinates Latitude: %f Longitude: %f", currentCoordinates.latitude, currentCoordinates.longitude);  
  65. }  
  66. - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {  
  67.     NSLog(@"Unable to start location manager. Error:%@", [error description]);  
  68.     [alertLabel setHidden:NO];  
  69. }  
  70.   
  71.   
  72. - (void)didReceiveMemoryWarning  
  73. {  
  74.     [super didReceiveMemoryWarning];  
  75.     // Dispose of any resources that can be recreated.  
  76. }  
  77. </span>  

 - (void)applicationDidEnterBackground:(UIApplication *)application

Oc代码  收藏代码
  1. <span style="font-family: 'comic sans ms', sans-serif; color: #008080; font-size: small;">{  
  2.     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.  
  3.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
  4.     
  5.     if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])  
  6.     { //Check if our iOS version supports multitasking I.E iOS 4  
  7.         if ([[UIDevice currentDevice] isMultitaskingSupported])  
  8.         { //Check if device supports mulitasking  
  9.             UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance  
  10.               
  11.             __block UIBackgroundTaskIdentifier background_task; //Create a task object  
  12.               
  13.             background_task = [application beginBackgroundTaskWithExpirationHandler: ^{  
  14.                 /*  
  15.                  当应用程序后台停留的时间为0时,会执行下面的操作(应用程序后台停留的时间为600s,可以通过backgroundTimeRemaining查看)  
  16.                  */  
  17.                 [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks  
  18.                 background_task = UIBackgroundTaskInvalid; //Set the task to be invalid  
  19.                   
  20.                 //System will be shutting down the app at any point in time now  
  21.             }];  
  22.               
  23.             // Background tasks require you to use asyncrous tasks  
  24.               
  25.             dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
  26.                 //Perform your tasks that your application requires  
  27.                 NSLog(@"time remain:%f", application.backgroundTimeRemaining);                  
  28.                 [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform  
  29.                 background_task = UIBackgroundTaskInvalid; //Invalidate the background_task  
  30.             });  
  31.         }  
  32.     }  
  33.       
  34.       
  35. }  
  36. </span>  

    修改应用的Info.plist 文件,你需要在Info.plist文件中添加UIBackgroundModes字段,该字段的值是应用支持的所有后台模式,是一个数值类型。目前此数 组可以包含“audio”、“location”和“voip”这三个字符串常量.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多