background task running on iphone

2019-08-27 16:33发布

问题:

I have some test code which i am using to keep my app to stay running in the background state, which works quite well on the iOS 5.1 simulator but is not behaving that way on the actual device.

Now i already know the requirements i have to follow, so i have set "background modes" to voip and location.

In my delegate's applicationDidEnterBackground method i am calling the following function which i call "doBackgroundActivity( )" to request time for application to complete some long running task in background :

-(void) threadedMethod{    
while(true){
    NSLog(@"looping");            
    [self showLocalNotification:@"This notification will come every 2 min. if the app is running in background. Close it!"];        
    [NSThread sleepForTimeInterval: (5)];        // 60 sec = 1 min
}

}

    -(void) doBackgroundActivity{
        self->_backgroundTask = [ [UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
                [[UIApplication sharedApplication] endBackgroundTask: self->_backgroundTask];
                self->_backgroundTask = UIBackgroundTaskInvalid;
            }
        ];


        [self threadedMethod];



[[UIApplication sharedApplication] endBackgroundTask:self->_backgroundTask];
    self->_backgroundTask = UIBackgroundTaskInvalid;
}

As you see, the doBackgroundAcitivity() just calls the threadedMethod() and all that does is run an infinite loop which sends a local notification every 5 seconds or so.

Now in the simulator when i run this, and minimize the app, i see a notification every 5 seconds or so. The application keeps on running in the background even when i run other applications i see my app sending notifications.

But this is not happening on the device. It looks like that the OS kills the app just after the first notification is send and i dont see any more subsequent notifications which i expect to see later?

Is there something else i have to do to keep the application running in background ?

回答1:

If all you are looking to do is present a notification to the user while your app is closed you should use UILocalNotifications.

You can set when the notification should fire, as well as whether or not it should repeat, and the amount of time between repeats.

As a side note, i wouldn't recommend using sleep() in a loop to control when code is executed like that because it stops the thread from doing anything at all, and is bad for any other tasks that would like to use that thread. Instead you should use NSTimers, and other ways of controlling the time at which code is executed.