Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8877725
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T19:32:10+00:00 2026-06-14T19:32:10+00:00

I want to use background gps background, and I set the App registers for

  • 0

I want to use background gps background, and I set the App registers for location updates .
I want to my app is not killed by system, but when 10min my app is close.

my code is:

    #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
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T19:32:11+00:00Added an answer on June 14, 2026 at 7:32 pm

    Using a timer (which suspends when the app goes into the background) would be a wrong approach.

    Apple strongly recommends against self termination of your app, since users might get a wrong impression that your app crashed (and then leave bad feedback or reviews about your app on the app store).

    If you really want to do this, the way I would do this would be — at either launch time or when the app goes into the background — to set a variable or property of your app to be a date 10 minutes into the future.

    When you get a Core Location / GPS update in background mode, if the current date/time is beyond that date you saved previously, then the app can terminate.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to use a set of 2 image layers as a background in
I don't often use background-position, so maybe I'm not doing this correctly, but my
I want to use background image and color for the same element but id
I use emacs in ubuntu 12.04. i want define some background or foreground in
I want use BYTE_ORDER macro in my Xcode project but i can't because i
I want use JQuery mobile for the front-end of my mobile application, but I
I have an image that I want to use as the background of my
I want to use a background image (/images/background.jpg) in all tabs, except the tab
I want to use my self background for my UIToolbar. To do that with
I want to use background-color of the body and to apply it to the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.