Tools & releasesHistorical technical note
Detecting device locking in an iOS app
Records SpringBoard lock-notification handling used to investigate a failure in an embedded game when the device locked. It preserves the troubleshooting approach and callback code; the conditions under which those interfaces may be used need separate verification.
Originally credited to Bison. Content is retained as published.
On this page
"Health is the foundation of everything. Getting more exercise is the way to go." Bison
A recent project contains an embedded game, and the app crashes as soon as the screen locks. I spent a long time looking for a solution.
The code is as follows
Core code
#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")
#define NotificationChange CFSTR("com.apple.springboard.lockstate")
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self lookLockScreen];
return YES;
}
- (void)lookLockScreen
{
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
}
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.");
}
}