需求:监听手机是否锁屏,开屏。两种状态。
该方法不是私有api。
通过iOS的文件保护机制。使用观察者监听UIApplicationProtectedDataWillBecomeUnavailable和UIApplicationProtectedDataDidBecomeAvailable这两个键。并在app中写一个文件,文件内容随意。
1、 创建一个文件保存到沙盒。
- (void)createProtectedFile {
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *path = [doc stringByAppendingPathComponent:@"pd_test"];
NSDictionary *attr = @{ NSFileProtectionKey : NSFileProtectionComplete };
NSData *data = [@"1" dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager] createFileAtPath:path contents:data attributes:attr];
}
2、使用观察者添加监听
- (void)addObserverForLock() {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(deviceLocked)
name:UIApplicationProtectedDataWillBecomeUnavailable
object:nil];
// 监听解锁
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(deviceUnlocked)
name:UIApplicationProtectedDataDidBecomeAvailable
object:nil];
}
- (void)deviceLocked {
NSLog(@"设备锁屏了");
self.isLock = YES;
}
- (void)deviceUnlocked {
NSLog(@"设备解锁了");
self.isLock = NO;
}
3、并在你的页面viewDidLoad中添加这两段代码
[self createProtectedFile];
[self addObserverForLock];
至此 就可以知道手机是否触发锁屏和解锁了。