iOS 監聽音量鍵事件的兩個方法+後臺監聽音量鍵
方法一,使用通知:
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]];
鎖屏監聽音量鍵: