有没有办法像“举手发言”功能一样监控用户的 iPhone 移动情况?

2024-04-20

我想在用户将 iPhone 举到脸上时收到通知。就像 Siri 一样。是否可以?

添加更具体的要求: 当用户将手机放在耳朵附近时,我想使屏幕变暗。我知道可以启用接近传感器来实现这一点。但令人烦恼的是,当用户在传感器上移动手指时,屏幕会时不时变暗。所以我想知道如何避免这种情况,并且只在用户举起iPhone说话时使屏幕变暗?


See 使用接近传感器 http://developer.apple.com/library/ios/documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/doc/uid/TP40006902-CH3-SW29 in the UIDevice 类参考。那么你:

  • 启用它:

    UIDevice *device = [UIDevice currentDevice];
    device.proximityMonitoringEnabled = YES;
    
  • 检查是否成功启用;观察UIDeviceProximityStateDidChangeNotification http://developer.apple.com/library/ios/documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/doc/uid/TP40006902-CH3-SW2如果成功则通知;如果没有,您的设备可能无法:

    if (device.proximityMonitoringEnabled)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleProximityChange:)
                                                     name:UIDeviceProximityStateDidChangeNotification
                                                   object:nil];
    }
    else
    {
         // device not capable
    }
    
  • 并写下你的选择器:

    - (void)handleProximityChange:(NSNotification *)notification
    {
        NSLog(@"%s proximityState=%d", __FUNCTION__, [[UIDevice currentDevice] proximityState]);
    }
    

为了检测用户是否将其举到脸上,我可能会将接近传感器与CMMotionManager并看看gravity财产,看看他们是否几乎垂直地拿着手机。因此,定义一些类属性:

@property (nonatomic, strong) CMMotionManager *motionManager;
@property (nonatomic, strong) NSOperationQueue *deviceQueue;

然后你就可以开始CMMotionManager,检查设备是否处于垂直位置:

self.deviceQueue = [[NSOperationQueue alloc] init];
self.motionManager = [[CMMotionManager alloc] init];
self.motionManager.deviceMotionUpdateInterval = 5.0 / 60.0;

UIDevice *device = [UIDevice currentDevice];

[self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryZVertical
                                                        toQueue:self.deviceQueue
                                                    withHandler:^(CMDeviceMotion *motion, NSError *error)
{
    BOOL vertical = (motion.gravity.z > -0.4 && motion.gravity.z < 0.4 & motion.gravity.y < -0.7);
    if ((vertical && !device.proximityMonitoringEnabled) || (!vertical && device.proximityMonitoringEnabled))
    {
        device.proximityMonitoringEnabled = vertical;
    }
}];

无论是这些gravity阈值是否有意义有点主观。您还可以查看其他加速度计数据(例如,它们是否举起物体),而不仅仅是查看手机是否大致垂直握持。看来剥猫皮的方法有很多种。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法像“举手发言”功能一样监控用户的 iPhone 移动情况? 的相关文章

随机推荐