【iOS Tips】锁屏/解锁事件监听的优化

本文介绍如何使用Objective-C在iOS应用中监测设备的锁屏和解锁事件。通过注册特定的通知并实现回调函数来更新应用状态,确保相关事件只被处理一次。

定义两个宏: 

//监听锁屏事件
#define kNotificationLock CFSTR("com.apple.springboard.lockcomplete")
//监听屏幕状态变化事件
#define kNotificationChange CFSTR("com.apple.springboard.lockstate")

注册达尔文通知:

注意此处CFNotificationCenterAddObserver() 为C的函数,其第三个参数需要传一个回调函数

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    //监听锁屏事件
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, kNotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    //监听屏幕状态变化事件
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, kNotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);

    return YES;
}

定义一个全局变量stateChaned,用来判断屏幕变化的状态

@property (nonatomic, assign)BOOL stateChanged;

定义AppDelegate的单例,以便在回调函数中调用stateChanged

//定义AppDelegate单例
+ (AppDelegate *)sharedDelegate{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
    
}

实现通知回调函数:

static void screenLockStateChanged(CFNotificationCenterRef center,void* observer,CFStringRef name,const void* object,CFDictionaryRef userInfo){
    
    NSString* lockstate = (__bridge NSString*)name;
    if ([lockstate isEqualToString:(__bridge  NSString*)kNotificationLock]) {
        [AppDelegate sharedDelegate].stateChanged = YES;
        NSLog(@"锁屏");
    }
    else{
        if ([AppDelegate sharedDelegate].stateChanged) {
            [AppDelegate sharedDelegate].stateChanged = NO;
        }else{
            NSLog(@"解锁");
        }
    }
    
}

运行效果:

Perfect! 锁屏 解锁只会打印一次。

190047_3hZk_2279344.png

这样把你的锁屏、解锁时触发的代码放在其中就可以了!

转载于:https://my.oschina.net/Misayalvyuan/blog/896199

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值