iOS开发——锁屏监听

第一步:AppDelegate.m 头部导入#import#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")

#define NotificationChange CFSTR("com.apple.springboard.lockstate")

#define NotificationPwdUI CFSTR("com.apple.springboard.hasBlankedScreen")

第二步:在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法内加入

以下代码

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);

第三步:在appDelege.m中加入新的方法(C语言的)

static void screenLockStateChanged(CFNotificationCenterRef center,void* observer,CFStringRef name,const void* object,CFDictionaryRef userInfo)

{

NSString* lockstate = (__bridge NSString*)name;

if ([lockstate isEqualToString:(__bridge  NSString*)NotificationLock]) {

NSLog(@"locked.");

// 此处监听的系统锁屏

} else {

NSLog(@"lock state changed.");

// 此处监听到屏幕解锁事件(锁屏也会掉用此处一次,锁屏事件要在上面实现)

}

}

第四步:如何在C语言函数内调用OC方法  ( C语言函数内没法使用self )

本例为了实现在appDelegate.m中通过self 调用一个方法(弹出手势解锁的方法)

本质是通过指针来实现

1. 声明一个全局变量,并赋nil

AppDelegate *appDelegate = nil;

2. 在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法内如下赋值:

appDelegate = self;

3.在刚才的锁屏监听的C语言函数内如下调用appDelegate OC方法,这样就不会因为self导致报错了

[appDelegate showGestureOrFinger];

你可能感兴趣的:(iOS开发——锁屏监听)