首页 文章

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

提问于
浏览
15

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

4 回答

  • 23

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

    告诉代表该应用程序现在在后台 .

    - (void)applicationDidEnterBackground:(UIApplication *)application
    

    告诉代表该应用程序已变为活动状态 .

    - (void)applicationDidBecomeActive:(UIApplication *)application
    

    告诉代表该应用程序即将变为非活动状态 .

    - (void)applicationWillResignActive:(UIApplication *)application
    
  • -2

    实际上我想要退出应用程序并锁定iPhone,过了一段时间我解锁iPhone,然后退出应用程序显示通知或提醒启动应用程序 .

    你不能在iPhone上这样做 .

  • 3

    看看这个,我想检测锁定/解锁事件,我通过达尔文通知解决了它 . 您可以通过 "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);  
    }
    
  • 1

    从当前视图控制器中,您应该为UIApplicationDidEnterBackgroundNotification添加一个观察者,并在解除视图控制器时删除观察者 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];

相关问题