我想检测两个事件:
- 设备被锁定/解锁。
- 设备进入睡眠状态和屏幕变黑。
第一个我已经能够在这里实现: 有没有一种方法来检查,如果iOS设备的锁定/解锁?
现在,我要检测的第二个事件,有没有办法做到这一点?
我想检测两个事件:
第一个我已经能够在这里实现: 有没有一种方法来检查,如果iOS设备的锁定/解锁?
现在,我要检测的第二个事件,有没有办法做到这一点?
你基本上已经有了解决方案,我猜你从我最近的答案之一:)发现
使用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
当屏幕变成开启或关闭的事件正在发生。 例如,你的应用程序启动时,设置一个变量,以指示屏幕上。 此外,任何用户界面交互时(按下按钮等)的任何时间,你知道屏幕目前必须上。 所以,接下来hasBlankedScreen
你应该表明该屏幕是关闭的。
另外,我想确保我们的术语清晰。 当屏幕自动变暗由于超时,或当用户手动按下电源按钮的装置锁定 。 出现这种情况,无论用户是否配置了密码 。 在那个时候,你会看到com.apple.springboard.hasBlankedScreen
和com.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",
¬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");
}
你将需要保持伊娃 ,或一些其他持久变量,来存储通知令牌(不只是使这个在注册方法的局部变量!)
int notifyToken;
你应该看到的state
变量,通过获得notify_get_state()
,0和1之间切换,这将让你打开和关闭屏幕事件区分。
虽然这个文件是很老 ,但它确实列表,它通知事件都可以通过检索相关联的状态notify_get_state()
。
警告: 看到此相关的问题对一些并发症的这最后一个技术
您也可以订阅一个通知:“com.apple.springboard.lockstate”,并使用API SBGetScreenLockStatus来确定设备状态是否被锁定或没有。