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)applicationWi
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 :-)
Yes, there is no definitive method. UIApplication
has a property protectedDataAvailable which will return YES
when screen is unlocked and NO
if locked only when user enables content protection. So this is the closest but unreliable I can think of. In such case, you can even listen to UIApplicationProtectedDataDidBecomeAvailable
and UIApplicationProtectedDataWillBecomeUnavailable
notifications.
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
is only called when the screen locks, not when it unlocks.