IOS监听屏幕状态

时间:2023-03-10 01:04:45
IOS监听屏幕状态

一、定义两个宏

 

//锁屏通知

#define NotificationOff CFSTR("com.apple.springboard.lockcomplete")

 

//解锁通知

#define NotificationOn CFSTR("com.apple.springboard.hasBlankedScreen")

 

二、注册屏幕监听事件

 

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, ListeningScreenLockState, NotificationOff, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);

    

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, ListeningScreenLockState, NotificationOn, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);

 

三、屏幕监听的事件

 

static void ListeningScreenLockState(CFNotificationCenterRef center,void* observer,CFStringRef name,const void* object,CFDictionaryRef userInfo)

 

{

    

    NSString* screenState = (__bridge NSString*)name;

    

    if ([screenState isEqualToString:(__bridge  NSString*)NotificationOff]) {

        

        NSLog(@"********锁屏**********");

        

    } else {

        

        NSLog(@"********解锁**********");

        

    }

    

}