2017-05-19 258 views
0

我知道有屏幕開/關事件時可以註冊事件偵聽器。如果我想檢查當前屏幕是打開還是關閉,該怎麼辦?任何方法讓我檢查它?檢查當前屏幕在iOS中是打開還是關閉

如果我使用通知來檢查,這裏是將要發生的事件:

當我鎖定屏幕。這將觸發

---接到通知:com.apple.springboard.hasBlankedScreen ---接到通知:com.apple.springboard.lockcomplete ---接到通知:com.apple.springboard.lockstate ---接到通知:com.apple.iokit.hid.displayStatus

當我解鎖屏幕時,會觸發

---接到通知:com.apple.springboard.hasBlanke dScreen ---接到通知:com.apple.springboard.lockstate ---接到通知:com.apple.iokit.hid.displayStatus

我不能簡單地檢測,看lockcomplete如果它是目前關閉,因爲當我試圖鎖定屏幕時,它也會觸發lockstate和displaystatus。

+0

看到這個:http://stackoverflow.com/a/14208787/3901620 – KKRocks

+0

是的,我知道這一個,並且這一個只有當用戶開/關行動時觸發。假設我的代碼連續運行,即使在後臺,我想知道是否有任何方法可以知道當前屏幕是開還是關,只是一個真/假的條件 – user6539552

回答

0

嘗試:

static void displayStatusChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) 
{ 
    CFStringRef nameCFString = (CFStringRef)name; 
    NSString *lockState = (NSString*)nameCFString; 
    NSLog(@"Darwin notification NAME = %@",name); 

    if([lockState isEqualToString:@"com.apple.springboard.lockcomplete"]) 
    { 
     NSLog(@"DEVICE LOCKED"); 
    } 
    else 
    { 
     NSLog(@"LOCK STATUS CHANGED"); 
    } 
} 

-(void)registerforDeviceLockNotification 
{ 
    //Screen lock notifications 
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center 
            NULL, // observer 
            displayStatusChanged, // callback 
            CFSTR("com.apple.springboard.lockcomplete"), // event name 
            NULL, // object 
            CFNotificationSuspensionBehaviorDeliverImmediately); 

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center 
            NULL, // observer 
            displayStatusChanged, // callback 
            CFSTR("com.apple.springboard.lockstate"), // event name 
            NULL, // object 
            CFNotificationSuspensionBehaviorDeliverImmediately); 
} 
1

這裏是簡單的解決方案

放置在viewDidLoad中的下面的代碼段時,該設備被鎖定或

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.applicationDidBecomeActive(notification:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) 

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.applicationDidEnterBackground(notification:)), 
     name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil) 

這些方法被調用解鎖

@objc func applicationDidBecomeActive(notification: NSNotification) { 
    print("Device is unlocked") 
} 

@objc func applicationDidEnterBackground(notification: NSNotification) { 
     print("Device is locked") 
} 
相關問題