14

我想检测两个事件:

  1. 设备被锁定/解锁。
  2. 设备进入睡眠状态,屏幕变黑。

我在这里能够实现的第一个: 有没有办法检查 iOS 设备是否被锁定/解锁?

现在我想检测第二个事件,有什么办法吗?

4

2 回答 2

22

你基本上已经有了解决方案,我猜你是从我最近的一个答案中找到的:)

使用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.hasBlankedScreencom.apple.springboard.lockcomplete事件。

当屏幕重新打开时,您将com.apple.springboard.hasBlankedScreen再次看到。com.apple.springboard.lockstate但是,在用户通过滑动(可能还有密码)实际解锁设备之前,您不会看到。


更新 2:

还有另一种方法可以做到这一点。您可以使用一组备用 API 来侦听此通知,并在通知到来时获取状态变量:

#import <notify.h>

int status = notify_register_dispatch("com.apple.springboard.hasBlankedScreen",
                                      &notifyToken,
                                      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或其他一些持久变量来存储通知令牌(不要只是在注册的方法中将其设为局部变量!)

int notifyToken;

您应该看到state通过 获得的变量notify_get_state()在 0 和 1 之间切换,这将使您能够区分屏幕开启和关闭事件。

虽然这个文档很旧,但它确实列出了哪些通知事件具有可以通过 检索的关联状态notify_get_state()

警告: 有关最后一种技术的一些并发症,请参阅此相关问题

于 2013-01-16T11:39:09.997 回答
1

您还可以订阅通知:“com.apple.springboard.lockstate”并使用 API SBGetScreenLockStatus来确定设备是否被锁定。

于 2013-01-16T16:33:50.193 回答