且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 iOS 服务检测屏幕开/关

更新时间:2023-11-18 13:24:04

您可以使用 达尔文通知,监听事件.我不是 100% 肯定,但在我看来,从在越狱的 iOS 5.0.1 iPhone 4 上运行来看,这些事件之一可能是您所需要的:

You can use Darwin notifications, to listen for the events. I'm not 100% sure, but it looks to me, from running on a jailbroken iOS 5.0.1 iPhone 4, that one of these events might be what you need:

com.apple.iokit.hid.displayStatus
com.apple.springboard.hasBlankedScreen
com.apple.springboard.lockstate

更新:此外,当手机锁定时(而不是解锁时)会发布以下通知:

Update: also, the following notification is posted when the phone locks (but not when it unlocks):

com.apple.springboard.lockcomplete

要使用它,请像这样注册事件(这仅注册一个事件,但如果这对您不起作用,请尝试其他事件):

To use this, register for the event like this (this registers for just one event, but if that doesn't work for you, try the others):

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                NULL, // observer
                                displayStatusChanged, // callback
                                CFSTR("com.apple.iokit.hid.displayStatus"), // event name
                                NULL, // object
                                CFNotificationSuspensionBehaviorDeliverImmediately);

其中 displayStatusChanged 是您的事件回调:

where displayStatusChanged is your event callback:

static void displayStatusChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    NSLog(@"event received!");
    // you might try inspecting the `userInfo` dictionary, to see 
    //  if it contains any useful info
    if (userInfo != nil) {
        CFShow(userInfo);
    }
}

如果您真的希望此代码作为服务在后台运行,并且您已越狱,我建议您查看 iOS 启动守护程序.与您简单地在后台运行的应用相反,启动守护程序可以在重新启动后自动启动,而且您不必担心应用在后台运行任务的 iOS 规则.

If you really want this code to run in the background as a service, and you're jailbroken, I would recommend looking into iOS Launch Daemons. As opposed to an app that you simply let run in the background, a launch daemon can start automatically after a reboot, and you don't have to worry about iOS rules for apps running tasks in the background.

让我们知道这是如何工作的!

Let us know how this works!