2012-11-23 45 views
0

我想使用後臺gps背景,並設置應用程序寄存器以進行位置更新。 我想我的應用程序沒有被系統殺死,但是當10分鐘我的應用程序關閉。應用程序在後臺取消

我的代碼是:

#import "AppDelegate.h" 
    #import "ViewController.h" 

    @implementation AppDelegate 
    @synthesize locationManager; 

    - (void)dealloc 
    { 
    [_window release]; 
     [_viewController release]; 
     [super dealloc]; 
    } 

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                 NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentDir = [paths objectAtIndex:0]; 
    NSString *logPath = [documentDir stringByAppendingPathComponent:@"decrypt.log"]; 
    freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding], "w", stderr); 


    timer_public = [NSTimer scheduledTimerWithTimeInterval:5*60 
                target:self 
                selector:@selector(locationManagerDidTimeout) 
                userInfo:nil 
                repeats:YES]; 

    self.locationManager = [[CLLocationManager alloc] init]; 
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; 
    //self.locationManager.distanceFilter = kCLDistanceFilterNone; //report all movement 
    self.locationManager.distanceFilter = 1; //report all movement 
    self.locationManager.delegate = self; 
    [self.locationManager startUpdatingLocation]; 

    late=0; 

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; 
    // Override point for customization after application launch. 
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; 
    self.window.rootViewController = self.viewController; 
    [self.window makeKeyAndVisible]; 
    return YES; 
    } 

    -(void)showNotificationWithAlertBody:(NSString *)alertBody object:(id)object objectkey:(NSString *)objectkey{ 

    UILocalNotification *alarm = [[UILocalNotification alloc] init]; 
    if (alarm) { 
     alarm.fireDate = [NSDate date]; 
     alarm.timeZone = [NSTimeZone defaultTimeZone]; 
     alarm.repeatInterval = 0; 
     alarm.soundName = UILocalNotificationDefaultSoundName; 
     alarm.alertBody =[NSString stringWithFormat:@" %f",[[UIDevice currentDevice]batteryLevel]]; 
     // alarm.alertAction 

     //  NSDictionary *infoDic = [NSDictionary dictionaryWithObject:object forKey:objectkey]; 
     //  alarm.userInfo = infoDic; 

     //  UIApplication *app = [UIApplication sharedApplication]; 
     //  [app scheduleLocalNotification:alarm]; 
     NSLog(@"alarm=%@",alarm); 
     [[UIApplication sharedApplication] presentLocalNotificationNow:alarm]; 
    } 
    } 
    -(NSString *)returnTime_All:(NSDate *)date{ 

    NSDate *dateStr=[NSDate dateWithTimeIntervalSince1970:[date timeIntervalSince1970]]; 
    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init]autorelease] ; 
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
    NSString *strDate=[formatter stringFromDate:dateStr]; 
    return strDate; 

    } 

    -(void)locationManagerDidTimeout 
    { 

     NSLog(@"time=%@", [self returnTime_All:[NSDate date] ]); 
     } 

     //retrieve the coordinate 
     - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
     { 
      NSLog(@"++++++++++++++++"); 
      NSTimeInterval new=[[NSDate date] timeIntervalSince1970]; 

      NSTimeInterval cha=new-late; 
      if(cha>=5*60){ 

      // if ([newLocation horizontalAccuracy] > 0.0f && [newLocation horizontalAccuracy] <= 100.0f) 
      // { 
         late=[[NSDate date] timeIntervalSince1970]*1; 
        NSString *strLoc=[NSString stringWithFormat:@"latitude=%f longitude=%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]; 
        NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"www.baidu.com"]]; 

        NSString *str=[[NSString alloc]initWithData:imgData encoding:NSUTF8StringEncoding]; 
        NSLog(@"str=%@",str); 
        [self showNotificationWithAlertBody:strLoc object:nil objectkey:nil]; 
      } 
     } 

    - (void)backgroundHandler { 

    NSLog(@"### -->backgroundinghandler"); 

    UIApplication* app = [UIApplication sharedApplication]; 

    __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
     [app endBackgroundTask:bgTask]; 
     bgTask = UIBackgroundTaskInvalid; 
    }]; 

    // Start the long-running task 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     [self.locationManager stopMonitoringSignificantLocationChanges]; 
     self.locationManager.delegate=self; 
     [self.locationManager startUpdatingLocation]; 
     [NSThread sleepForTimeInterval:2]; 
     [self.locationManager stopUpdatingLocation]; 
     }); 
    } 

    - (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. 
    */ 
    // [ self.locationManager stopUpdatingLocation]; 
    // [self.locationManager startMonitoringSignificantLocationChanges]; 

    late=[[NSDate date] timeIntervalSince1970]; 
    BOOL isInBackground = YES; 
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) 
    { 
     isInBackground = YES;   
     [self backgroundHandler];  
    } 
    } 

     - (void)applicationWillEnterForeground:(UIApplication *)application 
     { 
     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 


    if (self.locationManager==nil) { 
     self.locationManager = [[CLLocationManager alloc] init]; 
     // self.locationManager.distanceFilter = kCLDistanceFilterNone; //report all movement 
     [self.locationManager stopMonitoringSignificantLocationChanges]; 
     [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];//精確度 

    } 
     [self.locationManager stopMonitoringSignificantLocationChanges]; 
     self.locationManager.delegate=self; 
     [self.locationManager startUpdatingLocation]; 
    } 

     - (void)applicationDidBecomeActive:(UIApplication *)application 
     { 
     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
     } 

    - (void)applicationWillTerminate:(UIApplication *)application 
    { 
     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 

     NSLog(@"### -->applicationWillTerminate"); 
    } 

    @end 
+0

您是否編輯了您的info.plist以允許在後臺進行位置更新? – ekims

+0

是的,我已經添加它 – pengwang

回答

1

使用定時器(當應用程序進入後臺時暫停)將是一個錯誤的方法。

蘋果強烈反對你的應用程序的自終止,因爲用戶可能會得到一個錯誤的印象,你的應用程序崩潰(然後留下不好的反饋或評論有關應用程序商店中的應用)。

如果你真的要做到這一點,我會做到這一點的方法是 - 無論是在啓動時或當應用程序進入後臺 - 設置你的應用程序的一個變量或屬性是一個約會10分鐘到未來。

當您在後臺模式下獲得核心位置/ GPS更新時,如果當前日期/時間超出了之前保存的日期,那麼應用程序可以終止。

+0

你可以給一些代碼,當我只使用[self.locationManager stopUpdatingLocation]一切正常。但是當我使用[self.locationManager stopUpdatingLocation]; [self.locationManager startMonitoringSignificantLocationChanges];我的應用程序已關閉 – pengwang