近距离感应 传感器 iOS开发

- (void)dealloc

{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceProximityStateDidChangeNotification object:nil];


}


//viewDidLoad:


//   近距离感应主要用的两个属性

//   proximityMonitoringEnabled 传感器是否可用

//   proximityState                传感器感应状态


//   通过通知中心监视传感器状态,事件名是系统给定                        UIDeviceProximityStateDidChangeNotification

//   添加近距离事件监听,添加前先设置为YES,如果设置完后还是NO 话,说明当前设备没有近距离传感器

       [[UIDevice currentDevice] 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];

        }

       [[UIDevice currentDevice] 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];


        }

    }

}







  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值