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

本文介绍两种在iOS应用中监听音量键变化的方法:使用通知和KVO(Key Value Observing)。通过添加监听器和执行特定方法,开发者可以检测到音量键的触发,包括静音操作。文章还提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一,使用通知:

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.youkuaiyun.com/qq_450351763/article/details/54135615

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值