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


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

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

Oc代码
  1. <SPANstyle="FONT-FAMILY:'comicsansms',sans-serif;COLOR:#008080;FONT-SIZE:small">#import<UIKit/UIKit.h>
  2. #import<CoreLocation/CoreLocation.h>
  3. @interfaceBackgroundTrackerViewController:UIViewController<CLLocationManagerDelegate>
  4. @property(nonatomic,retain)CLLocationManager*locationManager;
  5. @property(nonatomic,retain)UIButton*startTrackingButton;
  6. @property(nonatomic,retain)UILabel*alertLabel;
  7. -(void)startTracking:(id)sender;
  8. </SPAN>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface BackgroundTrackerViewController : UIViewController<CLLocationManagerDelegate>

@property(nonatomic, retain) CLLocationManager *locationManager;
@property(nonatomic, retain)  UIButton *startTrackingButton;
@property(nonatomic, retain)  UILabel  *alertLabel;

- (void)startTracking:(id)sender;

#import "BackgroundTrackerViewController.h"

Oc代码
  1. <SPANstyle="FONT-FAMILY:'comicsansms',sans-serif;COLOR:#008080;FONT-SIZE:small">
  2. @interfaceBackgroundTrackerViewController()
  3. @end
  4. @implementationBackgroundTrackerViewController
  5. @synthesizelocationManager,startTrackingButton,alertLabel;
  6. //开始跟踪
  7. -(void)startTracking:(id)sender
  8. {
  9. [locationManagerstartUpdatingLocation];
  10. }
  11. -(void)start:(id)sender
  12. {
  13. //[locationManagerstartUpdatingLocation];
  14. }
  15. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil
  16. {
  17. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  18. if(self){
  19. //Custominitialization
  20. }
  21. returnself;
  22. }
  23. -(void)viewDidLoad
  24. {
  25. [superviewDidLoad];
  26. //Doanyadditionalsetupafterloadingtheviewfromitsnib.
  27. self.view.backgroundColor=[UIColorgrayColor];
  28. self.startTrackingButton=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];
  29. startTrackingButton.frame=CGRectMake(0,200,100,50);
  30. [startTrackingButtonaddTarget:selfaction:@selector(startTracking:)forControlEvents:UIControlEventTouchUpInside];
  31. [startTrackingButtonsetTitle:@"startTracking"forState:UIControlStateNormal];
  32. [self.viewaddSubview:startTrackingButton];
  33. self.alertLabel=[[UILabelalloc]initWithFrame:CGRectMake(0,100,320,50)];
  34. self.alertLabel.backgroundColor=[UIColororangeColor];
  35. self.alertLabel.hidden=YES;
  36. self.alertLabel.text=@"无法找到位置";
  37. [self.viewaddSubview:alertLabel];
  38. locationManager=[[CLLocationManageralloc]init];
  39. [locationManagersetDelegate:self];
  40. //Onlyapplieswheninforegroundotherwiseitisverysignificantchanges
  41. [locationManagersetDesiredAccuracy:kCLLocationAccuracyBest];//要求的精确度
  42. }
  43. -(void)locationManager:(CLLocationManager*)managerdidUpdateToLocation:(CLLocation*)newLocationfromLocation:(CLLocation*)oldLocation{
  44. CLLocationCoordinate2DcurrentCoordinates=newLocation.coordinate;
  45. [alertLabelsetText:@"LocationHasbeenfound"];
  46. [alertLabelsetHidden:NO];
  47. NSLog(@"EnterednewLocationwiththecoordinatesLatitude:%fLongitude:%f",currentCoordinates.latitude,currentCoordinates.longitude);
  48. }
  49. -(void)locationManager:(CLLocationManager*)managerdidFailWithError:(NSError*)error{
  50. NSLog(@"Unabletostartlocationmanager.Error:%@",[errordescription]);
  51. [alertLabelsetHidden:NO];
  52. }
  53. -(void)didReceiveMemoryWarning
  54. {
  55. [superdidReceiveMemoryWarning];
  56. //Disposeofanyresourcesthatcanberecreated.
  57. }
  58. </SPAN>


