私有API (慎用 不上appstore的话就可以用)
//AppDelegate.m
//监听锁屏事件
#define kNotificationLock CFSTR("com.apple.springboard.lockcomplete")
//监听屏幕状态变化事件
#define kNotificationChange CFSTR("com.apple.springboard.lockstate")
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//监听锁屏事件
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, kNotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
//监听屏幕状态变化事件
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, kNotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
return YES;
}
static void screenLockStateChanged(CFNotificationCenterRef center,void* observer,CFStringRef name,const void* object,CFDictionaryRef userInfo){
NSString* lockstate = (__bridge NSString*)name;
if ([lockstate isEqualToString:(__bridge NSString*)kNotificationLock]) {
NSLog(@"锁屏");
}
else{
NSLog(@"解锁");
}
}
红外线传感器判断是否息屏
//传感器(红外感应)打开 打开才能监听 适当的时机去关闭就ok
[[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(@"亮屏");
}
}
App不熄屏设置 适用于直播等长时间在activity的场景
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
网上说监听这两个通知可以监听到锁屏和解锁的回调, 实际上聊胜于无 (屁都没有)
UIApplicationProtectedDataWillBecomeUnavailable
UIApplicationProtectedDataDidBecomeAvailable
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(LOCK_SCREEN:)
name:UIApplicationProtectedDataWillBecomeUnavailable
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(UN_LOCK_SCREEN:)
name:UIApplicationProtectedDataDidBecomeAvailable
object:nil];