iOS 监听手机息屏、锁屏

集中起来的意志,能够击穿顽石。

前言

视图的生命周期,App的生命周期这已经老生常谈了。手机息屏如果做IM的话会用到,但是监听手机锁屏这个用的有点少了,这不,有可能会用到的就一定会用到。

正文

手机自动感应息屏,以及息屏监听。

- (void)observeSensor {
    //靠近听筒自动息屏
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    //设置监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(sensorStateChange:)
                                                 name:UIDeviceProximityStateDidChangeNotification
                                               object:nil];
}

通知

- (void)sensorStateChange:(NSNotificationCenter *)notification {
    if ([[UIDevice currentDevice] proximityState] == YES) {
        NSLog(@">>>屏幕熄灭");
    }else{
        NSLog(@">>>屏幕亮起");
    }
}

监听手机锁屏

  • 方法一

在类前面声明

#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")
#define NotificationChange CFSTR("com.apple.springboard.lockstate")
#define NotificationPwdUI CFSTR("com.apple.springboard.hasBlankedScreen")

static void screenLockStateChanged(CFNotificationCenterRef center, void * observer,CFStringRef name, const void * object, CFDictionaryRef userInfo) {
    NSString *lockstate = (__bridge NSString *)name;
    if ([lockstate isEqualToString:(__bridge  NSString *)NotificationLock]) {
        NSLog(@">>>locked.");
    } else {
        NSLog(@">>>lock state changed.");
    }
}

使用

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);

特别的:这是私有API,会被拒的
知道其它方法的小伙子积极留言哦

你可能感兴趣的:(iOS 监听手机息屏、锁屏)