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

标签 iphone ios background accelerometer multitasking

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

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

最佳答案

关于iphone - iOS 加速度计在后台(无限),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17042961/

相关文章:

iphone - 与另一个 UITableview 同时滚动其他 UITableview

wpf - 使用 XAML 图像作为 WPF 窗口背景

css - 大背景图像和屏幕尺寸

iphone - 将多对多关系迁移到 Core Data 中的连接表

iOS 在没有确认提示的情况下从应用程序调用电话

iphone - 在 iOS 应用程序的 XCode 6.1 中设置 Launchimage 时出现错误

ios - Swift4 - 分页

jQuery UI slider 背景

iphone - 删除 UITableView 中 2 个部分之间的标题空间

iphone - 将 NSData 加载到 UIWebView