- 程序在前台,这种比较简单。直接使用Darwin层的通知就可以了:(但是这种方法,只能针对不上线的项目来使用,有可能被拒。在17年的时间这个API变成私有的了)
#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,const void*object,CFDictionaryRef userInfo)
{
NSString* lockstate = (__bridge NSString*)name;
if ([lockstate isEqualToString:(__bridgeNSString*)NotificationLock]) {
//如果想做在这里面做一些操作的话,可以用通知来和OC语言来做交互
NSLog(@"locked.");
} else {
// 此处监听到屏幕解锁事件(锁屏也会掉用此处一次,锁屏事件要在上面实现)
NSLog(@"lock state changed.");
}
}
添加通知
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
return YES;
}
2: 还有一种黑客的做法是调节屏幕的亮度,直接上代码
-(void)applicationDidEnterBackground:(NSNotification*)notification {
if ([self didUserPressLockButton]) {
//User pressed lock button
NSLog(@"Lock screen.");
}else{
NSLog(@"Home.");
//user pressed home button
}
}
-(BOOL)didUserPressLockButton{
//获取屏幕亮度
CGFloat oldBrightness = [UIScreen mainScreen].brightness;
//以较小的数量改变屏幕亮度
[UIScreenmainScreen].brightness= oldBrightness + (oldBrightness <=0.01? (0.01) : (-0.01));
CGFloatnewBrightness = [UIScreen mainScreen].brightness;
//恢复屏幕亮度
[UIScreen mainScreen].brightness = oldBrightness;
//判断屏幕亮度是否能够被改变
returnoldBrightness != newBrightness;
}
当用户离开通过锁定按钮而不是主页按钮时,苹果只允许你从applicationDidEnterBackground更改屏幕亮度。这种方法是当APP进入后台时, 以较小的数量改变屏幕亮度,并检查是否能够更改。如果能够更改便是锁定按钮,不能则是主页按钮。经过检测这种方法是可行的,这里讲的是监听锁屏,这个方法同样也可以监听解锁,小编开发的功能是有定时器的,每隔一秒就会执行下didUserPressLockButton这个方法,解锁的时候会同样执行锁屏的语句。
另外网上还有一种方法是通过检测屏幕亮度来判断是锁屏还是按了home键,这种方法是不可以的,因为锁屏之后屏幕的亮度并不为0。
网友评论