3

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

但是他们是怎么做到的呢?当我使用 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;
             }
     });        
 }];
4

1 回答 1

-1

要在后台无限运行您的应用程序,您需要在 Info.plist 文件中提供 UIBackgroundModes 值。

https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW20

于 2014-09-04T10:25:40.563 回答