距离传感器 - (Obj-C)

距离传感器集成在UIDevice类中,Apple电话APP自动开启距离传感器,但是开发者自己的APP需要手动开启距离传感器

开启方式很简单,只需一行代码:

//  开启距离传感器
[UIDevice currentDevice].proximityMonitoringEnabled = YES;

使用场景:
通常是在语音,网络会话时,当手机贴近脸部时,关闭屏幕,或执行某些操作

监听距离变化(通知),使用UIDevice的proximityState属性:

@property(nonatomic,readonly) BOOL proximityState
    //  监听距离的变化(通知)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange) name:UIDeviceProximityStateDidChangeNotification object:nil];
- (void)proximityStateDidChange{
    
    if ([UIDevice currentDevice].proximityState) {
        
        // 近距离
        NSLog(@"滚远点,贴脸上了");
        
    } else {
        
        // 远距离
        NSLog(@"亲爱的,靠近点");
        
    }
}

实例代码:

#import "ViewController.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //  开启距离传感器
    [UIDevice currentDevice].proximityMonitoringEnabled = YES;
    
    //  监听距离的变化(通知)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange) name:UIDeviceProximityStateDidChangeNotification object:nil];
    
}

- (void)proximityStateDidChange{
    
    if ([UIDevice currentDevice].proximityState) {
        
        // 近距离
        NSLog(@"滚远点,贴脸上了");
        
    } else {
        
        // 远距离
        NSLog(@"亲爱的,靠近点");
        
    }
}

@end

还可以通过距离监听,来判断是否禁止自动锁屏,需要使用UIApplication的idleTimerDisabled属性

@property(nonatomic,getter=isIdleTimerDisabled) BOOL idleTimerDisabled;

演示代码:

NSString *sessionType = @"语音";
if ([sessionType isEqualToString:@"语音"]) { //语音
    
    [UIDevice currentDevice].proximityMonitoringEnabled = YES;
    
} else {  //视频
    
    [UIDevice currentDevice].proximityMonitoringEnabled = NO;
    //禁用自动锁屏
    [UIApplication sharedApplication].idleTimerDisabled = YES;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,002评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,107评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,267评论 4 61
  • { 😠、引导界面 sleep(1.5); self.window = [[UIWindow alloc] init...
    CYC666阅读 362评论 0 1
  • 文 宝爱 在候车室,遇到 一位背着行囊 外出打工的姑娘 她站在窗口 在用双手讲话 玻璃窗外,站着 一对聋哑人 背包...
    福星高照_8805阅读 369评论 5 37