当前位置:首页 > 开发 > 移动开发 > 正文

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

发表于: 2013-01-04   作者:吃饱了就饿   来源:转载   浏览:
摘要: 大家都知道我们的程序在后台运行的时间是10分钟,10分钟后便会停止。但是像实时定位,播放音频,以及网络电话这些功能我们需要在后台持续运行。那么我们就要进行相应的设置。 下面具体的例子以定位为例   #import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> @interface Back

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

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

 

#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"



@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

{
    // 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.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  
    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
    { //Check if our iOS version supports multitasking I.E iOS 4
		if ([[UIDevice currentDevice] isMultitaskingSupported])
        { //Check if device supports mulitasking
			UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
            
			__block UIBackgroundTaskIdentifier background_task; //Create a task object
            
			background_task = [application beginBackgroundTaskWithExpirationHandler: ^{
                /*
                 当应用程序后台停留的时间为0时,会执行下面的操作(应用程序后台停留的时间为600s,可以通过backgroundTimeRemaining查看)
                 */
				[application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
				background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
                
				//System will be shutting down the app at any point in time now
			}];
            
			// Background tasks require you to use asyncrous tasks
            
			dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
				//Perform your tasks that your application requires
                NSLog(@"time remain:%f", application.backgroundTimeRemaining);                
				[application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
				background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
			});
		}
	}
    
    
}

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

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

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号