@interface BackgroundTrackerViewController ()

@end

@implementation BackgroundTrackerViewController
@synthesize locationManager,startTrackingButton,alertLabel;

//开始跟踪
- (void)startTracking:(id)sender
{
    [locationManager startUpdatingLocation]; 
}


-(void)start:(id)sender
{
//    [locationManager startUpdatingLocation]; 
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor=[UIColor grayColor];
    
    
    self.startTrackingButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    startTrackingButton.frame=CGRectMake(0, 200, 100, 50);
    [startTrackingButton addTarget:self action:@selector(startTracking:) forControlEvents:UIControlEventTouchUpInside];
    [startTrackingButton setTitle:@"startTracking" forState:UIControlStateNormal];
    [self.view addSubview:startTrackingButton];
    
    
    self.alertLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 50)];
    self.alertLabel.backgroundColor=[UIColor orangeColor];
    self.alertLabel.hidden=YES;
    self.alertLabel.text=@"无法找到位置";
    [self.view addSubview:alertLabel];
    
    
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    //Only applies when in foreground otherwise it is very significant changes
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];//要求的精确度
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    CLLocationCoordinate2D currentCoordinates = newLocation.coordinate;
    [alertLabel setText:@"Location Has been found"];
    [alertLabel setHidden:NO];
    NSLog(@"Entered new Location with the coordinates Latitude: %f Longitude: %f", currentCoordinates.latitude, currentCoordinates.longitude);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Unable to start location manager. Error:%@", [error description]);
    [alertLabel setHidden:NO];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)applicationDidEnterBackground:(UIApplication *)application

Oc代码
  1. <SPANstyle="FONT-FAMILY:'comicsansms',sans-serif;COLOR:#008080;FONT-SIZE:small">{
  2. //Usethismethodtoreleasesharedresources,saveuserdata,invalidatetimers,andstoreenoughapplicationstateinformationtorestoreyourapplicationtoitscurrentstateincaseitisterminatedlater.
  3. //Ifyourapplicationsupportsbackgroundexecution,thismethodiscalledinsteadofapplicationWillTerminate:whentheuserquits.
  4. if([[UIDevicecurrentDevice]respondsToSelector:@selector(isMultitaskingSupported)])
  5. {//CheckifouriOSversionsupportsmultitaskingI.EiOS4
  6. if([[UIDevicecurrentDevice]isMultitaskingSupported])
  7. {//Checkifdevicesupportsmulitasking
  8. UIApplication*application=[UIApplicationsharedApplication];//Getthesharedapplicationinstance
  9. __blockUIBackgroundTaskIdentifierbackground_task;//Createataskobject
  10. background_task=[applicationbeginBackgroundTaskWithExpirationHandler:^{
  11. /*
  12. 当应用程序后台停留的时间为0时,会执行下面的操作(应用程序后台停留的时间为600s,可以通过backgroundTimeRemaining查看)
  13. */
  14. [applicationendBackgroundTask:background_task];//Tellthesystemthatwearedonewiththetasks
  15. background_task=UIBackgroundTaskInvalid;//Setthetasktobeinvalid
  16. //Systemwillbeshuttingdowntheappatanypointintimenow
  17. }];
  18. //Backgroundtasksrequireyoutouseasyncroustasks
  19. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{
  20. //Performyourtasksthatyourapplicationrequires
  21. NSLog(@"timeremain:%f",application.backgroundTimeRemaining);
  22. [applicationendBackgroundTask:background_task];//Endthetasksothesystemknowsthatyouaredonewithwhatyouneedtoperform
  23. background_task=UIBackgroundTaskInvalid;//Invalidatethebackground_task
  24. });
  25. }
  26. }
  27. }
  28. </SPAN>

作者:陈杭州

优质内容筛选与推荐>>
1、待研究
2、Kubernetes技术分析之灰度升级
3、pythonic-让python代码更高效
4、jquery之stop()的用法
5、异步编程模式(五):实现 IAsyncResult 异步调用模式的组件


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn