5

当应用程序在后台运行/设备处于睡眠模式时,我需要加速器更新。有些应用程序会这样做,我无法让它工作。为此,我在 appdelegate 和 applicationDidEnterBackground 中有一个 CoreMotion 属性,我调用

-(void) startAccelerationUpdates
{

    self.motionManager.deviceMotionUpdateInterval = 0.01;
    [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
                                       withHandler:^(CMDeviceMotion *motion, NSError *error){
         dispatch_async(dispatch_get_main_queue(), ^{
         NSLog(@"acceleration x %f", motion.userAcceleration.x);
         NSLog(@"acceleration y %f", motion.userAcceleration.y);
         NSLog(@"acceleration z %f", motion.userAcceleration.z);
         }
         );
         }
    ];
}

在应用程序列表中,我将所需的后台模式放入应用程序寄存器以进行位置更新。当我将设备置于睡眠模式或后台时,日志中不会出现任何更新。当应用程序激活时,coremotion 开始登录。有人给我提示吗?谢谢你。

4

1 回答 1

0

这是因为您将其分派到主队列。要启用后台活动,您应该将其分派到全局队列:

dispatch_queue_t lowQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_async(lowQueue, ^{ ...

更新添加 Swift 版本:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
    // do some task
}

参考:在一个方法中使用同一个dispatch queue进行后台处理

于 2013-05-20T10:40:13.400 回答