detect if phone screen is on/off in iOS -
i have requirement in application detect if phone screen on/off when application in background? found can possible using private framework spring board. can public apis?
thank.
try this:
in appdelegate.m
- (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { //other code [self registerfordevicelocknotif]; } //register notification -(void)registerfordevicelocknotif { //screen screendisplaystatus notifications cfnotificationcenteraddobserver(cfnotificationcentergetdarwinnotifycenter(), null, screendisplaystatus, cfstr("com.apple.iokit.hid.displaystatus"), null, cfnotificationsuspensionbehaviordeliverimmediately); cfnotificationcenteraddobserver(cfnotificationcentergetdarwinnotifycenter(), //center null, // observer screenlockstatus, // callback cfstr("com.apple.springboard.lockstate"), // event name null, // object cfnotificationsuspensionbehaviordeliverimmediately); } //removenotification if don't need more. -(void)removefordevicelocknotif{ cfnotificationcenterremoveobserver(cfnotificationcentergetdarwinnotifycenter(), null, cfstr("com.apple.iokit.hid.displaystatus"), null); cfnotificationcenterremoveobserver(cfnotificationcentergetdarwinnotifycenter(), null, cfstr("com.apple.springboard.lockstate"), null); } //call methods static void screendisplaystatus(cfnotificationcenterref center, void* observer, cfstringref name, const void* object, cfdictionaryref userinfo) { uint64_t state; int token; notify_register_check("com.apple.iokit.hid.displaystatus", &token); notify_get_state(token, &state); notify_cancel(token); if (state) { screenisblack = no; }else{ screenisblack = yes; } } static void screenlockstatus(cfnotificationcenterref center, void* observer, cfstringref name, const void* object, cfdictionaryref userinfo) { uint64_t state; int token; notify_register_check("com.apple.springboard.lockstate", &token); notify_get_state(token, &state); notify_cancel(token); if (state) { screenislocked = yes; } else { screenislocked = no; } }
do task when screen black screen:
if (appisbackground && (screenisblack || screenislocked) { //do task. }
note that, here have made screen lock status screen black, if need not, remove lock status judgement.
Comments
Post a Comment