当iOS设备进入睡眠模式(屏幕变黑)时,有没有发现事件?

我想要检测两个事件:

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

第一个我已经能够在这里实现: 有没有办法来检查iOS设备是否locking/解锁?

现在我想检测第二个事件,有没有办法做到这一点?

你基本上已经有了解决scheme,我猜你是从我最近的答案中find的:)

使用com.apple.springboard.hasBlankedScreen事件。

当屏幕空白时会发生多个事件,但是这个应该足够了:

 CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center NULL, // observer hasBlankedScreen, // callback CFSTR("com.apple.springboard.hasBlankedScreen"), // event name NULL, // object CFNotificationSuspensionBehaviorDeliverImmediately); 

callback的地方是:

 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在下面的评论中所说的那样,应该很容易跟踪自己是否屏幕正在打开closures 。 这使您可以确定在屏幕开启或closures时是否发生hasBlankedScreen事件。 例如,当您的应用程序启动时,请设置一个variables以指示屏幕处于打开状态。 此外,任何时候发生任何UI交互(按下button等),您都知道屏幕必须处于打开状态。 所以,下一个hasBlankedScreen你应该指出,屏幕是closures的

另外,我想确保我们清楚的术语。 当屏幕由于超时而自动变暗或者用户手动按下电源button时,设备会locking 。 无论用户是否configuration了密码,都会发生这种情况。 那时候,你会看到com.apple.springboard.hasBlankedScreencom.apple.springboard.lockcomplete事件。

当屏幕重新打开时,您将再次看到com.apple.springboard.hasBlankedScreen 。 但是,直到用户实际上用滑动(也许是密码)解锁设备,才会看到com.apple.springboard.lockstate


更新2:

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

 #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或者其他的持久variables来存储通知标记(不要只是在注册的方法中把它作为局部variables)

 int notifyToken; 

您应该看到通过notify_get_state()获取的statevariables,在0和1之间切换,这将使您能够区分屏幕开启和closures事件。

虽然这个文档很老 ,但它列出了哪些通知事件具有可以通过notify_get_state()获取的关联状态。

警告: 看到这个相关的问题,最后一种技术的一些复杂性

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

Interesting Posts