我想检测两个事件:
- 设备锁定/解锁。
- 设备进入睡眠状态,屏幕变黑。
你已经基本上有了解决方案,我猜想你是从我的最近的回答中找到的 :)
使用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!");
}
}
#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或其他持久化变量来存储通知令牌(不要只将其作为注册方法中的本地变量!)
int notifyToken;
notify_get_state()
获取的state
变量在0和1之间切换,这将使您区分屏幕开和关事件。notify_get_state()
检索的关联状态。
警告:请参阅此相关问题以了解此最后一种技术的一些复杂性。