最近公司产品中需要增加一项功能--视频录制。在录制过程中不可避免会出现一些非常规操作,例如点击Home和锁屏键时都需要终止录制并保存相关数据。这个给开发带来一定的难度。
1.监听Home键
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序,(把程序放在后台执行其他操作)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:)
name:UIApplicationDidBecomeActiveNotification object:nil]; //监听是否重新进入程序程序.(回到程序)
-(void)applicationWillResignActive:(NSNotification *)notification{
DLog("触发home按下,在该区域书写点击home键的逻辑");
}
-(void)applicationDidBecomeActive:(NSNotification *)notification{
DLog("重新进来后响应,该区域编写重新进入页面的逻辑");
}
2.监听锁屏键
(1)导入头文件和定义宏
#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 HAVehicleTravelingDataRecorderController *selfClass =nil;
(2)定义监听锁屏函数
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(@"锁屏操作");
function();
} else {
NSLog(@"lock state changed.");
// 此处监听到屏幕解锁事件(锁屏也会掉用此处一次,锁屏事件要在上面实现)
}
}
void function(){
[selfClass test];
}
- (void)test{
/*OC的相关方法写在该位置*/
}
(3)添加监听函数
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
注:函数调OC类方法会有更好的方案,后期会跟进更改一下的。