今天在研究获取是否锁屏状态,没找到方法。有找到的说要越狱,没越狱的方法又只能获取到响应通知,不能识别是锁还是解。无意间看到这么个文章,测试了一下真机可以运行就收藏留着后面备用吧!(测试环境:iPhone5s)
原文来自:http://wangqingpeng.info/blog/2013/11/04/huo-qu-and-qu-fen-iossuo-ping-yu-homeshi-jian/
//put this in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
NULL,
displayStatusChanged,
CFSTR("com.apple.springboard.lockcomplete"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
//put this function in AppDelegate
static void displayStatusChanged(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo) {
if (name == CFSTR("com.apple.springboard.lockcomplete")) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"kDisplayStatusLocked"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
//put this in onAppEnterBackground
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateInactive) {
NSLog(@"Sent to background by locking screen");
} else if (state == UIApplicationStateBackground) {
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"kDisplayStatusLocked"]) {
NSLog(@"Sent to background by home button/switching to other app");
} else {
NSLog(@"Sent to background by locking screen");
}
}
//put this in - (void)applicationWillEnterForeground:(UIApplication *)application
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"kDisplayStatusLocked"];
[[NSUserDefaults standardUserDefaults] synchronize];
上面那个只能响应锁屏、点击home键进入后台。
以下是自己综合网上的写出来的方法。
原文参考:http://blog.csdn.net/feng3327/article/details/8859478
通知方式判断解锁/锁屏:目前我只能在运行当前demo的时候响应通知,不能获取到状态,初步考虑是认为加入bool判断(因为,我觉得锁屏、解锁跟开关值是一个意思)。废话有点多,先上代码:
//这段写在:- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, updateEnabled, CFSTR("com.apple.iokit.hid.displayStatus"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
//这段写在:AppDelegate 下
static void updateEnabled(CFNotificationCenterRef center, void* observer, CFStringRef name, const void* object, CFDictionaryRef userInfo) {
NSLog(@"锁屏/解锁");
}