距离传感器 Proximity Sensor

2015-11-26  本文已影响619人  redye

作用

用于检测是否有物体靠近设备屏幕

  1. 节省电量
  2. 防止耳朵或面部不小心触摸而引发一些不想要的意外操作
4FF4785F-1BF1-48FD-956E-C5FBF7A5BC19.png

所以要先判断当前设备是否支持 proximity Sensor
看代码
- (void)viewDidLoad {
[super viewDidLoad];
//判断当前设备是否支持
if ([UIDevice currentDevice].proximityMonitoringEnabled) {
//开启距离感应功能
[[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
//监听距离感应的通知,如果你想在有物体靠近屏幕的时候 do something,可以在通知的检测方法里进行
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityChange:) name:UIDeviceProximityStateDidChangeNotification object:nil];
}
}

- (void)proximityChange:(NSNotification *)notification {
    // 判断当前设备距离传感器的状态来获得是否有物体靠近屏幕
    if ([UIDevice currentDevice].proximityState) {
        NSLog(@"某个物体靠近了设备屏幕");   //屏幕接收到通知,判断如果当前有物体靠近,则关闭屏幕,使屏幕处于黑屏状态
    } else {
        NSLog(@"某个物体原理了设备屏幕");  //启动屏幕、点亮屏幕
    }
} 

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
上一篇 下一篇

猜你喜欢

热点阅读