您可以使用Darwin notifications 来监听事件。我不能 100% 确定,但在我看来,在越狱的 iOS 5.0.1 iPhone 4 上运行,这些事件之一可能是你需要的:
com.apple.iokit.hid.displayStatus
com.apple.springboard.hasBlankedScreen
com.apple.springboard.lockstate
注意:根据发帖者的comments to a similar question I answered here,这应该也适用于未越狱的手机。
要使用它,请像这样注册事件(这仅注册一个事件,但如果这对您不起作用,请尝试其他两个):
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
NULL, // observer
displayStatusChanged, // callback
CFSTR("com.apple.iokit.hid.displayStatus"), // event name
NULL, // object
CFNotificationSuspensionBehaviorDeliverImmediately);
displayStatusChanged 是您的事件回调:
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);
}
}
我相信我上面列出的事件会在屏幕同时打开和、锁定和解锁时触发。您可能需要自己跟踪状态。还有,
com.apple.springboard.lockcomplete
仅在屏幕锁定时调用,而不是在解锁时调用。