Accelerate not getting called when accelerometer initialized within beginBackgroundTaskWithExpirationHandler?
In my app, I want to r开发者_StackOverflow中文版ecord the accelerometer data when the app enters background (expiration time granted by the system will be enough). I have coded this as follows:
- (void)applicationDidEnterBackground:(UIApplication *)application {
UIDevice* device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)])
backgroundSupported = device.multitaskingSupported;
if (backgroundSupported) {
UIApplication* app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
// Do the work associated with the task.
if ([application backgroundTimeRemaining] > 1.0 ) {
UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = kUpdateInterval;
}
});
In the delegate I mentioned like:
- (void) accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)acceleration {
if (acceleration.x > kAccelerationThreshold ||
acceleration.y > kAccelerationThreshold ||
acceleration.z > kAccelerationThreshold) {
NSLog(@"Sensed acceleration");
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
However, didAccelerate doesn't get triggered when the app enters background, rather it gets called after applicationWillEnterForeground. After the app gets relaunched ( from background ), didAccelerate seems to get fired multiple times ( possibly, the number of times accelerometer value changed when in background ). The request seems to get piled up and executed when app comes to foreground.
Is there any way I can record the accelerometer value when the app is in background state ( inside beginBackgroundTaskWithExpirationHandler )
Please help.
Your code is run as-is and then the application exit continues normally. In other words, your accelerometer related code is not synchronious and thus will not block exit process.
Read again the comment:
// Start the long-running task and return immediately.
Your task is not a "long-running" one, unfortunately.
精彩评论