I would like to have my app monitor when phone becomes locked and unlocked, as well as when it turns blank (after longer inactivity), all this while my app is not focused, but running in the background.
I can receive lock/unlock/blank events with ease while app is focused:
-(void) startListeningForPhoneLockEvent
{
NSLog(@"Start listening to lock/unlock and screen-goes-black events.");
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
(void*)self,
lockStateChanged,
CFSTR("com.apple.springboard.lockstate"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
(void*)self,
hasBlankedScreen,
CFSTR("com.apple.springboard.hasBlankedScreen"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
}
And callback functions:
static void lockStateChanged( CFNotificationCenterRef center, void*observer, CFStringRef name, const void *object, CFDictionaryRef userInfo )
{
NSLog(@"Lock event received!");
}
static void hasBlankedScreen( CFNotificationCenterRef center, void*observer, CFStringRef name, const void *object, CFDictionaryRef userInfo )
{
NSLog(@"Blanked screen event received!");
}
I've enabled background mode:
- Background fetch.
However, once app goes into background, it does not receive lock/unlock/blank screen events.
I've tried with other background modes, such as sound playback, location updates etc. but app is still not receiving lock/unlock/blank screen events when in background.
I'm not sure if this is actually possible, or if I am doing something wrong.
I'm testing it on real device that is updated to iOS9, using latest XCode with iOS9 SDK.