您基本上已经有了解决方案,我猜您是从我最近的一个答案中找到的 :)
使用com.apple.springboard.hasBlankedScreen 事件。
当屏幕空白时会发生多个事件,但这一个就足够了:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
NULL, // observer
hasBlankedScreen, // callback
CFSTR("com.apple.springboard.hasBlankedScreen"), // event name
NULL, // object
CFNotificationSuspensionBehaviorDeliverImmediately);
回调在哪里:
static void hasBlankedScreen(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
NSString* notifyName = (__bridge NSString*)name;
// this check should really only be necessary if you reuse this one callback method
// for multiple Darwin notification events
if ([notifyName isEqualToString:@"com.apple.springboard.hasBlankedScreen"]) {
NSLog(@"screen has either gone dark, or been turned back on!");
}
}
更新:正如@VictorRonin 在下面的评论中所说,应该很容易跟踪屏幕当前是打开还是关闭。这使您可以确定屏幕打开或关闭时是否正在发生hasBlankedScreen 事件。例如,当您的应用启动时,设置一个变量以指示屏幕处于打开状态。此外,任何时候发生任何 UI 交互(按下按钮等),您都知道当前必须打开屏幕。因此,您收到的下一个hasBlankedScreen 应该表明屏幕已关闭。
另外,我想确保我们清楚术语。当屏幕因超时自动变暗或用户手动按下电源按钮时,设备锁定。无论用户是否配置了密码,都会发生这种情况。届时,您将看到com.apple.springboard.hasBlankedScreen 和com.apple.springboard.lockcomplete 事件。
当屏幕重新打开时,您将再次看到com.apple.springboard.hasBlankedScreen。但是,在用户通过滑动(可能还有密码)实际解锁设备之前,您不会看到 com.apple.springboard.lockstate。
更新 2:
还有另一种方法可以做到这一点。您可以使用一组备用 API 来侦听此通知,也可以在通知到来时使用 get a state variable:
#import <notify.h>
int status = notify_register_dispatch("com.apple.springboard.hasBlankedScreen",
¬ifyToken,
dispatch_get_main_queue(), ^(int t) {
uint64_t state;
int result = notify_get_state(notifyToken, &state);
NSLog(@"lock state change = %llu", state);
if (result != NOTIFY_STATUS_OK) {
NSLog(@"notify_get_state() not returning NOTIFY_STATUS_OK");
}
});
if (status != NOTIFY_STATUS_OK) {
NSLog(@"notify_register_dispatch() not returning NOTIFY_STATUS_OK");
}
您需要保留一个 ivar 或其他一些 persistent 变量来存储通知令牌(不要只在方法中将其设为局部变量)注册!)
int notifyToken;
您应该看到通过notify_get_state() 获得的state 变量在0 和1 之间切换,这可以让您区分屏幕开启和关闭事件。
尽管this document is very old,它确实列出了哪些通知事件具有可以通过notify_get_state()检索的关联状态。
警告: see this related question for some complications with this last technique