最近公司在做一个关于外接蓝牙音箱的功能,上网搜索了相关资料,发现大都雷同,今天做个稍许总结:
1.利用远程控制事件- (void)remoteControlReceivedWithEvent:(UIEvent *)event方法
这个方法系统会自动调用,可以放在AppDelegate.m文件里,也可以放在相关控制器里,前提是需要设置
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents],接收远程事件,
接收完毕后结束接收[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
接收到远程事件如播放,停止,会调用remoteControlReceivedWithEvent:方法,利用改方法里的event参数判断是什么类型的事件:
-(void)remoteControlReceivedWithEvent:(UIEvent *)event
if (event.type == UIEventTypeRemoteControl) {
if (event.subtype == UIEventSubtypeRemoteControlPlay) {
//....做一些事情.如播放
} else if(//...){
// ...
}
}
}
2.利用MPRemoteCommandCenter类
该类也会在系统接收到远程事件后被调用,前提是要添加相关事件的监听,并且该类是一个单例,如:
MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
[commandCenter.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
NSLog(@"暂停事件");
//暂停的相关事情
return MPRemoteCommandHandlerStatusSuccess;
}];
[commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
NSLog(@"播放事件");
//播放相关事情
return MPRemoteCommandHandlerStatusSuccess;
}];
在不用接收远程事件时要记的移除监听:
MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
[commandCenter.pauseCommand removeTarget:self];
[commandCenter.playCommand removeTarget:self];
网友评论