Alex Rivera | Logout

Detect if iPhone screen is on/off

Asked 2011-05-24T17:52:03.927
11

Is there any way to detect if an iPhone's screen is on or off? For example, when the phone's screen lock button is pressed.

I've been using (void)applicationWillResignActive:(UIApplication *)application; to prepare for such events (which works fine for the most part), but this method is also fired for incoming calls, texts, etc.

As far as I can tell, there is no documented method to determine this.

I've been playing with some workarounds, like checking if screen resolution changed, checking if the orientation is unknown, or getting the brightness of the device. Nothing has panned out yet.

Does anyone have any creative/workaround solutions for this?

Edit
Report

2 Answers

2

You can use Darwin notifications, to listen for the events. I'm not 100% sure, but it looks to me, from running on a jailbroken iOS 5.0.1 iPhone 4, that one of these events might be what you need:

com.apple.iokit.hid.displayStatus
com.apple.springboard.hasBlankedScreen
com.apple.springboard.lockstate

Note: according to the poster's comments to a similar question I answered here, this should work on a non-jailbroken phone, too.

To use this, register for the event like this (this registers for just one event, but if that doesn't work for you, try the other two):

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                NULL, // observer
                                displayStatusChanged, // callback
                                CFSTR("com.apple.iokit.hid.displayStatus"), // event name
                                NULL, // object
                                CFNotificationSuspensionBehaviorDeliverImmediately);

where displayStatusChanged is your event callback:

static void displayStatusChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    NSLog(@"event received!");
    // you might try inspecting the `userInfo` dictionary, to see 
    //  if it contains any useful info
    if (userInfo != nil) {
        CFShow(userInfo);
    }
}

I believe the events I listed above get triggered when the screen is both turned on and off, locked and unlocked. You may need to track the state yourself. Also,

com.apple.springboard.lockcomplete
<
answered 2013-01-08T11:17:42.627
1

Try this workaround. Author claims that it works well on 4.2

I have checked it on iOS 3.1 (iPhone 3G) - works well.

update: Doesn't work on iOS 5 beta 7 (iPod Touch 4G) :-(

update2: app go to background when screen locked, thus solution is kinda working on iOS 5 beta 7 :-)

answered 2011-09-23T15:26:38.577

Your Answer