如何检测iPhone上的屏幕锁定/解锁事件?

Vik*_*ngh 15 events objective-c unlock ios

如何检测iPhone上的屏幕锁定/解锁事件?当用户解锁时,我想从我的iPhone应用程序显示通知提醒.(就像在Android中用于屏幕解锁的广播接收器一样.)

Roh*_*yap 24

看看这个,我想检测锁定/解锁事件,我通过达尔文通知解决了它.您可以在设备被锁定时检测到事件"com.apple.springboard.lockcomplete".

//call back
static void displayStatusChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    // the "com.apple.springboard.lockcomplete" notification will always come after the "com.apple.springboard.lockstate" notification

    NSString *lockState = (NSString*)name;
    NSLog(@"Darwin notification NAME = %@",name);

    if([lockState isEqualToString:@"com.apple.springboard.lockcomplete"])
    {
        NSLog(@"DEVICE LOCKED");
    }
    else
    {
        NSLog(@"LOCK STATUS CHANGED");
    }   
}


-(void)registerforDeviceLockNotif
{
    //Screen lock notifications
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                    NULL, // observer
                                    displayStatusChanged, // callback
                                    CFSTR("com.apple.springboard.lockcomplete"), // event name
                                    NULL, // object
                                    CFNotificationSuspensionBehaviorDeliverImmediately);

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                    NULL, // observer
                                    displayStatusChanged, // callback
                                    CFSTR("com.apple.springboard.lockstate"), // event name
                                    NULL, // object
                                    CFNotificationSuspensionBehaviorDeliverImmediately);  
}   
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案似乎不再可用.https://forums.developer.apple.com/message/224401#224401 (2认同)

Nek*_*kto 1

可能您需要在中实现以下方法AppDelegate

告诉委托人应用程序现在处于后台。

- (void)applicationDidEnterBackground:(UIApplication *)application
Run Code Online (Sandbox Code Playgroud)

告诉委托人应用程序已变为活动状态。

- (void)applicationDidBecomeActive:(UIApplication *)application
Run Code Online (Sandbox Code Playgroud)

告诉委托人应用程序即将变为非活动状态。

- (void)applicationWillResignActive:(UIApplication *)application
Run Code Online (Sandbox Code Playgroud)