iOS 监听音量键事件的两个方法+后台监听音量键

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_31177681/article/details/83058003

方法一,使用通知:

1、添加监听

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeDidChange:)name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

2、添加执行方法

- (void)volumeDidChange:(NSNotification *)notification

{

    DDLogInfo(@"%@-%@,点击音量键静音", THIS_FILE, THIS_METHOD);

}

3、销毁的时候,移除监听

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];

 [[UIApplication sharedApplication] endReceivingRemoteControlEvents];

方法二,使用KVO:

1、添加KVO

[[AVAudioSession sharedInstance] addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:(void *)[AVAudioSession sharedInstance]];
 

2、实现方法

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if(context == (__bridge void *)[AVAudioSession sharedInstance]){
        float newValue = [[change objectForKey:@"new"] floatValue];
        float oldValue = [[change objectForKey:@"old"] floatValue];
        // TODO: 这里实现你的逻辑代码
    }
}

3、销毁的时候,移除KVO

[[AVAudioSession sharedInstance] removeObserver:self forKeyPath:@"outputVolume" context:(void *)[AVAudioSession sharedInstance]];

锁屏监听音量键:

https://blog.csdn.net/qq_450351763/article/details/54135615

猜你喜欢

转载自blog.csdn.net/sinat_31177681/article/details/83058003