- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceProximityStateDidChangeNotification object:nil];
}
//viewDidLoad:
// 近距离感应主要用的两个属性
// proximityMonitoringEnabled传感器是否可用
// proximityState 传感器感应状态
// 通过通知中心监视传感器状态,事件名是系统给定 UIDeviceProximityStateDidChangeNotification
// 添加近距离事件监听,添加前先设置为YES,如果设置完后还是NO的话,说明当前设备没有近距离传感器
[[UIDevicecurrentDevice]setProximityMonitoringEnabled:YES];
if ([UIDevice currentDevice].proximityMonitoringEnabled == YES)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sensorStateChange:)name:UIDeviceProximityStateDidChangeNotification object:nil];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Warning" message:@"感应器不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
[[UIDevicecurrentDevice]setProximityMonitoringEnabled:NO];
// 删除近距离事件监听
[[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
if ([UIDevice currentDevice].proximityMonitoringEnabled == YES)
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceProximityStateDidChangeNotification object:nil];
}
[[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
//通知中心改变内容:
#pragma mark - 处理近距离监听触发事件
- (void)sensorStateChange:(NSNotificationCenter *)notification;
{
NSLog(@"sensorAvailable");
//如果此时手机靠近面部放在耳朵旁,那么声音将通过听筒输出,并将屏幕变暗(省电啊)
if ([[UIDevice currentDevice] proximityState] == YES) //黑屏
{
NSLog(@"设备靠近用户");
#pragma在这里做屏幕变黑后的操作
NSLog(@"听筒播放");
// [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
}
else //没黑屏幕
{
NSLog(@"设备没有靠近用户");
if (self.PlayerStatus == NO)
{
//没有播放了,也没有在黑屏状态下,就可以把距离传感器关了
NSLog(@"停止播放");
[[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
}
else
{
#pragma在这里做屏幕变亮后的操作
NSLog(@"扬声器播放");
// [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}
}
}