CMMotionManager检测设备何时静止不动

时间:2013-10-02 19:18:15

标签: cocoa-touch core-motion

如何设置处理,以便我可以检测设备何时静止不动(在某个阈值中)

下面的代码没有按预期工作(userAcceleration只是更加严格,取决于设备方向,用户甚至不移动设备(此值可能来自重力))

self.motionManager = [[CMMotionManager alloc] init];
        self.motionManager.accelerometerUpdateInterval = 1/2.0;
        [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {

            float accelerationThreshold = 0.75;
            CMAcceleration userAcceleration = accelerometerData.acceleration;
            if ((fabs(userAcceleration.x) > accelerationThreshold)
                || (fabs(userAcceleration.y) > accelerationThreshold)
                || (fabs(userAcceleration.z) > accelerationThreshold)) {
                self.deviceMoved = YES;
            } else {
                self.deviceMoved = NO;
            }

        }];

1 个答案:

答案 0 :(得分:1)

需要使用startDeviceMotionUpdatesToQueue

if (self.motionManager == nil) {
        self.motionManager = [[CMMotionManager alloc] init];
        self.motionManager.accelerometerUpdateInterval = 1/2.0;
        [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {

            float accelerationThreshold = 0.25;
            CMAcceleration userAcceleration = motion.userAcceleration;
            if ((fabs(userAcceleration.x) > accelerationThreshold)
                || (fabs(userAcceleration.y) > accelerationThreshold)
                || (fabs(userAcceleration.z) > accelerationThreshold)) {
                self.deviceMoved = YES;
            } else {
                self.deviceMoved = NO;
            }

        }];
    }