iOS监听手机锁屏状态
程序员文章站
2024-02-13 09:30:34
iphone的锁屏监测分为两种方式监听:
1. 程序在前台,这种比较简单。直接使用darwin层的通知就可以了:
#import
iphone的锁屏监测分为两种方式监听:
1. 程序在前台,这种比较简单。直接使用darwin层的通知就可以了:
#import <notify.h> #define notificationlock cfstr("com.apple.springboard.lockcomplete") #define notificationchange cfstr("com.apple.springboard.lockstate") #define notificationpwdui cfstr("com.apple.springboard.hasblankedscreen") static void screenlockstatechanged(cfnotificationcenterref center,void* observer,cfstringref name,const void*object,cfdictionaryref userinfo) { nsstring* lockstate = (__bridge nsstring*)name; if ([lockstate isequaltostring:(__bridge nsstring*)notificationlock]) { nslog(@"locked."); } else { nslog(@"lock state changed."); } } - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { // override point for customization after application launch. cfnotificationcenteraddobserver(cfnotificationcentergetdarwinnotifycenter(), null, screenlockstatechanged, notificationlock, null, cfnotificationsuspensionbehaviordeliverimmediately); cfnotificationcenteraddobserver(cfnotificationcentergetdarwinnotifycenter(), null, screenlockstatechanged, notificationchange, null, cfnotificationsuspensionbehaviordeliverimmediately); //setscreenstatecb(); return yes; }
2. 第二种是程序退后台后,这时再锁屏就收不到上面的那个通知了,需要另外一种方式, 以循环的方式一直来检测是否是锁屏状态,会消耗性能并可能被苹果挂起(有可能没作用);
static void setscreenstatecb() { uint64_t locked; __block int token = 0; notify_register_dispatch("com.apple.springboard.lockstate",&token,dispatch_get_main_queue(),^(int t){ }); notify_get_state(token, &locked); nslog(@"%d",(int)locked); } - (void)applicationdidenterbackground:(uiapplication *)application { while (yes) { setscreenstatecb(); sleep(1); } }
以上所述是小编给大家介绍的ios监听手机锁屏状态,希望对大家有所帮助