在Darwin层建立Notification监听锁屏/解屏事件

判断屏幕锁屏/解锁:

//
//  ViewController.m
//  TestScreenLockDemo
//
//  Created by aaron.zheng on 2015-09-21.
//  Copyright © 2015 aaron.zheng. All rights reserved.
//

#import "ViewController.h"
#include <notify.h>


bool screenLocked;
bool isScreenLocked;
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //锁屏
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, handleLockStateNotification, CFSTR("com.apple.springboard.lockstate"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, handleDisplayStatusNotification, CFSTR("com.apple.iokit.hid.displayStatus"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
}



static void handleLockStateNotification(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    uint64_t state;
    int token;
    notify_register_check("com.apple.springboard.lockstate", &token);
    notify_get_state(token, &state);
    notify_cancel(token);
    if ((uint64_t)1 == state)
    {
        isScreenLocked = true;
    }
    else
    {
        screenLocked = false;
        isScreenLocked = false;
    }
}

static void handleDisplayStatusNotification(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    if (userInfo)
    {
        CFShow(userInfo);
    }
    uint64_t state;
    int token;
    notify_register_check("com.apple.iokit.hid.displayStatus", &token);
    notify_get_state(token, &state);
    notify_cancel(token);
    if ((uint64_t)1 == state)
    {
        screenLocked = true;
    }
    else
    {
        screenLocked = false;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


参考链接:

Is there a way to check if the IOS device locked/unlocked?

SpringBoard.app/Notifications

发布了171 篇原创文章 · 获赞 333 · 访问量 141万+

猜你喜欢

转载自blog.csdn.net/chaoyuan899/article/details/48626889