Detect screen on/off from iOS service

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:

Update: also, the following notification is posted when the phone locks (but not when it unlocks):

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 others):

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                NULL, // observer
                                displayStatusChanged, // callback
                                CFSTR(""), // event name
                                NULL, // object

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) {

If you really want this code to run in the background as a service, and you’re jailbroken, I would recommend looking into iOS Launch Daemons. As opposed to an app that you simply let run in the background, a launch daemon can start automatically after a reboot, and you don’t have to worry about iOS rules for apps running tasks in the background.

Let us know how this works!

Leave a Comment