当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS监听手机锁屏状态

iOS监听手机锁屏状态

2019年07月24日  | 移动技术网移动技术  | 我要评论
iphone的锁屏监测分为两种方式监听: 1. 程序在前台,这种比较简单。直接使用darwin层的通知就可以了: #import <notify.h>

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监听手机锁屏状态,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网