iOS加速度计在后台(无限)

时间:2013-06-11 11:27:17

标签: iphone ios background accelerometer multitasking

我希望我的应用能够无限时间监控我的加速度计(即使在后台)。当它达到一定数量时,我想发送一个本地通知。这与“睡眠周期”应用程序具有完全相同的功能。

但是他们是怎么做到的?当我使用beginBackgroundTaskWithExpirationHandler函数时,它在10分钟后不再工作。添加UIBackgroundModes根本没有帮助。

UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

_motionManager = [[CMMotionManager alloc] init];
_motionManager.accelerometerUpdateInterval = 1;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[_motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error)
 {
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         NSLog(@"%@",accelerometerData);
             if(accelerometerData.acceleration.x > 0.5){

                 UILocalNotification *localNotif = [[UILocalNotification alloc] init];

                 if (localNotif == nil)
                     return;

                 localNotif.fireDate = [NSDate date];
                 localNotif.timeZone = [NSTimeZone defaultTimeZone];

                 localNotif.alertBody = @"Wake up!";
                 localNotif.alertAction = @"wake";

                 localNotif.soundName = UILocalNotificationDefaultSoundName;
                 localNotif.applicationIconBadgeNumber = 4;

                 [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
                 [app endBackgroundTask:bgTask];
                 bgTask = UIBackgroundTaskInvalid;
             }
     });        
 }];

1 个答案:

答案 0 :(得分:-1)

相关问题