iOS开发-检测程序在前台和后台锁屏解锁的状态
Posted sunshine-zzz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS开发-检测程序在前台和后台锁屏解锁的状态相关的知识,希望对你有一定的参考价值。
1、程序在前台判断是否锁屏或解锁。 判断方法:直接使用Darwin层的通知就可以。#import <notify.h>
#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")
#define NotificationChange CFSTR("com.apple.springboard.lockstate")
#define NotificationPwdUI CFSTR("com.apple.springboard.hasBlankedScreen")
static void screenLockStateChanged(CFNotificationCenterRef center,void* observer,CFStringRef name,constvoid* object,CFDictionaryRef userInfo)
NSString* lockstate = (__bridge NSString*)name;
if ([lockstate isEqualToString:(__bridge NSString*)NotificationLock])
// 锁屏
NSLog(@"locked.”);
else
NSLog(@"lock state changed.");
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
// Override point for customization after application launch.
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
//setScreenStateCb();
return YES;
2、程序退后台判断是否锁屏或解锁。
判断方法: 以循环的方式一直来检测是否是锁屏状态,会消耗性能并可能被苹果挂起(慎重);
static void setScreenStateCb()
uint64_t locked;
__block int token = 0;
notify_register_dispatch("com.apple.springboard.lockstate",&token,dispatch_get_main_queue(),^(int t)
);
notify_get_state(token, &locked);
NSLog(@"%d",(int)locked);
- (void)applicationDidEnterBackground:(UIApplication *)application
while (YES)
setScreenStateCb();
sleep(1);
以上是关于iOS开发-检测程序在前台和后台锁屏解锁的状态的主要内容,如果未能解决你的问题,请参考以下文章